Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

perf(format): Reuse Rust Zstandard workspaces

Rene Leonhardt02a63c94c2d4
diff --git a/crates/format/src/store.rs b/crates/format/src/store.rs
index 7da5dd6b5..96647d096 100644
--- a/crates/format/src/store.rs
+++ b/crates/format/src/store.rs
@@ -26,9 +26,7 @@ fn blob_path(h: &str) -> String {
format!("blobs/{h}.zst")
}
-fn compress(data: &[u8]) -> Vec<u8> {
- ruzstd::encoding::compress_to_vec(data, ruzstd::encoding::CompressionLevel::Fastest)
-}
+type Compressor<'a> = ruzstd::encoding::FrameCompressor<std::io::Cursor<std::borrow::Cow<'a, [u8]>>, Vec<u8>, ruzstd::encoding::MatchGeneratorDriver>;
/// Decodes a zstd frame of at most `max` bytes (`LimitExceeded` beyond). With `exact`, the
/// decoded length must be exactly that (`Corrupt` otherwise).
@@ -416,8 +414,16 @@ enum Object {
}
impl Object {
- fn compressed(&self) -> Vec<u8> {
- compress(&self.content())
+ fn compressed<'a>(&'a self, compressor: &mut Compressor<'a>) -> Vec<u8> {
+ let bytes = self.content();
+ // ruzstd's pooled suffix tables retain the first block's size.
+ if !bytes.len().is_multiple_of(128 << 10) {
+ return ruzstd::encoding::compress_to_vec(bytes.as_ref(), ruzstd::encoding::CompressionLevel::Fastest);
+ }
+ compressor.set_source(std::io::Cursor::new(bytes));
+ compressor.set_drain(Vec::new());
+ compressor.compress();
+ compressor.set_drain(Vec::new()).unwrap_or_default()
}
/// The bytes this object stores (tiles little-endian).
@@ -689,18 +695,20 @@ type Compressed<'a> = (&'a String, Arc<Vec<u8>>);
fn par_compress<'a>(objects: &[(&'a String, &'a Object)]) -> Result<Vec<Compressed<'a>>> {
let threads = if cfg!(target_arch = "wasm32") { 1 } else { std::thread::available_parallelism().map_or(1, |n| n.get()).clamp(1, 32) };
if threads < 2 || objects.len() < 2 {
- return Ok(objects.iter().map(|(p, o)| (*p, Arc::new(o.compressed()))).collect());
+ let mut compressor = Compressor::new(ruzstd::encoding::CompressionLevel::Fastest);
+ return Ok(objects.iter().map(|(p, o)| (*p, Arc::new(o.compressed(&mut compressor)))).collect());
}
let next = std::sync::atomic::AtomicUsize::new(0);
std::thread::scope(|sc| {
let hs: Vec<_> = (0..threads.min(objects.len()))
.map(|_| {
sc.spawn(|| {
+ let mut compressor = Compressor::new(ruzstd::encoding::CompressionLevel::Fastest);
let mut out = Vec::new();
loop {
let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let Some((p, o)) = objects.get(i) else { break };
- out.push((*p, Arc::new(o.compressed())));
+ out.push((*p, Arc::new(o.compressed(&mut compressor))));
}
out
})
@@ -793,7 +801,7 @@ impl PcraftWriter {
Object::Tile(..) => stats.tiles_written += 1,
Object::Blob(_) => stats.blobs_written += 1,
}
- fresh.remove(path).unwrap_or_else(|| Arc::new(obj.compressed()))
+ fresh.remove(path).unwrap_or_else(|| Arc::new(obj.compressed(&mut Compressor::new(ruzstd::encoding::CompressionLevel::Fastest))))
}
};
z.add(path, &data)?;
@@ -828,6 +836,7 @@ impl PcraftWriter {
None => 0,
};
let recheck = self.rolling_recheck(&p.objects);
+ let mut compressor = Compressor::new(ruzstd::encoding::CompressionLevel::Fastest);
for (path, obj) in &p.objects {
let object_path = dir.join(path);
// bundle_root and list_objects validated the fixed parent directories once. Check
@@ -862,7 +871,7 @@ impl PcraftWriter {
Object::Tile(..) => stats.tiles_written += 1,
Object::Blob(_) => stats.blobs_written += 1,
}
- write_bundle_file(dir, &object_path, &obj.compressed())?;
+ write_bundle_file(dir, &object_path, &obj.compressed(&mut compressor))?;
let written = path_signature(&object_path)?;
if let Some(cache) = &mut self.verified_directory {
match written {
@@ -1011,3 +1020,53 @@ pub(crate) fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
crate::atomic::atomic_write(path, data)?;
Ok(())
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ #[ignore = "manual 24 MP RGBA8-equivalent release benchmark"]
+ fn benchmark_workspace_reuse() {
+ use std::{hint::black_box, time::Instant};
+ let data: Vec<_> = (0..367).map(|seed| Arc::new((0..262_144).map(|i| ((i * 37 + i / 97 + seed * 13) % 251) as u8).collect())).collect();
+ let objects: Vec<_> = data.into_iter().map(Object::Blob).collect();
+ for trial in 0..6 {
+ let mut paths = ["main", "split"];
+ if trial % 2 == 1 {
+ paths.reverse();
+ }
+ for name in paths {
+ let t = Instant::now();
+ let mut compressor = Compressor::new(ruzstd::encoding::CompressionLevel::Fastest);
+ let bytes: usize = objects
+ .iter()
+ .map(|o| {
+ let encoded = if name == "main" {
+ ruzstd::encoding::compress_to_vec(o.content().as_ref(), ruzstd::encoding::CompressionLevel::Fastest)
+ } else {
+ o.compressed(&mut compressor)
+ };
+ black_box(encoded).len()
+ })
+ .sum();
+ println!("workspace,24mp-rgba8,{trial},{name},{:.6},{bytes}", t.elapsed().as_secs_f64() * 1000.0);
+ }
+ }
+ }
+
+ #[test]
+ fn reused_compressor_produces_independent_frames() {
+ let data: Vec<Arc<Vec<u8>>> = [0, 1, 8, 131_072, 0, 262_144, 262_147, 131_072, 1]
+ .into_iter()
+ .map(|n| Arc::new((0..n).map(|i| ((i * 37 + i / 97) % 251) as u8).collect()))
+ .collect();
+ let objects: Vec<_> = data.iter().cloned().map(Object::Blob).collect();
+ let mut compressor = Compressor::new(ruzstd::encoding::CompressionLevel::Fastest);
+ for (object, bytes) in objects.iter().zip(&data) {
+ let encoded = object.compressed(&mut compressor);
+ assert_eq!(encoded, ruzstd::encoding::compress_to_vec(bytes.as_slice(), ruzstd::encoding::CompressionLevel::Fastest));
+ assert_eq!(decompress(&encoded, bytes.len(), "test").unwrap(), **bytes);
+ }
+ }
+}
diff --git a/docs/zstd-workspaces-performance.md b/docs/zstd-workspaces-performance.md
new file mode 100644
index 000000000..48f35252d
--- /dev/null
+++ b/docs/zstd-workspaces-performance.md
@@ -0,0 +1,35 @@
+# Rust Zstandard workspace reuse
+
+Only the existing pure-Rust compressor workspace is reused per worker/save. No new backend or C dependency. The kernel compresses 367 independent 256 KiB objects, approximately 24 MP of RGBA8 data, with the fresh main path and reused path alternating order.
+
+Measured on 2026-10-19 against `d95fdf3181c01ad41e95456091a394b105a9afb2` on an Apple M4 Max
+(16 CPUs, 128 GiB), macOS arm64, rustc 1.99.1. Each branch starts directly at that
+base; none of the other performance splits is applied. Release uses optimization
+level 3, LTO off, 16 codegen units, debug info off and incremental compilation off.
+Builds ran at nice 10 with APFS-cloned warm caches; measurements ran at normal
+priority with no concurrent builds. Timings are medians of five samples after one
+warm-up, except the compositor's ten Criterion samples. These synthetic workloads
+are reproducible checks of this change, not a representative image corpus.
+
+| Workload | Main ms | This change ms | Time change |
+|---|---:|---:|---:|
+| 24mp-rgba8 | 125.373 | 121.006 | -3.5% |
+
+Both paths produced 1,352,031 encoded bytes. These are serial compression-kernel timings; they do not measure ZIP assembly, hashing, filesystem work or parallel save latency.
+
+The committed unit test compares each frame byte-for-byte with the previous fresh compress_to_vec path and decodes it, across empty/short/full/partial block inputs and size transitions, including empty input after nonempty input. Partial-block objects keep the fresh-compressor fallback.
+
+Reproduce with the same release profile environment:
+
+```sh
+CARGO_PROFILE_RELEASE_LTO=false CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16 CARGO_PROFILE_RELEASE_DEBUG=0 CARGO_INCREMENTAL=0 nice -n 10 cargo test --release -p photocraft-format --lib --no-run
+# Run the printed executable at normal priority:
+<printed-executable> benchmark_workspace_reuse --ignored --nocapture --test-threads=1
+```
+
+## Local validation
+
+- `cargo test -p photocraft-format --locked`: passed (147 passed, 1 ignored).
+- `cargo clippy -p photocraft-format --locked --all-targets -- -D warnings`: passed.
+- `cargo xtask layers`: passed.
+- `cargo check -p photocraft-format --locked --target wasm32-unknown-unknown`: passed.