use super::{
GeometryOverflow, InsufficientPlane, InsufficientStride, 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 Xyz12FrameError {
#[error(transparent)]
ZeroDimension(ZeroDimension),
#[error(transparent)]
InsufficientStride(InsufficientStride),
#[error(transparent)]
InsufficientPlane(InsufficientPlane),
#[error(transparent)]
GeometryOverflow(GeometryOverflow),
#[error(transparent)]
WidthOverflow(WidthOverflow),
}
#[derive(Debug, Clone, Copy)]
pub struct Xyz12Frame<'a, const BE: bool = false> {
xyz: &'a [u16],
width: u32,
height: u32,
stride: u32,
}
impl<'a, const BE: bool> Xyz12Frame<'a, BE> {
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn try_new(
xyz: &'a [u16],
width: u32,
height: u32,
stride: u32,
) -> Result<Self, Xyz12FrameError> {
if width == 0 || height == 0 {
return Err(Xyz12FrameError::ZeroDimension(ZeroDimension::new(
width, height,
)));
}
let min_stride = match width.checked_mul(3) {
Some(v) => v,
None => return Err(Xyz12FrameError::WidthOverflow(WidthOverflow::new(width))),
};
if stride < min_stride {
return Err(Xyz12FrameError::InsufficientStride(
InsufficientStride::new(stride, min_stride),
));
}
let plane_min = match (stride as usize).checked_mul(height as usize) {
Some(v) => v,
None => {
return Err(Xyz12FrameError::GeometryOverflow(GeometryOverflow::new(
stride, height,
)));
}
};
if xyz.len() < plane_min {
return Err(Xyz12FrameError::InsufficientPlane(InsufficientPlane::new(
plane_min,
xyz.len(),
)));
}
Ok(Self {
xyz,
width,
height,
stride,
})
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn new(xyz: &'a [u16], width: u32, height: u32, stride: u32) -> Self {
match Self::try_new(xyz, width, height, stride) {
Ok(frame) => frame,
Err(_) => panic!("invalid Xyz12Frame dimensions or plane length"),
}
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn xyz(&self) -> &'a [u16] {
self.xyz
}
#[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
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn big_endian(&self) -> bool {
BE
}
}
pub type Xyz12LeFrame<'a> = Xyz12Frame<'a, false>;
pub type Xyz12BeFrame<'a> = Xyz12Frame<'a, true>;