ssd1680/
color.rs

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