From d5e7b0c81824faa0319a080afa014806b04e75fb Mon Sep 17 00:00:00 2001 From: Robert Garrett Date: Mon, 14 Oct 2024 15:09:03 -0500 Subject: [PATCH] New `Decoder` creation function, more metadata The qoi_header is specified as knowing the width, height, channels, and colorspace. I figure this information would be captured by the decoder, if anywhere. I've added more properties to the struct, and created a new, fallible construction function. --- src/decoder.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/src/decoder.rs b/src/decoder.rs index bb81e5a..26fdc30 100644 --- a/src/decoder.rs +++ b/src/decoder.rs @@ -35,6 +35,7 @@ fn try_read_u32>(bytes: &mut I) -> Result } mod codec_utils { + use super::DecodeError; use super::PixelRGBA; pub(crate) fn hash(pixel: PixelRGBA) -> u8 { pixel @@ -45,10 +46,24 @@ mod codec_utils { .wrapping_add(pixel.a.wrapping_mul(11)) % 64 } + + pub (crate) fn read_u8_rewrap>(bytes: &mut I) -> Result { + if let Some(byte) = bytes.next() { + return Ok(byte); + } else { + return Err(DecodeError::EarlyIteratorExhaustion); + } + } } struct Decoder> { + // Image metadata + width: u32, + height: u32, + channels: u8, + colorspace: u8, + // QOI codec state information back_buffer: [PixelRGBA; 64], prev_pixel: PixelRGBA, @@ -61,6 +76,20 @@ impl Decoder where I: Iterator, { + fn try_new(mut bytes: I) -> Result { + let _ = try_read_magic(&mut bytes)?; + Ok(Self { + width: try_read_u32(&mut bytes)?, + height: try_read_u32(&mut bytes)?, + channels: codec_utils::read_u8_rewrap(&mut bytes)?, + colorspace: codec_utils::read_u8_rewrap(&mut bytes)?, + back_buffer: [PixelRGBA::zero(); 64], + prev_pixel: PixelRGBA { r:0, g:0, b:0, a: 255}, + bytes, + run_len: 0, + }) + } + fn new(bytes: I) -> Self { Self { back_buffer: [PixelRGBA::zero(); 64],