unicode-plot 0.1.0

unicode-plot-rs: Unicode terminal plotting library for Rust
Documentation
use crate::canvas::Transform2D;
use crate::color::CanvasColor;

#[derive(Debug, Clone, PartialEq)]
pub(crate) struct CanvasCore<T: Default + Copy> {
    pub(crate) char_width: usize,
    pub(crate) char_height: usize,
    pub(crate) pixel_width: usize,
    pub(crate) pixel_height: usize,
    pub(crate) transform: Transform2D,
    pub(crate) grid: Vec<T>,
    pub(crate) colors: Vec<u8>,
}

impl<T: Default + Copy> CanvasCore<T> {
    /// Creates a new canvas backing store with initialized grid and colors.
    ///
    /// # Panics
    ///
    /// Panics when `char_width * char_height` overflows `usize`.
    #[must_use]
    pub(crate) fn new(
        char_width: usize,
        char_height: usize,
        pixel_width: usize,
        pixel_height: usize,
        transform: Transform2D,
    ) -> Self {
        let Some(cell_count) = char_width.checked_mul(char_height) else {
            panic!("canvas dimensions overflow allocation size")
        };

        Self {
            char_width,
            char_height,
            pixel_width,
            pixel_height,
            transform,
            grid: vec![T::default(); cell_count],
            colors: vec![CanvasColor::NORMAL.as_u8(); cell_count],
        }
    }
}

#[cfg(test)]
mod tests {
    use super::CanvasCore;
    use crate::canvas::{AxisTransform, Scale, Transform2D};
    use crate::color::CanvasColor;

    #[test]
    fn constructor_allocates_grid_and_color_storage_for_each_cell() {
        let x = AxisTransform::new(0.0, 1.0, 8, Scale::Identity, false)
            .unwrap_or_else(|| unreachable!("valid transform"));
        let y = AxisTransform::new(0.0, 1.0, 12, Scale::Identity, true)
            .unwrap_or_else(|| unreachable!("valid transform"));
        let transform = Transform2D::new(x, y);
        let core = CanvasCore::<u16>::new(4, 3, 8, 12, transform);

        assert_eq!(core.char_width, 4);
        assert_eq!(core.char_height, 3);
        assert_eq!(core.pixel_width, 8);
        assert_eq!(core.pixel_height, 12);
        assert_eq!(core.transform, transform);
        assert_eq!(core.grid.len(), 12);
        assert_eq!(core.colors.len(), 12);
        assert!(core.grid.iter().all(|cell| *cell == 0));
        assert!(
            core.colors
                .iter()
                .all(|color| *color == CanvasColor::NORMAL.as_u8())
        );
    }
}