Skip to content

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

Format: reopening a .pcraft shares deduplicated tiles again (#3315) (#3339)

Valentin Klein60ef9d836f62
diff --git a/crates/format/src/convert.rs b/crates/format/src/convert.rs
index 4ee79f36b..d319c85a9 100644
--- a/crates/format/src/convert.rs
+++ b/crates/format/src/convert.rs
@@ -306,6 +306,11 @@ pub(crate) struct Loader<'a> {
pub id_map: std::collections::HashMap<u64, LayerId>,
pub contents_id_map: std::collections::HashMap<u64, SmartContentsId>,
pub legacy_linked_contents: std::collections::HashMap<String, SmartContentsId>,
+ /// Decoded tiles by content hash and sample type. Saves store a tile once however often it
+ /// is referenced (a solid fill shares one tile), so a load decodes and charges the byte
+ /// budget once per distinct tile and hands every reference the same copy-on-write `Arc`
+ /// (#3315). Grouped by sample type: in-memory byte order depends on it.
+ pub tiles: std::collections::HashMap<SampleType, std::collections::HashMap<Hash, Arc<Tile>>>,
}
impl Loader<'_> {
@@ -338,9 +343,21 @@ impl Loader<'_> {
if s.tile(c).is_some() {
return Err(FormatError::corrupt(format!("duplicate tile ({}, {})", t.tx, t.ty)));
}
+ if let Some(tile) = self.tiles.get(&f.sample).and_then(|m| m.get(&t.hash)) {
+ // One hash names one byte string, so a cached tile of another length means
+ // the same hash was referenced from formats of different pixel sizes.
+ if tile.bytes().len() != len {
+ return Err(FormatError::corrupt(format!("tile {} is referenced with different sizes", t.hash)));
+ }
+ s.put_tiles([(c, tile.clone())]);
+ continue;
+ }
let mut bytes = self.fetch.tile(&t.hash, len)?;
swap_to_le(&mut bytes, f.sample);
s.tile_mut(c).bytes_mut().copy_from_slice(&bytes);
+ if let Some(tile) = s.tile(c) {
+ self.tiles.entry(f.sample).or_default().insert(t.hash.clone(), tile.clone());
+ }
}
Ok(s)
}
diff --git a/crates/format/src/store.rs b/crates/format/src/store.rs
index d7f6d4596..5c2835608 100644
--- a/crates/format/src/store.rs
+++ b/crates/format/src/store.rs
@@ -269,6 +269,7 @@ pub(crate) fn load(src: &dyn ByteSource, opts: &LoadOptions) -> Result<Document>
id_map: HashMap::new(),
contents_id_map: HashMap::new(),
legacy_linked_contents: HashMap::new(),
+ tiles: HashMap::new(),
};
loader.document(&m.document)
}
diff --git a/crates/format/tests/corruption.rs b/crates/format/tests/corruption.rs
index 9215e7cd1..2f47203b3 100644
--- a/crates/format/tests/corruption.rs
+++ b/crates/format/tests/corruption.rs
@@ -154,6 +154,37 @@ fn total_size_limit() {
assert!(matches!(load_from_bytes_with(&b, &opts), Err(FormatError::LimitExceeded(_))));
}
+/// A hostile manifest may name one stored tile at very many coordinates. The load decodes and
+/// charges it once, each reference only clones the shared tile, and the budget still bounds the
+/// distinct bytes (#3315).
+#[test]
+fn many_references_to_one_tile_load_within_the_budget() {
+ let mut doc = photocraft_doc::Document::new("d", photocraft_doc::Size::new(256, 256), ColorMode::Rgb, SampleType::U8);
+ let mut l = photocraft_doc::Layer::raster("solid", doc.pixel_format());
+ l.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 256, 256), &[1.0, 0.0, 0.0, 1.0]);
+ doc.layers.push(l);
+ let bytes = save_to_bytes(&doc, &SaveOptions::default()).unwrap();
+ let hostile = rebuild(&bytes, |name, data| {
+ if name != "manifest.json" {
+ return Some(data);
+ }
+ let mut m: serde_json::Value = serde_json::from_slice(&data).unwrap();
+ let tiles = m["document"]["layers"][0]["content"]["surface"]["tiles"].as_array_mut().unwrap();
+ let hash = tiles[0]["hash"].clone();
+ *tiles = (0..256 * 256).map(|i| serde_json::json!({ "tx": i % 256, "ty": i / 256, "hash": hash })).collect();
+ Some(serde_json::to_vec(&m).unwrap())
+ });
+ let one_tile = 256 * 256 * 4;
+ let back = load_from_bytes_with(&hostile, &LoadOptions { max_total_bytes: one_tile, ..Default::default() }).unwrap();
+ let s = back.layers[0].surface().unwrap();
+ assert_eq!(s.tile_count(), 256 * 256);
+ let first = s.tiles().next().unwrap().1;
+ assert!(s.tiles().all(|(_, t)| std::sync::Arc::ptr_eq(t, first)));
+ // The one distinct tile is still charged against the budget.
+ let opts = LoadOptions { max_total_bytes: one_tile - 1, ..Default::default() };
+ assert!(matches!(load_from_bytes_with(&hostile, &opts), Err(FormatError::LimitExceeded(_))));
+}
+
#[test]
fn directory_bundle_resave_repairs_tampered_objects() {
let doc = rich_doc(ColorMode::Rgb, SampleType::U8);
diff --git a/crates/format/tests/roundtrip.rs b/crates/format/tests/roundtrip.rs
index 537515cff..d12618366 100644
--- a/crates/format/tests/roundtrip.rs
+++ b/crates/format/tests/roundtrip.rs
@@ -270,6 +270,28 @@ fn identical_tiles_are_stored_once() {
assert_eq!(s.tiles_total, per_layer);
}
+/// A solid fill saves one tile however many coordinates share it; reopening must decode it once,
+/// charge the byte budget once and keep the sharing (#3315). The budget here holds one tile,
+/// standing in for a canvas too large to expand tile by tile.
+#[test]
+fn solid_fill_reopens_with_one_shared_tile() {
+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ let size = photocraft_doc::Size::new(2048, 2048);
+ let mut doc = Document::new("d", size, ColorMode::Rgb, depth);
+ let mut l = Layer::raster("solid", doc.pixel_format());
+ l.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::from_size(size), &[1.0, 0.5, 0.25, 1.0]);
+ doc.layers.push(l);
+ let bytes = save_to_bytes(&doc, &SaveOptions::default()).unwrap();
+ let one_tile = (256 * 256 * doc.pixel_format().bytes_per_pixel()) as u64;
+ let back = load_from_bytes_with(&bytes, &LoadOptions { max_total_bytes: one_tile, ..Default::default() }).unwrap();
+ assert_eq!(back, doc, "{depth:?}");
+ let s = back.layers[0].surface().unwrap();
+ assert_eq!(s.tile_count(), 64, "{depth:?}");
+ let first = s.tiles().next().unwrap().1;
+ assert!(s.tiles().all(|(_, t)| std::sync::Arc::ptr_eq(t, first)), "{depth:?}: tiles not shared after reopening");
+ }
+}
+
#[test]
fn ids_preserved_and_counter_advanced() {
let doc = rich_doc(ColorMode::Rgb, SampleType::U8);