dpx: write the reservation helper and its test independently of tga's

This commit is contained in:
FredApps
2026-11-16 02:42:09 +01:00
parent 95aba513e7
commit 831c080ac5
+10 -9
View File
@@ -9,12 +9,13 @@ pub enum Rgba8EncodeError {
/// The output buffer could not be allocated.
OutOfMemory,
}
/// An empty buffer with room for `len` bytes, or [`Rgba8EncodeError::OutOfMemory`] when the
/// allocation fails (instead of aborting the process).
fn output_buffer(len: usize) -> std::result::Result<Vec<u8>, Rgba8EncodeError> {
let mut out = Vec::new();
out.try_reserve_exact(len).map_err(|_| Rgba8EncodeError::OutOfMemory)?;
Ok(out)
/// Reserves the DPX output up front; a failed reservation becomes [`Rgba8EncodeError::OutOfMemory`].
fn output_buffer(size: usize) -> std::result::Result<Vec<u8>, Rgba8EncodeError> {
let mut buf = Vec::new();
match buf.try_reserve_exact(size) {
Ok(()) => Ok(buf),
Err(_) => Err(Rgba8EncodeError::OutOfMemory),
}
}
fn checked_len(rgba: &[u8], w: u32, h: u32) -> std::result::Result<usize, Rgba8EncodeError> {
let n = (w as usize).checked_mul(h as usize).and_then(|n| n.checked_mul(4)).ok_or(Rgba8EncodeError::FrameSize)?;
@@ -114,8 +115,8 @@ mod tests {
assert_eq!(encode_rgba8_dpx10(&[], 0, 1, ""), Err(Rgba8EncodeError::FrameSize));
}
#[test]
fn a_failed_output_allocation_is_an_error() {
assert_eq!(output_buffer(usize::MAX), Err(Rgba8EncodeError::OutOfMemory));
assert!(output_buffer(16).is_ok_and(|b| b.is_empty() && b.capacity() >= 16));
fn output_reservation_failure_maps_to_out_of_memory() {
assert!(matches!(output_buffer(usize::MAX), Err(Rgba8EncodeError::OutOfMemory)));
assert_eq!(output_buffer(DPX_HEADER).map(|b| b.capacity() >= DPX_HEADER), Ok(true));
}
}