Skip to content

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

file.new at 300000x300000 no longer fills ~360 GB of tiles before returning (#705) (#900)

Ian Swope874867461d8a
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 4bcd486fc..754ca9077 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -22,6 +22,17 @@ fn document_pixel_at_the_coordinate_limits() {
assert!(matches!(e, EngineError::BadParams { .. }), "{e}");
}
+#[test]
+fn file_new_at_the_size_limit_does_not_fill_every_tile() {
+ // A 300000² white background used to fill ~360 GB of tiles before returning (#705).
+ for background in ["white", "black", "backgroundColor", "#336699"] {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 300_000, "height": 300_000, "background": background})).unwrap();
+ assert_eq!(px(&mut s, 299_999, 299_999)[3], 1.0, "{background}");
+ assert_eq!(px(&mut s, 0, 0)[3], 1.0, "{background}");
+ }
+}
+
#[test]
fn command_ids_are_unique_and_documented() {
let mut seen = std::collections::HashSet::new();
diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs
index 43c2d0c87..eeb9ea302 100644
--- a/crates/raster/src/lib.rs
+++ b/crates/raster/src/lib.rs
@@ -438,8 +438,17 @@ impl Surface {
let mut enc = vec![0u8; self.format.bytes_per_pixel()];
encode_pixel(&self.format, &px[..n], &mut enc);
let bpp = enc.len();
+ // Fully covered tiles share one Arc: a solid fill costs one tile however large `r` is,
+ // and copy-on-write splits a tile off when it is edited (#705).
+ let mut full: Option<Arc<Tile>> = None;
for tc in r.tiles() {
let tr = tc.rect().intersect(&r);
+ if tr == tc.rect() {
+ let fmt = self.format;
+ let t = full.get_or_insert_with(|| Arc::new(Tile::filled(&fmt, &enc)));
+ self.tiles.insert(tc, t.clone());
+ continue;
+ }
let t = self.tile_mut(tc);
for y in tr.y0..tr.y1 {
let ly = (y - tc.ty * TILE_SIZE) as usize;
@@ -681,6 +690,24 @@ mod tests {
}
}
+ #[test]
+ fn fill_rect_shares_covered_tiles_and_edits_stay_local() {
+ // A 300000² background used to materialize ~360 GB of tiles (#705).
+ let mut s = Surface::new(PixelFormat::RGBA8);
+ s.fill_rect(Rect::new(0, 0, 300_000, 300_000), &[1.0, 0.5, 0.0, 1.0]);
+ let t = |s: &Surface, x, y| s.tile(TileCoord::new(x, y)).unwrap().clone();
+ assert!(Arc::ptr_eq(&t(&s, 0, 0), &t(&s, 1000, 900)));
+ // 300000 is not a multiple of 256: the edge tile is partial and stays its own.
+ let edge = 300_000 / TILE_SIZE;
+ assert!(!Arc::ptr_eq(&t(&s, 0, 0), &t(&s, edge, 0)));
+ assert_eq!(s.pixel(299_999, 299_999), vec![1.0, 128.0 / 255.0, 0.0, 1.0]);
+ assert_eq!(s.pixel(300_000, 0), vec![0.0; 4]);
+ s.write_pixel(5, 5, &[0.0, 0.0, 1.0, 1.0]);
+ assert_eq!(s.pixel(5, 5), vec![0.0, 0.0, 1.0, 1.0]);
+ assert_eq!(s.pixel(300, 5), vec![1.0, 128.0 / 255.0, 0.0, 1.0]);
+ assert!(!Arc::ptr_eq(&t(&s, 0, 0), &t(&s, 1, 0)));
+ }
+
#[test]
fn empty_surface_reads_default() {
let s = Surface::new(PixelFormat::RGBA8);