mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-03 06:31:42 +01:00
perf(format): reduce ZIP archive allocations
Reserve complete bundles and directories from compressed sizes, and borrow UTF-8 entry paths in the lookup index. Preserve lossy names and first-entry lookup for duplicates. Check ZIP field lengths before writing, bound metadata reservations, and cover byte equivalence, overflow and incremental saves. ZIP entry paths have a format limit independent of filesystem path constraints.
This commit is contained in:
4 files changed
+115
-24
No files matched your search
@@ -771,15 +771,21 @@ impl PcraftWriter {
|
||||
pub fn save_zip(&mut self, doc: &Document, opts: &SaveOptions) -> Result<(Vec<u8>, SaveStats)> {
|
||||
let p = self.prepare(doc, opts)?;
|
||||
let mut stats = p.stats;
|
||||
let mut z = ZipWriter::new();
|
||||
z.add(MANIFEST, &p.manifest)?;
|
||||
for (name, data) in &p.previews {
|
||||
z.add(name, data)?;
|
||||
}
|
||||
let mut next = HashMap::with_capacity(p.objects.len());
|
||||
// New objects are compressed on all cores first (zstd dominates a full save).
|
||||
let todo: Vec<(&String, &Object)> = p.objects.iter().filter(|(path, _)| !self.compressed.contains_key(*path)).collect();
|
||||
let mut fresh: HashMap<&String, Arc<Vec<u8>>> = par_compress(&todo)?.into_iter().collect();
|
||||
let entries = std::iter::once((MANIFEST, p.manifest.len())).chain(p.previews.iter().map(|(name, data)| (*name, data.len()))).chain(
|
||||
p.objects.keys().map(|path| {
|
||||
let size = self.compressed.get(path).or_else(|| fresh.get(path)).map_or(0, |data| data.len());
|
||||
(path.as_str(), size)
|
||||
}),
|
||||
);
|
||||
let mut z = ZipWriter::with_entries(entries)?;
|
||||
z.add(MANIFEST, &p.manifest)?;
|
||||
for (name, data) in &p.previews {
|
||||
z.add(name, data)?;
|
||||
}
|
||||
for (path, obj) in &p.objects {
|
||||
let data = match self.compressed.get(path) {
|
||||
Some(d) => {
|
||||
|
||||
+95
-15
@@ -3,6 +3,7 @@
|
||||
//! unzipped and re-zipped by another tool still loads). No ZIP64, no
|
||||
//! encryption, no multi-disk archives.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use std::io::Read;
|
||||
|
||||
@@ -31,18 +32,41 @@ impl Default for ZipWriter {
|
||||
}
|
||||
|
||||
impl ZipWriter {
|
||||
/// Creates an empty archive of STORE entries.
|
||||
pub fn new() -> Self {
|
||||
ZipWriter { out: Vec::new(), central: Vec::new(), count: 0 }
|
||||
}
|
||||
|
||||
/// Reserves the complete archive from its entry names and payload sizes.
|
||||
pub(crate) fn with_entries<'a>(entries: impl IntoIterator<Item = (&'a str, usize)>) -> Result<Self, FormatError> {
|
||||
let (size, directory) = entries.into_iter().try_fold((22usize, 0usize), |(size, directory), (name, bytes)| {
|
||||
let directory = directory.checked_add(46 + name.len());
|
||||
let size = size.checked_add(76).and_then(|n| n.checked_add(name.len())).and_then(|n| n.checked_add(name.len())).and_then(|n| n.checked_add(bytes));
|
||||
size.zip(directory).ok_or_else(|| FormatError::Unsupported("zip size overflow".into()))
|
||||
})?;
|
||||
let mut writer = Self::new();
|
||||
writer.out.try_reserve_exact(size).map_err(|_| FormatError::LimitExceeded("not enough memory for zip".into()))?;
|
||||
writer.central.try_reserve_exact(directory).map_err(|_| FormatError::LimitExceeded("not enough memory for zip directory".into()))?;
|
||||
Ok(writer)
|
||||
}
|
||||
|
||||
/// Adds a STORE entry, rejecting names or data that exceed ZIP field limits.
|
||||
/// The entry path has a 16-bit byte length, independent of filesystem limits.
|
||||
pub fn add(&mut self, name: &str, data: &[u8]) -> Result<(), FormatError> {
|
||||
if self.count == u16::MAX {
|
||||
return Err(FormatError::Unsupported("more than 65535 zip entries (ZIP64 not supported)".into()));
|
||||
}
|
||||
let size = u32::try_from(data.len()).map_err(|_| FormatError::Unsupported("zip entry over 4 GiB".into()))?;
|
||||
let offset = u32::try_from(self.out.len()).map_err(|_| FormatError::Unsupported("zip over 4 GiB".into()))?;
|
||||
let crc = crc32(data);
|
||||
let name_b = name.as_bytes();
|
||||
let name_len = u16::try_from(name_b.len()).map_err(|_| FormatError::Unsupported("zip entry path exceeds the 65535-byte format limit".into()))?;
|
||||
let local_len = 30usize
|
||||
.checked_add(name_b.len())
|
||||
.and_then(|n| n.checked_add(data.len()))
|
||||
.ok_or_else(|| FormatError::Unsupported("zip entry size overflow".into()))?;
|
||||
self.out.try_reserve(local_len).map_err(|_| FormatError::LimitExceeded("not enough memory for zip entry".into()))?;
|
||||
self.central.try_reserve(46 + name_b.len()).map_err(|_| FormatError::LimitExceeded("not enough memory for zip directory".into()))?;
|
||||
let crc = crc32(data);
|
||||
// Local file header.
|
||||
let o = &mut self.out;
|
||||
o.extend_from_slice(&LOCAL_SIG.to_le_bytes());
|
||||
@@ -54,7 +78,7 @@ impl ZipWriter {
|
||||
o.extend_from_slice(&crc.to_le_bytes());
|
||||
o.extend_from_slice(&size.to_le_bytes());
|
||||
o.extend_from_slice(&size.to_le_bytes());
|
||||
o.extend_from_slice(&(name_b.len() as u16).to_le_bytes());
|
||||
o.extend_from_slice(&name_len.to_le_bytes());
|
||||
o.extend_from_slice(&0u16.to_le_bytes());
|
||||
o.extend_from_slice(name_b);
|
||||
o.extend_from_slice(data);
|
||||
@@ -70,7 +94,7 @@ impl ZipWriter {
|
||||
c.extend_from_slice(&crc.to_le_bytes());
|
||||
c.extend_from_slice(&size.to_le_bytes());
|
||||
c.extend_from_slice(&size.to_le_bytes());
|
||||
c.extend_from_slice(&(name_b.len() as u16).to_le_bytes());
|
||||
c.extend_from_slice(&name_len.to_le_bytes());
|
||||
c.extend_from_slice(&[0; 8]); // extra len, comment len, disk, internal attrs
|
||||
c.extend_from_slice(&0u32.to_le_bytes()); // external attrs
|
||||
c.extend_from_slice(&offset.to_le_bytes());
|
||||
@@ -79,9 +103,11 @@ impl ZipWriter {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Appends the central directory and returns the complete archive.
|
||||
pub fn finish(mut self) -> Result<Vec<u8>, FormatError> {
|
||||
let cd_offset = u32::try_from(self.out.len()).map_err(|_| FormatError::Unsupported("zip over 4 GiB".into()))?;
|
||||
let cd_size = self.central.len() as u32;
|
||||
let cd_size = u32::try_from(self.central.len()).map_err(|_| FormatError::Unsupported("zip directory over 4 GiB".into()))?;
|
||||
self.out.try_reserve(self.central.len().saturating_add(22)).map_err(|_| FormatError::LimitExceeded("not enough memory to finish zip".into()))?;
|
||||
self.out.extend_from_slice(&self.central);
|
||||
self.out.extend_from_slice(&EOCD_SIG.to_le_bytes());
|
||||
self.out.extend_from_slice(&[0; 4]); // disk numbers
|
||||
@@ -112,7 +138,7 @@ pub struct ZipReader<'a> {
|
||||
pub entries: Vec<Entry>,
|
||||
/// Name -> index of the first entry with that name, so `find` is O(1)
|
||||
/// instead of a scan per lookup (a bundle reads one entry per tile).
|
||||
by_name: HashMap<String, usize>,
|
||||
by_name: HashMap<Cow<'a, str>, usize>,
|
||||
}
|
||||
|
||||
fn u16_at(b: &[u8], o: usize) -> Result<u16, FormatError> {
|
||||
@@ -123,6 +149,7 @@ fn u32_at(b: &[u8], o: usize) -> Result<u32, FormatError> {
|
||||
}
|
||||
|
||||
impl<'a> ZipReader<'a> {
|
||||
/// Checks ZIP record bounds and indexes the first entry for each name.
|
||||
pub fn new(bytes: &'a [u8]) -> Result<Self, FormatError> {
|
||||
if bytes.len() < 22 {
|
||||
return Err(FormatError::corrupt("not a zip archive (too short)"));
|
||||
@@ -137,7 +164,8 @@ impl<'a> ZipReader<'a> {
|
||||
let cd_size = u32_at(bytes, eocd + 12)? as usize;
|
||||
let cd_off = u32_at(bytes, eocd + 16)? as usize;
|
||||
let cd_end = cd_off.checked_add(cd_size).filter(|end| *end <= eocd).ok_or_else(|| FormatError::corrupt("zip central directory out of range"))?;
|
||||
let mut entries = Vec::with_capacity(count.min(bytes.len() / 46));
|
||||
let mut entries = Vec::with_capacity(count.min(cd_size / 46));
|
||||
let mut by_name = HashMap::with_capacity(entries.capacity());
|
||||
let mut p = cd_off;
|
||||
for _ in 0..count {
|
||||
let header_end = p.checked_add(46).filter(|end| *end <= cd_end).ok_or_else(|| FormatError::corrupt("truncated zip central directory entry"))?;
|
||||
@@ -155,7 +183,7 @@ impl<'a> ZipReader<'a> {
|
||||
let local = u32_at(bytes, p + 42)? as usize;
|
||||
let name_end = header_end.checked_add(nlen).filter(|end| *end <= cd_end).ok_or_else(|| FormatError::corrupt("zip entry name out of range"))?;
|
||||
let name = bytes.get(header_end..name_end).ok_or_else(|| FormatError::corrupt("truncated zip name"))?;
|
||||
let name = String::from_utf8_lossy(name).into_owned();
|
||||
let name = String::from_utf8_lossy(name);
|
||||
if flags & 1 != 0 {
|
||||
return Err(FormatError::Unsupported("encrypted zip entries".into()));
|
||||
}
|
||||
@@ -181,14 +209,11 @@ impl<'a> ZipReader<'a> {
|
||||
if data_offset.checked_add(compressed).is_none_or(|end| end > bytes.len()) {
|
||||
return Err(FormatError::corrupt(format!("zip entry `{name}` out of range")));
|
||||
}
|
||||
entries.push(Entry { name, method, crc, compressed, uncompressed, data_offset });
|
||||
// The index borrows valid UTF-8 names; duplicate names keep the first entry.
|
||||
by_name.entry(name.clone()).or_insert(entries.len());
|
||||
entries.push(Entry { name: name.into_owned(), method, crc, compressed, uncompressed, data_offset });
|
||||
p = entry_end;
|
||||
}
|
||||
let mut by_name = HashMap::with_capacity(entries.len());
|
||||
for (i, e) in entries.iter().enumerate() {
|
||||
// Duplicate names: the first entry wins, as with a front-to-back scan.
|
||||
by_name.entry(e.name.clone()).or_insert(i);
|
||||
}
|
||||
Ok(ZipReader { bytes, entries, by_name })
|
||||
}
|
||||
|
||||
@@ -249,6 +274,20 @@ mod tests {
|
||||
assert_eq!(crc32(b"123456789"), 0xCBF4_3926);
|
||||
}
|
||||
|
||||
/// ZIP entry paths have a format limit even when each component is short.
|
||||
#[test]
|
||||
fn entry_path_length_is_checked_before_writing() {
|
||||
let mut writer = ZipWriter::new();
|
||||
for name in ["dir/".repeat(16384), "é/".repeat(21846)] {
|
||||
assert!(matches!(writer.add(&name, b"invalid"), Err(FormatError::Unsupported(_))));
|
||||
assert!(writer.out.is_empty() && writer.central.is_empty());
|
||||
}
|
||||
let name = "dir/".repeat(16383) + "end";
|
||||
writer.add(&name, b"valid").unwrap();
|
||||
let bytes = writer.finish().unwrap();
|
||||
assert_eq!(ZipReader::new(&bytes).unwrap().read_by_name(&name, 5).unwrap(), b"valid");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip() {
|
||||
let mut w = ZipWriter::new();
|
||||
@@ -262,6 +301,7 @@ mod tests {
|
||||
assert_eq!(r.read_by_name("dir/b.bin", 100).unwrap(), [0, 1, 2, 3]);
|
||||
assert!(r.read_by_name("empty", 0).unwrap().is_empty());
|
||||
assert!(matches!(r.read_by_name("a.txt", 3), Err(FormatError::LimitExceeded(_))));
|
||||
assert!(r.by_name.keys().all(|name| matches!(name, Cow::Borrowed(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -317,6 +357,46 @@ mod tests {
|
||||
assert_eq!(r.read_by_name("b", 100).unwrap(), b"other");
|
||||
}
|
||||
|
||||
/// Reservation changes neither entry bytes nor final output, and avoids growth.
|
||||
#[test]
|
||||
fn whole_archive_reservation_preserves_output() {
|
||||
let entries = [("层/é.png", &b"image"[..]), ("empty", &b""[..]), ("empty", &b"duplicate"[..])];
|
||||
for entries in [&entries[..0], &entries[..]] {
|
||||
let mut previous = ZipWriter::new();
|
||||
let mut reserved = ZipWriter::with_entries(entries.iter().map(|(name, data)| (*name, data.len()))).unwrap();
|
||||
let (capacity, directory) = (reserved.out.capacity(), reserved.central.capacity());
|
||||
for (name, data) in entries {
|
||||
previous.add(name, data).unwrap();
|
||||
reserved.add(name, data).unwrap();
|
||||
}
|
||||
assert_eq!(reserved.central.capacity(), directory);
|
||||
let bytes = reserved.finish().unwrap();
|
||||
assert_eq!(bytes.capacity(), capacity);
|
||||
assert_eq!(bytes, previous.finish().unwrap());
|
||||
}
|
||||
assert!(matches!(ZipWriter::with_entries([("x", usize::MAX)]), Err(FormatError::Unsupported(_))));
|
||||
assert!(matches!(ZipWriter::with_entries([("x", isize::MAX as usize)]), Err(FormatError::LimitExceeded(_))));
|
||||
}
|
||||
|
||||
/// Invalid UTF-8 names retain their lossy spelling and first-entry lookup.
|
||||
#[test]
|
||||
fn name_index_borrows_unicode_and_owns_lossy_names() {
|
||||
let mut writer = ZipWriter::new();
|
||||
for name in ["层/é.png", "a", "b"] {
|
||||
writer.add(name, name.as_bytes()).unwrap();
|
||||
}
|
||||
let mut bytes = writer.finish().unwrap();
|
||||
let mut p = u32_at(&bytes, bytes.len() - 6).unwrap() as usize;
|
||||
p += 46 + "层/é.png".len();
|
||||
bytes[p + 46] = 0xff;
|
||||
bytes[p + 47 + 46] = 0xfe;
|
||||
let reader = ZipReader::new(&bytes).unwrap();
|
||||
assert_eq!(reader.read_by_name("层/é.png", 100).unwrap(), "层/é.png".as_bytes());
|
||||
assert!(matches!(reader.by_name.get_key_value("层/é.png").unwrap().0, Cow::Borrowed(_)));
|
||||
assert!(matches!(reader.by_name.get_key_value("�").unwrap().0, Cow::Owned(_)));
|
||||
assert_eq!(reader.read_by_name("�", 1).unwrap(), b"a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crc_mismatch_detected() {
|
||||
let mut w = ZipWriter::new();
|
||||
@@ -359,8 +439,8 @@ mod tests {
|
||||
/// A false small size must stop expansion before decoding the rest of the stream.
|
||||
#[test]
|
||||
fn deflate_surplus_stops_before_a_corrupt_suffix() {
|
||||
// Non-final stored block, then an invalid block type after its payload.
|
||||
let raw = [&[0, 32, 0, 0xdf, 0xff][..], &[b'x'; 32], &[7]].concat();
|
||||
// Exceed miniz's internal 32 KiB output buffer before the corrupt block.
|
||||
let raw = [&[0, 0xff, 0xff, 0, 0][..], &[b'x'; 65535], &[7]].concat();
|
||||
let reader = ZipReader { bytes: &raw, entries: Vec::new(), by_name: HashMap::new() };
|
||||
for declared in [0, 7] {
|
||||
let entry = Entry { name: "surplus".into(), method: 8, crc: 0, compressed: raw.len(), uncompressed: declared, data_offset: 0 };
|
||||
|
||||
@@ -217,10 +217,11 @@ fn exhausted_document_ids_and_maximal_text_runs_roundtrip() {
|
||||
fn zip_incremental_only_new_tiles() {
|
||||
let mut doc = rich_doc(ColorMode::Rgb, SampleType::U16);
|
||||
let mut w = PcraftWriter::new();
|
||||
let (_, s1) = w.save_zip(&doc, &SaveOptions::default()).unwrap();
|
||||
let (first, s1) = w.save_zip(&doc, &SaveOptions::default()).unwrap();
|
||||
assert!(s1.tiles_total > 5);
|
||||
assert_eq!(s1.tiles_written, s1.tiles_total);
|
||||
let (_, s2) = w.save_zip(&doc, &SaveOptions::default()).unwrap();
|
||||
let (cached, s2) = w.save_zip(&doc, &SaveOptions::default()).unwrap();
|
||||
assert_eq!(first, cached);
|
||||
assert_eq!(s2.tiles_written, 0);
|
||||
assert_eq!(s2.tiles_reused, s2.tiles_total);
|
||||
assert_eq!(s2.blobs_written, 0);
|
||||
@@ -230,6 +231,7 @@ fn zip_incremental_only_new_tiles() {
|
||||
let (bytes, s3) = w.save_zip(&doc, &SaveOptions::default()).unwrap();
|
||||
assert_eq!(s3.tiles_written, 1);
|
||||
assert_eq!(load_from_bytes(&bytes).unwrap(), doc);
|
||||
assert_eq!(bytes, PcraftWriter::new().save_zip(&doc, &SaveOptions::default()).unwrap().0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -8,8 +8,7 @@ The small web-layout PNG grows by 598 bytes (+1.40%). One .pcraft preview adds 2
|
||||
Real photo PNGs become smaller and encode faster. Compression levels are unchanged.
|
||||
There is no native-format tile speedup from deflate.
|
||||
|
||||
These timings measure the backend switch before the ZIP input-buffer removal and output-size guard.
|
||||
Neither ZIP change was benchmarked.
|
||||
The timings below measure only the backend switch. They exclude the later ZIP allocation and validation changes.
|
||||
|
||||
Measured on 2026-10-19 against main `d95fdf31`, independently of the other performance changes.
|
||||
Host: Apple M4 Max, 16 CPUs, 128 GiB RAM, macOS arm64, rustc 1.99.1.
|
||||
@@ -72,6 +71,10 @@ The shared harness times in-memory operations. Input loading, image conversion,
|
||||
|
||||
Every PNG encode decodes to identical source pixels, each PSD operation produces the same decoded layer/mask samples as main, and complete .pcraft documents compare equal at every depth. Compressed bytes may differ. The committed compatibility test independently inflates PNG IDAT and PSD ZIP/ZIP-prediction data using old miniz_oxide and checks .pcraft tiles plus thumbnails.
|
||||
|
||||
## Allocation and validation changes
|
||||
|
||||
ZIP lookup keys borrow valid UTF-8 entry paths, avoiding a second string allocation per entry. Invalid names keep their previous lossy spelling and duplicate-name lookup still selects the first entry. The bundle writer reserves the complete archive after compression, including its central directory. It rejects entry paths that exceed ZIP's 65,535-byte field before writing and checks that the central-directory size fits its ZIP field. These archive paths are independent of filesystem path limits.
|
||||
|
||||
## Linux and Windows x86-64 validation
|
||||
|
||||
[GitHub Actions run](https://github.com/reneleonhardt/photocraft/actions/runs/39444647224) passed the deflate compatibility test,
|
||||
|
||||
Reference in new issue
Block a user