diff --git a/crates/psd/src/pixels.rs b/crates/psd/src/pixels.rs index f9b7ca6f3..8ce6f2d63 100644 --- a/crates/psd/src/pixels.rs +++ b/crates/psd/src/pixels.rs @@ -472,27 +472,12 @@ enum PlaneStream { /// PackBits decoding of one row (appends exactly `row` bytes, zero-padded). pub(crate) fn unpack_bits(src: &[u8], row: usize, out: &mut Vec) -> Result<()> { - let start = out.len(); - let mut i = 0; - while i < src.len() && out.len() - start < row { - let n = src[i] as i8; - i += 1; - // A packet is written only up to the row's end, so the reserved plane never grows. - let room = row - (out.len() - start); - if n >= 0 { - let k = n as usize + 1; - let s = src.get(i..i + k).ok_or(Error::Truncated)?; - out.extend_from_slice(&s[..k.min(room)]); - i += k; - } else if n != -128 { - let k = (1 - n as isize) as usize; - let v = *src.get(i).ok_or(Error::Truncated)?; - out.extend(std::iter::repeat_n(v, k.min(room))); - i += 1; - } - } - out.resize(start + row, 0); - Ok(()) + // The production caller already charges/reserves the complete plane in Budget. + // Keep the shared recovery API bounded to this row; never relax the app budget. + craft_psd::compression::packbits::decode_padded_into(src, row, row, out).map_err(|error| match error { + craft_psd::PsdError::Decompress(_) => Error::Truncated, + other => Error::Invalid(other.to_string()), + }) } pub(crate) fn srgb_encode(v: f32) -> f32 { diff --git a/crates/psd/src/tests.rs b/crates/psd/src/tests.rs index 7406c0345..e32df0122 100644 --- a/crates/psd/src/tests.rs +++ b/crates/psd/src/tests.rs @@ -596,3 +596,24 @@ fn written_32_bit_color_samples_keep_their_range() { let q = |x: f32| (x.clamp(0.0, 1.0) * 255.0).round() / 255.0; assert_eq!(p8.composite().expect("composite").data[0], [q(2.0), q(-0.5), q(0.25), q(1.5)]); } + +#[test] +fn shared_packbits_keeps_padded_rows_and_truncated_packet_errors() { + let mut out = vec![42]; + unpack_bits(&[0, 7], 3, &mut out).unwrap(); + assert_eq!(out, [42, 7, 0, 0]); + unpack_bits(&[128], 2, &mut out).unwrap(); + assert_eq!(out, [42, 7, 0, 0, 0, 0]); + assert_eq!(unpack_bits(&[3, 1], 1, &mut vec![]), Err(Error::Truncated)); + assert_eq!(unpack_bits(&[255], 1, &mut vec![]), Err(Error::Truncated)); + let mut row = vec![]; + unpack_bits(&[0, 9, 255], 1, &mut row).unwrap(); + assert_eq!(row, [9]); +} + +#[test] +fn shared_packbits_reports_row_limits_as_invalid_not_truncated() { + // The shared recovery decoder refuses a row beyond its decoded-size limit. That refusal + // is a limit, not truncated PackBits data, so the wrapper must not report it as one. + assert!(matches!(unpack_bits(&[], usize::MAX, &mut Vec::new()), Err(Error::Invalid(_)))); +}