PhotoCraft: An open-source, photo editor written by scratch in pure Rust
security(raster,doc): count tile grids without walking them; share rebuilt tiles; index slice merges
Dylan M. Taylor3729c3f66432
diff --git a/crates/doc/src/slices.rs b/crates/doc/src/slices.rsindex 7fb6ba3ad..9e6675283 100644--- a/crates/doc/src/slices.rs+++ b/crates/doc/src/slices.rs@@ -241,12 +241,22 @@ pub fn auto_slices(canvas: Rect, taken: &[Rect]) -> Vec<Rect> {}}// Merge vertically adjacent runs with the same columns.+ // `open` finds the slice a run continues by its columns and bottom edge: searching the output+ // for each run is quadratic in the runs, and bars crossing in a grid leave a million of them.let mut out: Vec<Rect> = Vec::new();+ let mut open: std::collections::HashMap<(i32, i32, i32), usize> = std::collections::HashMap::new();for r in runs {- if let Some(prev) = out.iter_mut().find(|p| p.x0 == r.x0 && p.x1 == r.x1 && p.y1 == r.y0) {- prev.y1 = r.y1;- } else {- out.push(r);+ match open.remove(&(r.x0, r.x1, r.y0)) {+ Some(i) => {+ if let Some(prev) = out.get_mut(i) {+ prev.y1 = r.y1;+ }+ open.insert((r.x0, r.x1, r.y1), i);+ }+ None => {+ open.insert((r.x0, r.x1, r.y1), out.len());+ out.push(r);+ }}}outdiff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rsindex d95e4b847..acd422b32 100644--- a/crates/geom/src/lib.rs+++ b/crates/geom/src/lib.rs@@ -96,6 +96,14 @@ impl Rect {pub fn inflate(&self, d: i32) -> Rect {Rect::new(self.x0.saturating_sub(d), self.y0.saturating_sub(d), self.x1.saturating_add(d), self.y1.saturating_add(d))}+ /// How many tiles overlap this rect, without visiting them (a rect can span billions).+ pub fn tile_count(&self) -> u64 {+ if self.is_empty() {+ return 0;+ }+ let (a, b) = (TileCoord::containing(self.x0, self.y0), TileCoord::containing(self.x1 - 1, self.y1 - 1));+ ((i64::from(b.tx) - i64::from(a.tx) + 1) as u64) * ((i64::from(b.ty) - i64::from(a.ty) + 1) as u64)+ }/// All tiles overlapping this rect.pub fn tiles(&self) -> impl Iterator<Item = TileCoord> + use<> {let (a, b) = if self.is_empty() {diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rsindex 49806e521..6ce0ea688 100644--- a/crates/raster/src/lib.rs+++ b/crates/raster/src/lib.rs@@ -732,7 +732,9 @@ impl Surface {/// Fallible counterpart to [`Surface::take_tiles`]. Reserves the complete result and any/// default tile before removing a tile, so a reservation failure leaves the surface intact.pub fn try_take_tiles(&mut self, r: Rect) -> Result<Vec<(TileCoord, Arc<Tile>)>, AllocationError> {- let count = r.tiles().count();+ // Counted in u64 and checked before narrowing: on 32-bit targets the grid of a sparse+ // surface's bounds can pass `usize` (and visiting it to count it takes just as long).+ let count = usize::try_from(r.tile_count()).map_err(|_| AllocationError::SizeOverflow)?;let bytes = count.checked_mul(std::mem::size_of::<(TileCoord, Arc<Tile>)>()).ok_or(AllocationError::SizeOverflow)?;let mut out = Vec::new();out.try_reserve_exact(count).map_err(|_| AllocationError::NotEnoughMemory { bytes })?;@@ -890,6 +892,10 @@ impl Surface {// One tile row of the default pixel, to compare a finished tile with a row at a time.let default_row = self.default_pixel.repeat(TILE_SIZE.unsigned_abs() as usize);+ // Target tiles rebuilt from the same source tiles at the same offset are the same tile:+ // a bundle can point thousands of tile references at one payload, and a move would+ // otherwise copy it into a separate buffer for each.+ let built: std::sync::Mutex<std::collections::HashMap<Vec<usize>, Option<Arc<Tile>>>> = Default::default();let build_target = |dc: TileCoord| -> Option<(TileCoord, Arc<Tile>)> {let dr = dc.rect();let sr = dr.translate(dx.saturating_neg(), dy.saturating_neg());@@ -904,6 +910,14 @@ impl Surface {// A tile of only the default pixel is left out, as `prune` would.return (shared.data.get(..bpp) != Some(&*self.default_pixel)).then_some((dc, shared));}+ // The identities of the source tiles under a covered window (the offset is the same+ // for every target of this call).+ let memo_key: Option<Vec<usize>> = covered.then(|| sr.tiles().map(|sc| self.tiles.get(&sc).map_or(0, |t| Arc::as_ptr(t) as usize)).collect());+ if let Some(k) = &memo_key+ && let Some(hit) = built.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(k)+ {+ return hit.clone().map(|t| (dc, t));+ }let mut tile = Tile { data: vec![0u8; (TILE_SIZE * TILE_SIZE) as usize * bpp].into_boxed_slice() };let (tx0, ty0) = (i64::from(dc.tx) * i64::from(TILE_SIZE), i64::from(dc.ty) * i64::from(TILE_SIZE));@@ -984,7 +998,11 @@ impl Surface {}// A target that got only default pixels isn't stored, as `prune` would drop it. Checked// after the copy, a row at a time: a tile with content stops at its first such row.- tile.data.chunks(default_row.len()).any(|row| row != default_row).then(|| (dc, Arc::new(tile)))+ let finished = tile.data.chunks(default_row.len()).any(|row| row != default_row).then(|| Arc::new(tile));+ if let Some(k) = memo_key {+ built.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(k, finished.clone());+ }+ finished.map(|t| (dc, t))};#[cfg(not(target_arch = "wasm32"))]{@@ -1835,6 +1853,36 @@ mod tests {let _ = s.translated(i32::MIN + 1, 3, all);}+ /// Many references to one payload, moved off the tile grid: the rebuilt tiles that read the+ /// same source tiles at the same offset are one tile, not a copy each.+ #[test]+ fn translated_shares_tiles_rebuilt_from_shared_sources() {+ let fmt = PixelFormat::RGBA8;+ let mut one = Surface::new(fmt);+ let r = Rect::new(0, 0, TILE_SIZE, TILE_SIZE);+ let px: Vec<f32> = (0..r.width() * r.height()).flat_map(|i| [(i % 251) as f32 / 255.0, (i % 7) as f32 / 7.0, 0.5, 1.0]).collect();+ one.write_region(r, &px);+ let payload = Arc::clone(one.tile(TileCoord::new(0, 0)).unwrap());+ let mut s = Surface::new(fmt);+ s.put_tiles((0..16).flat_map(|ty| (0..16).map(move |tx| TileCoord::new(tx, ty))).map(|c| (c, Arc::clone(&payload))));+ let moved = s.translated(7, 5, s.content_bounds());+ let distinct: std::collections::HashSet<_> = moved.tiles().map(|(_, t)| Arc::as_ptr(t)).collect();+ // The 15 × 15 interior tiles read the same four source tiles at the same offset, so they are+ // one tile; only the 64 border tiles (cut by the content's edge) are built one by one.+ assert!(moved.tile_count() == 289 && distinct.len() <= 64 + 5, "{} tiles, {} distinct", moved.tile_count(), distinct.len());+ let all = Rect::new(-50, -50, 16 * TILE_SIZE + 50, 16 * TILE_SIZE + 50);+ assert_eq!(moved.read_region(all), s.read_region(all.translate(-7, -5)));+ }++ #[test]+ fn a_surface_bounds_tile_count_is_counted_not_walked() {+ let mut s = Surface::new(PixelFormat::RGBA8);+ let far = Rect::new(0, 0, i32::MAX, i32::MAX);+ assert_eq!(far.tile_count(), u64::from(i32::MAX as u32 / TILE_SIZE as u32 + 1).pow(2));+ // Not allocated: 2^46 entries is far past any reservation.+ assert!(s.try_take_tiles(far).is_err());+ }+#[test]fn translated_stores_no_tiles_of_only_the_default_pixel() {let only_default = |t: &Surface| {