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 Rgbf16FrameError {
#[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 Rgbf16Frame<'a, const BE: bool = false> {
rgb: &'a [half::f16],
width: u32,
height: u32,
stride: u32,
}
pub type Rgbf16LeFrame<'a> = Rgbf16Frame<'a, false>;
pub type Rgbf16BeFrame<'a> = Rgbf16Frame<'a, true>;
impl<'a, const BE: bool> Rgbf16Frame<'a, BE> {
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn try_new(
rgb: &'a [half::f16],
width: u32,
height: u32,
stride: u32,
) -> Result<Self, Rgbf16FrameError> {
if width == 0 || height == 0 {
return Err(Rgbf16FrameError::ZeroDimension(ZeroDimension::new(
width, height,
)));
}
let min_stride = match width.checked_mul(3) {
Some(v) => v,
None => return Err(Rgbf16FrameError::WidthOverflow(WidthOverflow::new(width))),
};
if stride < min_stride {
return Err(Rgbf16FrameError::InsufficientStride(
InsufficientStride::new(stride, min_stride),
));
}
let plane_min = match (stride as usize).checked_mul(height as usize) {
Some(v) => v,
None => {
return Err(Rgbf16FrameError::GeometryOverflow(GeometryOverflow::new(
stride, height,
)));
}
};
if rgb.len() < plane_min {
return Err(Rgbf16FrameError::InsufficientPlane(InsufficientPlane::new(
plane_min,
rgb.len(),
)));
}
Ok(Self {
rgb,
width,
height,
stride,
})
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn new(rgb: &'a [half::f16], width: u32, height: u32, stride: u32) -> Self {
match Self::try_new(rgb, width, height, stride) {
Ok(frame) => frame,
Err(_) => panic!("invalid Rgbf16Frame dimensions or plane length"),
}
}
#[cfg_attr(not(tarpaulin), inline(always))]
pub const fn rgb(&self) -> &'a [half::f16] {
self.rgb
}
#[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 is_be(&self) -> bool {
BE
}
}