use super::error::EncodeError;
use super::header::valid_dimensions;
use super::types::{BitDepth, ColorType, PixelFormat};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ImageRef<'a> {
width: u32,
height: u32,
format: PixelFormat,
data: &'a [u8],
}
impl<'a> ImageRef<'a> {
pub fn new(
width: u32,
height: u32,
color: ColorType,
bit_depth: BitDepth,
data: &'a [u8],
) -> Result<Self, EncodeError> {
if !valid_dimensions(width, height) {
return Err(EncodeError::InvalidDimensions { width, height });
}
let format = PixelFormat::new(color, bit_depth)
.filter(|_| color != ColorType::Indexed)
.ok_or(EncodeError::UnsupportedFormat { color, bit_depth })?;
let expected = format
.image_bytes(width, height)
.ok_or(EncodeError::ImageTooLarge)?;
if data.len() != expected {
return Err(EncodeError::DataLengthMismatch {
expected,
actual: data.len(),
});
}
Ok(Self {
width,
height,
format,
data,
})
}
pub fn rgba8(width: u32, height: u32, data: &'a [u8]) -> Result<Self, EncodeError> {
Self::new(width, height, ColorType::Rgba, BitDepth::Eight, data)
}
pub fn rgb8(width: u32, height: u32, data: &'a [u8]) -> Result<Self, EncodeError> {
Self::new(width, height, ColorType::Rgb, BitDepth::Eight, data)
}
pub const fn width(&self) -> u32 {
self.width
}
pub const fn height(&self) -> u32 {
self.height
}
pub const fn color_type(&self) -> ColorType {
self.format.color
}
pub const fn bit_depth(&self) -> BitDepth {
self.format.depth
}
pub const fn data(&self) -> &'a [u8] {
self.data
}
pub fn row_bytes(&self) -> usize {
self.data.len() / self.height as usize
}
pub(crate) const fn format(&self) -> PixelFormat {
self.format
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn validates_dimensions_format_and_length() {
assert_eq!(
ImageRef::rgba8(0, 1, &[]),
Err(EncodeError::InvalidDimensions {
width: 0,
height: 1
})
);
assert_eq!(
ImageRef::rgba8(1, 1 << 31, &[]),
Err(EncodeError::InvalidDimensions {
width: 1,
height: 1 << 31
})
);
assert_eq!(
ImageRef::new(1, 1, ColorType::Indexed, BitDepth::Eight, &[0]),
Err(EncodeError::UnsupportedFormat {
color: ColorType::Indexed,
bit_depth: BitDepth::Eight
})
);
assert_eq!(
ImageRef::new(1, 1, ColorType::Rgb, BitDepth::Four, &[0, 0]),
Err(EncodeError::UnsupportedFormat {
color: ColorType::Rgb,
bit_depth: BitDepth::Four
})
);
assert_eq!(
ImageRef::rgb8(2, 2, &[0; 11]),
Err(EncodeError::DataLengthMismatch {
expected: 12,
actual: 11
})
);
}
#[test]
fn packed_grey_rows_are_padded_to_bytes() {
let image = ImageRef::new(9, 2, ColorType::Gray, BitDepth::One, &[0; 4]).unwrap();
assert_eq!(image.row_bytes(), 2);
assert_eq!((image.width(), image.height()), (9, 2));
assert_eq!(
(image.color_type(), image.bit_depth()),
(ColorType::Gray, BitDepth::One)
);
assert_eq!(image.data().len(), 4);
}
}