psd: share legacy guide header and record encoding

Extract PhotoCraft guide framing from 2aa88b0956; leave rounding and document ordering with callers. Add fixed-byte and hostile-prefix coverage.

Co-authored-by: Dylan M. Taylor <dylan@dylanmtaylor.com>
This commit is contained in:
aionggandDylan M. Taylor authored and Dylan M. Taylor committed 2026-11-17 14:23:06 -05:00
1 parent e1d883e444
commit d55beb8f61
1 file changed
+45
+45
View File
@@ -16,6 +16,23 @@ pub struct GuideV1 {
pub direction: u8,
}
impl GuideV1 {
/// Encode exactly one five-byte record without allocation.
pub fn to_bytes(self) -> [u8; 5] {
let p = self.location.to_be_bytes();
[p[0], p[1], p[2], p[3], self.direction]
}
}
/// Encode a legacy resource header. Grid cycles and count are caller supplied.
pub fn header_v1(horizontal_cycle: u32, vertical_cycle: u32, count: u32) -> [u8; 16] {
let mut out = [0; 16];
for (chunk, value) in out.chunks_exact_mut(4).zip([1u32, horizontal_cycle, vertical_cycle, count]) {
chunk.copy_from_slice(&value.to_be_bytes());
}
out
}
/// Read complete legacy records, preserving the valid prefix on truncation.
/// Matches PhotoCraft recovery: version/grid fields are ignored. Declared counts
/// cannot drive allocation or scanning beyond complete records in the input.
@@ -124,3 +141,31 @@ mod tests {
assert_eq!(ids_count(&[0, 0, 0]), None);
}
}
#[cfg(test)]
mod v1_tests {
use super::*;
#[test]
fn wire_roundtrip_and_signed_unknown_direction() {
let entries = [GuideV1 { location: -33, direction: 1 }, GuideV1 { location: i32::MAX, direction: 255 }];
let mut data = header_v1(576, 576, 2).to_vec();
assert_eq!(data, [0, 0, 0, 1, 0, 0, 2, 64, 0, 0, 2, 64, 0, 0, 0, 2]);
for e in entries {
data.extend(e.to_bytes());
}
assert_eq!(&data[16..21], &[255, 255, 255, 223, 1]);
assert_eq!(parse_v1_prefix(&data).collect::<Vec<_>>(), entries);
for end in 0..=data.len() {
assert_eq!(parse_v1_prefix(&data[..end]).count(), end.saturating_sub(16) / 5);
}
data[..4].copy_from_slice(&99u32.to_be_bytes());
data[12..16].copy_from_slice(&u32::MAX.to_be_bytes());
data.extend([9, 9, 9, 9]);
assert_eq!(parse_v1_prefix(&data).collect::<Vec<_>>(), entries);
data[12..16].copy_from_slice(&1u32.to_be_bytes());
assert_eq!(parse_v1_prefix(&data).collect::<Vec<_>>(), &entries[..1]);
data[12..16].fill(0);
assert_eq!(parse_v1_prefix(&data).count(), 0);
}
}