console_display/display/
console_display.rs

1use num_traits::NumCast;
2
3use crate::{
4    constraint,
5    drawing::DynamicCanvas,
6    pixel::Pixel,
7    widget::StaticWidget,
8};
9
10// TODO: Check if this can be const
11pub trait DynamicConsoleDisplay<T: Pixel>: DynamicCanvas<T> {
12    /// Returns the width of the display in a display specific, individually addressable unit (e.g. pixels, characters).
13    fn width(&self) -> usize;
14    /// Returns the height of the display in a display specific, individually addressable unit (e.g. pixels, characters).
15    fn height(&self) -> usize;
16
17    /// Returns a vector containing all the pixels in the display.
18    ///
19    /// # Panics
20    ///
21    /// This function panics if the index of a pixel is out of bounds.
22    /// This should not happen and is subject to change in the future.
23    #[must_use]
24    fn pixels(&self) -> Vec<T::U>
25    where
26        [(); T::WIDTH * T::HEIGHT]:,
27    {
28        let mut pixels = Vec::with_capacity(self.width() * self.height());
29        for y in 0..self.height() {
30            for x in 0..self.width() {
31                pixels.push(
32                    self.pixel(
33                        NumCast::from(x).unwrap(),
34                        NumCast::from(y).unwrap(),
35                    )
36                    .expect(
37                        "Invariant violated, pixel index out of range.",
38                    ),
39                );
40            }
41        }
42        pixels
43    }
44
45    /// Sets the pixels of the display to the provided data.
46    ///
47    /// # Errors
48    ///
49    /// Returns an error if the provided data does not match the dimensions of the display.
50    ///
51    /// # Panics
52    ///
53    /// This function panics if the index of a pixel is out of bounds.
54    /// This should not happen and is subject to change in the future.
55    fn set_pixels(&mut self, data: &[T::U]) -> Result<(), String>
56    where
57        [(); T::WIDTH * T::HEIGHT]:,
58    {
59        if data.len() != self.width() * self.height() {
60            return Err(format!(
61                "Data does not match specified dimensions. Expected length of {}, got {}.",
62                self.width() * self.height(),
63                data.len()
64            ));
65        }
66        for y in 0..self.height() {
67            for x in 0..self.width() {
68                self.set_pixel(
69                    NumCast::from(x).unwrap(),
70                    NumCast::from(y).unwrap(),
71                    data[x + y * self.width()],
72                )
73                .expect("Invariant violated, pixel index out of range.");
74            }
75        }
76        Ok(())
77    }
78
79    #[must_use]
80    fn data(&self) -> &[T];
81
82    fn data_mut(&mut self) -> &mut Box<[T]>;
83}
84
85// TODO: Check if this can be const
86pub trait StaticConsoleDisplay<T: Pixel>:
87    DynamicConsoleDisplay<T> + StaticWidget
88{
89    const WIDTH: usize;
90    const HEIGHT: usize;
91    // TODO: Update docs
92    /// Returns a bool representing the state of the pixel at the specified coordinate.
93    ///
94    /// # Examples
95    ///
96    /// ```
97    /// #![allow(incomplete_features)]
98    /// #![feature(generic_const_exprs)]
99    ///
100    /// use console_display::{
101    ///     console_display::DynamicConsoleDisplay,
102    ///     display_driver::DisplayDriver,
103    ///     pixel::monochrome_pixel::SinglePixel,
104    ///     pixel_display::StaticPixelDisplay,
105    ///     drawing::DynamicCanvas
106    /// };
107    ///
108    /// let disp: DisplayDriver<StaticPixelDisplay<SinglePixel, 6, 6>> = DisplayDriver::new(
109    ///     StaticPixelDisplay::<SinglePixel, 6, 6>::new_from_data(
110    ///         &[
111    ///             true, true, true, true,  true, true, // 0
112    ///             true, true, true, true,  true, true, // 1
113    ///             true, true, true, false, true, true, //-2-
114    ///             true, true, true, true,  true, true, // 3
115    ///             true, true, true, true,  true, true, // 4
116    ///             true, true, true, true,  true, true, // 5
117    ///         ] //  0     1     2   --3--    4     5
118    ///     )
119    /// );
120    /// // Replace with actual error handling
121    ///
122    /// let pixel = disp.pixel(3, 2);
123    ///
124    /// assert_eq!(pixel, Ok(false));
125    ///
126    /// let pixel = disp.pixel(5, 6);
127    ///
128    /// assert!(matches!(pixel, Err(_)));
129    /// ```
130    ///
131    /// # Errors
132    ///
133    /// Returns an error if the pixel coordinates are out of bounds.
134    ///
135    /// # Panics
136    ///
137    /// If the index of a subpixel is out of bounds.
138    /// This should not happen and is subject to change in the future.
139    #[must_use]
140    fn pixel_static<const X: usize, const Y: usize>(&self) -> T::U
141    where
142        constraint!(X <= Self::WIDTH):,
143        constraint!(Y <= Self::HEIGHT):,
144        constraint!(X % T::WIDTH < T::WIDTH):,
145        constraint!(Y % T::HEIGHT < T::HEIGHT):,
146        [(); T::WIDTH * T::HEIGHT]:,
147    {
148        let pixel = &self.data()
149            [X / T::WIDTH + Y / T::HEIGHT * Self::WIDTH_CHARACTERS];
150        pixel.subpixel_static::<{ X % T::WIDTH }, { Y % T::HEIGHT }>()
151    }
152    // TODO: Update docs
153    /// Set a pixel at the specified coordinate with a given value.
154    ///
155    /// # Errors
156    ///
157    /// Returns an error if the pixel coordinates are out of bounds.
158    ///
159    /// # Panics
160    ///
161    /// If the index of a subpixel is out of bounds.
162    /// This should not happen and is subject to change in the future.
163    fn set_pixel_static<const X: usize, const Y: usize>(
164        &mut self,
165        value: T::U,
166    ) where
167        constraint!(X <= Self::WIDTH):,
168        constraint!(Y <= Self::HEIGHT):,
169        constraint!(X % T::WIDTH < T::WIDTH):,
170        constraint!(Y % T::HEIGHT < T::HEIGHT):,
171        [(); T::WIDTH * T::HEIGHT]:,
172    {
173        let pixel = &mut self.data_mut()
174            [X / T::WIDTH + Y / T::HEIGHT * Self::WIDTH_CHARACTERS];
175        pixel.set_subpixel_static::<{ X % T::WIDTH }, { Y % T::HEIGHT }>(
176            value,
177        );
178    }
179}