use gamut_core::{
DecodeImage, Dimensions, EncodeImage, Error, ImageBuf, ImageRef, Pixel, Result, Rgb8,
};
struct RawCodec;
impl EncodeImage<Rgb8> for RawCodec {
fn encode_image(&self, image: ImageRef<'_, Rgb8>, out: &mut Vec<u8>) -> Result<usize> {
let start = out.len();
out.extend_from_slice(&image.width().to_be_bytes());
out.extend_from_slice(&image.height().to_be_bytes());
out.extend_from_slice(image.as_samples());
Ok(out.len() - start)
}
}
impl DecodeImage<Rgb8> for RawCodec {
fn decode_image(&self, data: &[u8]) -> Result<ImageBuf<Rgb8>> {
let header = data
.get(..8)
.ok_or(Error::InvalidInput("raw: truncated header"))?;
let width = u32::from_be_bytes(header[0..4].try_into().expect("8-byte header"));
let height = u32::from_be_bytes(header[4..8].try_into().expect("8-byte header"));
let dims = Dimensions::new(width, height)?;
ImageBuf::new(data[8..].to_vec(), dims)
}
}
#[test]
fn round_trips_through_the_public_api() {
let dims = Dimensions::new(3, 2).unwrap();
let samples: Vec<u8> = (0..dims.sample_count(Rgb8::CHANNELS).unwrap() as u8).collect();
let original = ImageBuf::<Rgb8>::new(samples, dims).unwrap();
let bytes = RawCodec.encode_to_vec(original.as_ref()).unwrap();
let decoded = RawCodec.decode_image(&bytes).unwrap();
assert_eq!(decoded, original);
assert_eq!(decoded.dimensions(), dims);
}
#[test]
fn decode_rejects_a_truncated_stream() {
let full = RawCodec
.encode_to_vec(
ImageBuf::<Rgb8>::new(vec![0u8; 18], Dimensions::new(3, 2).unwrap())
.unwrap()
.as_ref(),
)
.unwrap();
let truncated = &full[..8 + 2];
assert!(matches!(
RawCodec.decode_image(truncated),
Err(Error::InvalidInput(_))
));
}