use super::{
GeometryOverflow, InsufficientPlane, InsufficientStride, WidthAlignment, WidthOverflow,
ZeroDimension,
};
use derive_more::{IsVariant, TryUnwrap, Unwrap};
use thiserror::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, IsVariant, TryUnwrap, Unwrap, Error)]
#[non_exhaustive]
#[unwrap(ref, ref_mut)]
#[try_unwrap(ref, ref_mut)]
pub enum Uyyvyy411FrameError {
#[error(transparent)]
ZeroDimension(ZeroDimension),
#[error(transparent)]
WidthAlignment(WidthAlignment),
#[error(transparent)]
InsufficientStride(InsufficientStride),
#[error(transparent)]
InsufficientPlane(InsufficientPlane),
#[error(transparent)]
GeometryOverflow(GeometryOverflow),
#[error(transparent)]
WidthOverflow(WidthOverflow),
}
#[derive(Debug, Clone, Copy)]
pub struct Uyyvyy411Frame<'a> {
uyyvyy: &'a [u8],
width: u32,
height: u32,
stride: u32,
}
impl<'a> Uyyvyy411Frame<'a> {
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn try_new(
uyyvyy: &'a [u8],
width: u32,
height: u32,
stride: u32,
) -> Result<Self, Uyyvyy411FrameError> {
if width == 0 || height == 0 {
return Err(Uyyvyy411FrameError::ZeroDimension(ZeroDimension::new(
width, height,
)));
}
if width & 3 != 0 {
return Err(Uyyvyy411FrameError::WidthAlignment(
WidthAlignment::multiple_of_four(width as usize),
));
}
let min_stride = match width.checked_mul(3) {
Some(v) => v / 2,
None => {
return Err(Uyyvyy411FrameError::WidthOverflow(WidthOverflow::new(
width,
)));
}
};
if stride < min_stride {
return Err(Uyyvyy411FrameError::InsufficientStride(
InsufficientStride::new(stride, min_stride),
));
}
let plane_min = match (stride as usize).checked_mul(height as usize) {
Some(v) => v,
None => {
return Err(Uyyvyy411FrameError::GeometryOverflow(
GeometryOverflow::new(stride, height),
));
}
};
if uyyvyy.len() < plane_min {
return Err(Uyyvyy411FrameError::InsufficientPlane(
InsufficientPlane::new(plane_min, uyyvyy.len()),
));
}
Ok(Self {
uyyvyy,
width,
height,
stride,
})
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn new(uyyvyy: &'a [u8], width: u32, height: u32, stride: u32) -> Self {
match Self::try_new(uyyvyy, width, height, stride) {
Ok(frame) => frame,
Err(_) => panic!("invalid Uyyvyy411Frame dimensions or plane length"),
}
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn uyyvyy(&self) -> &'a [u8] {
self.uyyvyy
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn width(&self) -> u32 {
self.width
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn height(&self) -> u32 {
self.height
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn stride(&self) -> u32 {
self.stride
}
}