PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Format: index ZIP entries by name and use crc32fast (#3474) (#3488)
Valentin Klein35b5b8ceb04d
diff --git a/Cargo.lock b/Cargo.lockindex 34f537eb4..dceb5602e 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4383,6 +4383,7 @@ name = "photocraft-format"version = "0.7.0"dependencies = ["blake3",+ "crc32fast","flate2","photocraft-codecs","photocraft-color",diff --git a/crates/format/Cargo.toml b/crates/format/Cargo.tomlindex f29ccf867..00a41ac07 100644--- a/crates/format/Cargo.toml+++ b/crates/format/Cargo.toml@@ -19,6 +19,8 @@ serde = { workspace = true }serde_json = { workspace = true, features = ["unbounded_depth"] }thiserror = { workspace = true }flate2 = { workspace = true }+# Same IEEE CRC-32 the ZIP container needs; already in Cargo.lock through flate2.+crc32fast = "1.5"blake3 = { version = "1.8", default-features = false, features = ["pure"] }ruzstd = "0.9"diff --git a/crates/format/src/zip.rs b/crates/format/src/zip.rsindex aec3a7adc..1e296e16d 100644--- a/crates/format/src/zip.rs+++ b/crates/format/src/zip.rs@@ -3,6 +3,7 @@//! unzipped and re-zipped by another tool still loads). No ZIP64, no//! encryption, no multi-disk archives.+use std::collections::HashMap;use std::io::Read;use crate::FormatError;@@ -11,25 +12,9 @@ const LOCAL_SIG: u32 = 0x0403_4b50;const CENTRAL_SIG: u32 = 0x0201_4b50;const EOCD_SIG: u32 = 0x0605_4b50;-/// CRC-32 (IEEE), table-driven.+/// CRC-32 (IEEE), as stored in ZIP headers.pub fn crc32(data: &[u8]) -> u32 {- static TABLE: std::sync::OnceLock<[u32; 256]> = std::sync::OnceLock::new();- let t = TABLE.get_or_init(|| {- let mut t = [0u32; 256];- for (i, e) in t.iter_mut().enumerate() {- let mut c = i as u32;- for _ in 0..8 {- c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 };- }- *e = c;- }- t- });- let mut c = 0xFFFF_FFFFu32;- for &b in data {- c = t[((c ^ b as u32) & 0xFF) as usize] ^ (c >> 8);- }- !c+ crc32fast::hash(data)}/// Streaming writer for STORE entries.@@ -122,7 +107,12 @@ pub struct Entry {/// Read-only view of an archive in memory.pub struct ZipReader<'a> {bytes: &'a [u8],+ /// All entries, in central-directory order. Treat as read-only: `find`+ /// looks names up through an index built from this list in `new`.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>,}fn u16_at(b: &[u8], o: usize) -> Result<u16, FormatError> {@@ -194,11 +184,16 @@ impl<'a> ZipReader<'a> {entries.push(Entry { name, method, crc, compressed, uncompressed, data_offset });p = entry_end;}- Ok(ZipReader { bytes, entries })+ 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 })}pub fn find(&self, name: &str) -> Option<&Entry> {- self.entries.iter().find(|e| e.name == name)+ self.by_name.get(name).and_then(|&i| self.entries.get(i))}/// Entry payload (decompressed), at most `max` bytes, CRC-checked.@@ -263,6 +258,59 @@ mod tests {assert!(matches!(r.read_by_name("a.txt", 3), Err(FormatError::LimitExceeded(_))));}+ #[test]+ fn crc_matches_bitwise_reference() {+ // Bit-at-a-time IEEE CRC-32 as the oracle, over lengths that cross+ // any SIMD / slicing block size.+ fn reference(data: &[u8]) -> u32 {+ let mut c = 0xFFFF_FFFFu32;+ for &b in data {+ c ^= u32::from(b);+ for _ in 0..8 {+ c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 };+ }+ }+ !c+ }+ let data: Vec<u8> = (0..1000u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8).collect();+ for len in [0, 1, 7, 15, 16, 17, 63, 64, 65, 255, 256, 1000] {+ assert_eq!(crc32(&data[..len]), reference(&data[..len]), "len {len}");+ }+ }++ #[test]+ fn find_locates_every_entry_in_a_large_archive() {+ let mut w = ZipWriter::new();+ let n = 3000u32;+ for i in 0..n {+ w.add(&format!("tiles/{i:05}.zst"), &i.to_le_bytes()).unwrap();+ }+ let bytes = w.finish().unwrap();+ let r = ZipReader::new(&bytes).unwrap();+ assert_eq!(r.entries.len(), n as usize);+ for i in (0..n).rev() {+ let name = format!("tiles/{i:05}.zst");+ let e = r.find(&name).unwrap();+ assert_eq!(e.name, name);+ assert_eq!(r.read(e, 4).unwrap(), i.to_le_bytes());+ }+ assert!(r.find("tiles/missing.zst").is_none());+ assert!(r.find("").is_none());+ }++ #[test]+ fn duplicate_names_resolve_to_the_first_entry() {+ let mut w = ZipWriter::new();+ w.add("a", b"first").unwrap();+ w.add("b", b"other").unwrap();+ w.add("a", b"second").unwrap();+ let bytes = w.finish().unwrap();+ let r = ZipReader::new(&bytes).unwrap();+ assert_eq!(r.entries.len(), 3);+ assert_eq!(r.read_by_name("a", 100).unwrap(), b"first");+ assert_eq!(r.read_by_name("b", 100).unwrap(), b"other");+ }+#[test]fn crc_mismatch_detected() {let mut w = ZipWriter::new();