use crate::Error;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RgbaFrame {
width: u32,
height: u32,
pixels: Vec<u8>,
}
impl RgbaFrame {
pub fn new(width: u32, height: u32, pixels: Vec<u8>) -> Result<Self, Error> {
let len = Self::byte_len(width, height)?;
if pixels.len() != len {
return Err(Error::InvalidFrame(
"buffer length must be width * height * 4",
));
}
Ok(Self {
width,
height,
pixels,
})
}
pub(crate) fn byte_len(width: u32, height: u32) -> Result<usize, Error> {
if width == 0 || height == 0 {
return Err(Error::InvalidFrame("dimensions must be nonzero"));
}
u64::from(width)
.checked_mul(u64::from(height))
.and_then(|pixels| pixels.checked_mul(4))
.and_then(|bytes| usize::try_from(bytes).ok())
.filter(|&bytes| bytes <= isize::MAX as usize)
.ok_or(Error::InvalidFrame("dimensions exceed addressable memory"))
}
pub(crate) fn prepare_buffer(
buffer: &mut Option<Self>,
width: u32,
height: u32,
) -> Result<&mut Self, Error> {
let len = Self::byte_len(width, height)?;
let frame = buffer.get_or_insert_with(|| Self {
width,
height,
pixels: Vec::new(),
});
frame.pixels.resize(len, 0);
frame.width = width;
frame.height = height;
Ok(frame)
}
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
pub fn pixels(&self) -> &[u8] {
&self.pixels
}
pub fn pixels_mut(&mut self) -> &mut [u8] {
&mut self.pixels
}
}