use crate::error::{Result, ScanError};
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub enum ImageInput<'a> {
Encoded(&'a [u8]),
Rgba8 {
data: &'a [u8],
width: u32,
height: u32,
},
Luma8 {
data: &'a [u8],
width: u32,
height: u32,
},
}
impl<'a> ImageInput<'a> {
#[must_use]
pub fn encoded(bytes: &'a [u8]) -> Self {
Self::Encoded(bytes)
}
#[must_use]
pub fn rgba8(data: &'a [u8], width: u32, height: u32) -> Self {
Self::Rgba8 {
data,
width,
height,
}
}
#[must_use]
pub fn luma8(data: &'a [u8], width: u32, height: u32) -> Self {
Self::Luma8 {
data,
width,
height,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Limits {
pub max_dimension: u32,
pub max_pixels: u64,
}
impl Default for Limits {
fn default() -> Self {
Self {
max_dimension: 10_000,
max_pixels: 64_000_000,
}
}
}
impl Limits {
pub fn validate(&self) -> Result<()> {
if self.max_dimension == 0 {
return Err(ScanError::invalid_option(
"max_dimension",
"0 pixels; the smallest is 1",
));
}
if self.max_pixels == 0 {
return Err(ScanError::invalid_option(
"max_pixels",
"0 pixels; the smallest is 1",
));
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct LumaImage {
data: Vec<u8>,
width: u32,
height: u32,
}
impl LumaImage {
pub(crate) fn new(data: Vec<u8>, width: u32, height: u32) -> Self {
debug_assert_eq!(data.len() as u64, u64::from(width) * u64::from(height));
Self {
data,
width,
height,
}
}
pub(crate) fn width(&self) -> u32 {
self.width
}
pub(crate) fn height(&self) -> u32 {
self.height
}
pub(crate) fn data(&self) -> &[u8] {
&self.data
}
}
pub(crate) fn validate_dims(width: u32, height: u32, limits: &Limits) -> Result<u64> {
if width == 0 || height == 0 {
return Err(ScanError::InvalidImage {
details: format!("zero dimension: {width}x{height}"),
});
}
if width > limits.max_dimension || height > limits.max_dimension {
return Err(ScanError::DimensionsExceeded {
width,
height,
max_dimension: limits.max_dimension,
});
}
let pixels = u64::from(width) * u64::from(height);
if pixels > limits.max_pixels {
return Err(ScanError::PixelOverflow {
width,
height,
max_pixels: limits.max_pixels,
});
}
Ok(pixels)
}
pub(crate) fn validate_buffer(got: usize, expected: u64) -> Result<usize> {
let expected_usize = usize::try_from(expected).map_err(|_| ScanError::PixelOverflow {
width: 0,
height: 0,
max_pixels: expected,
})?;
if got != expected_usize {
return Err(ScanError::BufferMismatch {
got,
expected: expected_usize,
});
}
Ok(expected_usize)
}
pub(crate) fn bt601(r: u8, g: u8, b: u8) -> u8 {
let y = (299 * u32::from(r) + 587 * u32::from(g) + 114 * u32::from(b) + 500) / 1000;
u8::try_from(y).unwrap_or(u8::MAX)
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used)]
use super::*;
use crate::ScanError;
fn decode_to_luma(input: &ImageInput<'_>, limits: &Limits) -> crate::Result<LumaImage> {
crate::transform::normalize(input, limits).map(|planes| planes.luma)
}
fn png_bytes(width: u32, height: u32) -> Vec<u8> {
let img = image::DynamicImage::ImageLuma8(image::ImageBuffer::new(width, height));
let mut buf = Vec::new();
img.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
.unwrap();
buf
}
#[test]
fn encoded_garbage_is_invalid_image() {
let err = decode_to_luma(
&ImageInput::encoded(b"definitely not an image"),
&Limits::default(),
)
.unwrap_err();
assert!(matches!(err, ScanError::InvalidImage { .. }), "{err}");
assert_eq!(err.code(), "QRS-001");
}
#[test]
fn encoded_oversize_rejected_before_full_decode() {
let bytes = png_bytes(2_001, 1);
let limits = Limits {
max_dimension: 2_000,
..Limits::default()
};
let err = decode_to_luma(&ImageInput::encoded(&bytes), &limits).unwrap_err();
assert!(
matches!(
err,
ScanError::DimensionsExceeded {
width: 2_001,
height: 1,
max_dimension: 2_000
}
),
"{err}"
);
}
#[test]
fn raw_oversize_dimension_rejected() {
let data = vec![0u8; 4];
let err =
decode_to_luma(&ImageInput::rgba8(&data, 10_001, 1), &Limits::default()).unwrap_err();
assert_eq!(err.code(), "QRS-002");
}
#[test]
fn pixel_cap_applies_before_buffer_check() {
let err =
decode_to_luma(&ImageInput::luma8(&[], 9_000, 9_000), &Limits::default()).unwrap_err();
assert!(
matches!(
err,
ScanError::PixelOverflow {
max_pixels: 64_000_000,
..
}
),
"{err}"
);
}
#[test]
fn rgba8_buffer_mismatch_reports_expected_len() {
let data = vec![0u8; 11];
let err = decode_to_luma(&ImageInput::rgba8(&data, 2, 2), &Limits::default()).unwrap_err();
assert!(
matches!(
err,
ScanError::BufferMismatch {
got: 11,
expected: 16
}
),
"{err}"
);
}
#[test]
fn luma8_buffer_mismatch_reports_expected_len() {
let data = vec![0u8; 3];
let err = decode_to_luma(&ImageInput::luma8(&data, 2, 2), &Limits::default()).unwrap_err();
assert!(
matches!(
err,
ScanError::BufferMismatch {
got: 3,
expected: 4
}
),
"{err}"
);
}
#[test]
fn rgba8_converts_with_bt601_integer_coefficients() {
let data: Vec<u8> = vec![
255, 0, 0, 255, 255, 255, 255, 255, 0, 0, 0, 255, 0, 255, 0, 255,
];
let luma = decode_to_luma(&ImageInput::rgba8(&data, 4, 1), &Limits::default()).unwrap();
assert_eq!(luma.width(), 4);
assert_eq!(luma.height(), 1);
assert_eq!(luma.data(), &[76, 255, 0, 150]);
}
#[test]
fn luma8_is_passthrough() {
let data: Vec<u8> = vec![7, 42, 99, 200, 13, 0];
let luma = decode_to_luma(&ImageInput::luma8(&data, 3, 2), &Limits::default()).unwrap();
assert_eq!(luma.data(), data.as_slice());
assert_eq!((luma.width(), luma.height()), (3, 2));
}
#[test]
fn encoded_png_roundtrip_decodes_with_correct_dims() {
let bytes = png_bytes(31, 17);
let luma = decode_to_luma(&ImageInput::encoded(&bytes), &Limits::default()).unwrap();
assert_eq!((luma.width(), luma.height()), (31, 17));
assert_eq!(luma.data().len(), 31 * 17);
}
#[test]
fn zero_dimension_is_invalid() {
let err = decode_to_luma(&ImageInput::luma8(&[], 0, 4), &Limits::default()).unwrap_err();
assert_eq!(err.code(), "QRS-001");
}
#[test]
fn limits_admit_their_exact_values() {
let limits = Limits {
max_dimension: 100,
max_pixels: 5_000,
};
assert_eq!(validate_dims(100, 1, &limits).unwrap(), 100);
assert_eq!(validate_dims(1, 100, &limits).unwrap(), 100);
assert_eq!(validate_dims(50, 100, &limits).unwrap(), 5_000);
assert!(matches!(
validate_dims(101, 1, &limits),
Err(ScanError::DimensionsExceeded {
width: 101,
height: 1,
max_dimension: 100
})
));
assert!(matches!(
validate_dims(1, 101, &limits),
Err(ScanError::DimensionsExceeded {
width: 1,
height: 101,
max_dimension: 100
})
));
assert!(matches!(
validate_dims(51, 100, &limits),
Err(ScanError::PixelOverflow {
width: 51,
height: 100,
max_pixels: 5_000
})
));
}
}