diff --git a/crates/psd/src/lib.rs b/crates/psd/src/lib.rs index 12f2e79cf..d4db98065 100644 --- a/crates/psd/src/lib.rs +++ b/crates/psd/src/lib.rs @@ -103,6 +103,7 @@ pub mod testgen; pub mod text; pub mod tiff; pub mod tree; +pub mod unicode_names; pub use blend::BlendMode; pub use builder::{GroupSpec, LayerSpec, MaskSpec, PixelData, PsdBuilder}; diff --git a/crates/psd/src/unicode_names.rs b/crates/psd/src/unicode_names.rs new file mode 100644 index 000000000..c4547243b --- /dev/null +++ b/crates/psd/src/unicode_names.rs @@ -0,0 +1,54 @@ +//! Counted UTF-16 name records, as used by PSD Unicode Alpha Names (resource 1045). +//! +//! Adapted from PhotoCraft's channel-name reader. Framing is shared; decoding malformed +//! UTF-16, removing terminators and assigning names to document channels remain caller policy. + +/// Iterate complete records as borrowed big-endian UTF-16 byte slices. +/// +/// A record starts with a big-endian `u32` code-unit count. Empty records are retained. +/// An incomplete count, truncated record or arithmetic overflow ends the list, preserving +/// preceding complete records. No allocation is driven by the declared count, and bytes +/// after a malformed record are not interpreted as new records. +pub fn records(mut data: &[u8]) -> impl Iterator { + std::iter::from_fn(move || { + let count = data.get(..4)?; + let count = u32::from_be_bytes([count[0], count[1], count[2], count[3]]); + let input = data; + // On any malformed length the iterator stays exhausted on subsequent calls. + data = &[]; + let len = usize::try_from(count).ok()?.checked_mul(2)?; + let end = 4usize.checked_add(len)?; + let record = input.get(4..end)?; + data = input.get(end..)?; + Some(record) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn borrows_empty_and_uninterpreted_code_units() { + let data = [0, 0, 0, 0, 0, 0, 0, 3, 0xd8, 0, 0, 65, 0, 0]; + let found: Vec<_> = records(&data).collect(); + assert_eq!(found, [&data[4..4], &data[8..14]]); + assert_eq!(found[1].as_ptr(), data[8..].as_ptr()); + } + + #[test] + fn partial_tail_and_hostile_count_stop_without_losing_prefix() { + let first = [0, 0, 0, 1, 0, 65]; + for tail in [&[0][..], &[0, 0, 0], &[0, 0, 0, 2, 0, 66], &[255, 255, 255, 255, 0, 66]] { + let mut bytes = first.to_vec(); + bytes.extend(tail); + let mut it = records(&bytes); + assert_eq!(it.next(), Some(&first[4..])); + assert_eq!(it.next(), None); + assert_eq!(it.next(), None); + } + for end in 0..first.len() { + assert_eq!(records(&first[..end]).count(), 0); + } + } +}