From c864e1e8c9e0f7e2c9f24fca1faa6f298a068bca Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 09:46:17 -0500 Subject: [PATCH] psd: support caller-budgeted prediction scratch --- crates/psd/src/compression.rs | 40 ++++++++++++++++++++++++++--- crates/psd/src/compression/tests.rs | 36 ++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 3 deletions(-) diff --git a/crates/psd/src/compression.rs b/crates/psd/src/compression.rs index b41936a04..f9d4a744e 100644 --- a/crates/psd/src/compression.rs +++ b/crates/psd/src/compression.rs @@ -745,8 +745,42 @@ pub fn unpredict(buf: &mut [u8], layout: &PlaneLayout) -> Result<()> { if rb == 0 { return Ok(()); } + let mut scratch = if layout.depth == 32 && buf.len() >= rb { vec![0; rb] } else { Vec::new() }; + unpredict_rows(buf, layout, &mut scratch) +} + +/// Reverses prediction without allocating, using caller-accounted scratch memory. +/// +/// `buf` must contain exactly `planes * height` complete rows. For 32-bit samples, +/// `scratch` must hold at least one row (`width * 4` bytes); other depths need none. +/// Layout, input length and scratch capacity are checked before any bytes are changed. +/// Scratch contents are overwritten. Unlike [`unpredict`], partial or surplus rows +/// are rejected, making this suitable for callers with explicit decode budgets. +pub fn unpredict_with_scratch(buf: &mut [u8], layout: &PlaneLayout, scratch: &mut [u8]) -> Result<()> { + let rb = match layout.depth { + 1 => layout.width.div_ceil(8), + 8 => layout.width, + 16 => layout.width.checked_mul(2).ok_or(PsdError::LimitExceeded("row size overflow"))?, + 32 => layout.width.checked_mul(4).ok_or(PsdError::LimitExceeded("row size overflow"))?, + d => return Err(PsdError::Unsupported(format!("prediction for depth {d}"))), + }; + let expected = + rb.checked_mul(layout.height).and_then(|n| n.checked_mul(layout.planes)).ok_or(PsdError::LimitExceeded("decoded size overflow"))?; + if buf.len() != expected { + return Err(PsdError::Invalid("prediction buffer length does not match layout".into())); + } + if rb == 0 || buf.is_empty() { + return Ok(()); + } + if layout.depth == 32 && scratch.len() < rb { + return Err(PsdError::Invalid("prediction scratch is shorter than one row".into())); + } + unpredict_rows(buf, layout, scratch) +} + +fn unpredict_rows(buf: &mut [u8], layout: &PlaneLayout, scratch: &mut [u8]) -> Result<()> { + let rb = layout.row_bytes(); let w = layout.width; - let mut scratch = Vec::new(); for row in buf.chunks_exact_mut(rb) { match layout.depth { 1 | 8 => { @@ -763,8 +797,8 @@ pub fn unpredict(buf: &mut [u8], layout: &PlaneLayout) -> Result<()> { } } 32 => { - scratch.clear(); - scratch.extend_from_slice(row); + scratch[..rb].copy_from_slice(row); + let scratch = &scratch[..rb]; // The byte-wise running sum runs across the four planes, so // plane k starts at the wrapping total of planes 0..k. let (p0, rest) = scratch.split_at(w); diff --git a/crates/psd/src/compression/tests.rs b/crates/psd/src/compression/tests.rs index 6e0d86a7e..ed0fd2dbc 100644 --- a/crates/psd/src/compression/tests.rs +++ b/crates/psd/src/compression/tests.rs @@ -771,3 +771,39 @@ fn rle_chunks_use_the_callers_pool_and_report_panics() { assert!(map_chunks(2, vec![0, 1], |_| panic!("worker")).is_err()); }); } + +#[test] +fn caller_scratch_prediction_matches_existing_decoder_across_planes() { + for depth in [1u16, 8, 16, 32] { + let layout = PlaneLayout { planes: 3, width: 13, height: 7, depth, version: Version::Psb }; + let mut actual: Vec = (0..layout.decoded_len().unwrap()).map(|i| (i.wrapping_mul(31) % 251) as u8).collect(); + let mut expected = actual.clone(); + unpredict(&mut expected, &layout).unwrap(); + let needed = if depth == 32 { layout.row_bytes() } else { 0 }; + let mut scratch = vec![0xa5; needed + 11]; + unpredict_with_scratch(&mut actual, &layout, &mut scratch).unwrap(); + assert_eq!(actual, expected, "depth {depth}"); + assert_eq!(&scratch[needed..], &[0xa5; 11]); + } +} + +#[test] +fn caller_scratch_prediction_rejects_invalid_inputs_before_mutation() { + let layout = PlaneLayout { planes: 1, width: 3, height: 2, depth: 32, version: Version::Psd }; + let original = vec![0x73; 24]; + for (len, scratch_len) in [(23, 12), (25, 12), (24, 11)] { + let mut bytes = vec![0x73; len]; + let mut scratch = vec![0xa5; scratch_len]; + assert!(unpredict_with_scratch(&mut bytes, &layout, &mut scratch).is_err()); + assert_eq!(bytes, vec![0x73; len]); + assert_eq!(scratch, vec![0xa5; scratch_len]); + } + for invalid in [PlaneLayout { width: usize::MAX, ..layout }, PlaneLayout { planes: usize::MAX, ..layout }, PlaneLayout { depth: 12, ..layout }] { + let mut bytes = original.clone(); + assert!(unpredict_with_scratch(&mut bytes, &invalid, &mut []).is_err()); + assert_eq!(bytes, original); + } + for empty in [PlaneLayout { width: 0, ..layout }, PlaneLayout { height: 0, ..layout }] { + unpredict_with_scratch(&mut [], &empty, &mut []).unwrap(); + } +}