Skip to main content

epd_datafuri/
color.rs

1//! B/W Color for EPDs
2
3#[cfg(feature = "graphics")]
4use embedded_graphics::pixelcolor::BinaryColor;
5// #[cfg(feature = "graphics")]
6// use embedded_graphics::pixelcolor::Gray2;
7#[cfg(feature = "graphics")]
8pub use BinaryColor::Off as Black;
9#[cfg(feature = "graphics")]
10pub use BinaryColor::On as White;
11#[cfg(feature = "graphics")]
12pub use BinaryColor::On as Red;
13
14/// Black/White colors
15#[derive(Clone, Copy, PartialEq, Debug)]
16pub enum Color {
17    /// Black color
18    Black,
19    /// White color
20    White,
21}
22
23impl Color {
24    /// Get the color encoding of the color for one bit
25    pub fn get_bit_value(self) -> u8 {
26        match self {
27            Color::White => 1_u8,
28            Color::Black => 0_u8,
29        }
30    }
31
32    /// Gets a full byte of black or white pixels
33    pub fn get_byte_value(self) -> u8 {
34        match self {
35            Color::White => 0xff,
36            Color::Black => 0x00,
37        }
38    }
39
40    /// Parses from u8 to Color
41    fn from_u8(val: u8) -> Self {
42        match val {
43            0 => Color::Black,
44            1 => Color::White,
45            e => panic!(
46                "DisplayColor only parses 0 and 1 (Black and White) and not `{}`",
47                e
48            ),
49        }
50    }
51
52    /// Returns the inverse of the given color.
53    ///
54    /// Black returns White and White returns Black
55    pub fn inverse(self) -> Color {
56        match self {
57            Color::White => Color::Black,
58            Color::Black => Color::White,
59        }
60    }
61}
62
63impl From<u8> for Color {
64    fn from(value: u8) -> Self {
65        Color::from_u8(value)
66    }
67}
68
69#[cfg(test)]
70mod tests {
71    use super::*;
72
73    #[test]
74    fn from_u8() {
75        assert_eq!(Color::Black, Color::from(0u8));
76        assert_eq!(Color::White, Color::from(1u8));
77    }
78
79    // test all values aside from 0 and 1 which all should panic
80    #[test]
81    fn from_u8_panic() {
82        for val in 2..=u8::MAX {
83            extern crate std;
84            let result = std::panic::catch_unwind(|| Color::from(val));
85            assert!(result.is_err());
86        }
87    }
88
89    #[test]
90    fn u8_conversion_black() {
91        assert_eq!(Color::from(Color::Black.get_bit_value()), Color::Black);
92        assert_eq!(Color::from(0u8).get_bit_value(), 0u8);
93    }
94
95    #[test]
96    fn u8_conversion_white() {
97        assert_eq!(Color::from(Color::White.get_bit_value()), Color::White);
98        assert_eq!(Color::from(1u8).get_bit_value(), 1u8);
99    }
100}