anitty 0.1.0

Anime character animation rendering for terminals
Documentation
use crate::Error;

/// A nonempty, tightly packed RGBA8 image.
///
/// Pixels are in row-major order, starting at the top left, with four bytes per
/// pixel (red, green, blue, alpha), sRGB colors and straight (not premultiplied)
/// alpha. There is no row padding.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RgbaFrame {
    width: u32,
    height: u32,
    pixels: Vec<u8>,
}

impl RgbaFrame {
    /// Validate and take ownership of an RGBA buffer without copying it.
    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"))
    }

    // Allocate on first use and retain capacity when the output size changes.
    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
    }

    /// Mutate pixels without changing the validated buffer length.
    pub fn pixels_mut(&mut self) -> &mut [u8] {
        &mut self.pixels
    }
}