lighthouse_protocol/utils/
color.rs

1use rand::{prelude::Distribution, distributions::Standard};
2use serde::{Deserialize, Serialize};
3
4/// An RGB color.
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
6pub struct Color {
7    #[serde(rename = "R")]
8    pub red: u8,
9    #[serde(rename = "G")]
10    pub green: u8,
11    #[serde(rename = "B")]
12    pub blue: u8,
13}
14
15impl Color {
16    pub const BLACK: Self = Self { red: 0, green: 0, blue: 0 };
17    pub const WHITE: Self = Self { red: 255, green: 255, blue: 255 };
18    pub const RED: Self = Self { red: 255, green: 0, blue: 0 };
19    pub const GREEN: Self = Self { red: 0, green: 255, blue: 0 };
20    pub const BLUE: Self = Self { red: 0, green: 0, blue: 255 };
21    pub const YELLOW: Self = Self { red: 255, green: 255, blue: 0 };
22    pub const CYAN: Self = Self { red: 0, green: 255, blue: 255 };
23    pub const MAGENTA: Self = Self { red: 255, green: 0, blue: 255 };
24
25    /// Creates a new color from the given RGB components.
26    pub const fn new(red: u8, green: u8, blue: u8) -> Self {
27        Self { red, green, blue }
28    }
29}
30
31impl From<[u8; 3]> for Color {
32    fn from([red, green, blue]: [u8; 3]) -> Self {
33        Self { red, green, blue }
34    }
35}
36
37impl From<Color> for [u8; 3] {
38    fn from(color: Color) -> [u8; 3] {
39        [color.red, color.green, color.blue]
40    }
41}
42
43impl Distribution<Color> for Standard {
44    fn sample<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> Color {
45        Color::new(rng.gen(), rng.gen(), rng.gen())
46    }
47}
48
49#[cfg(test)]
50mod tests {
51    use crate::Color;
52
53    #[test]
54    fn to_array() {
55        assert_eq!(<[u8; 3]>::from(Color::BLACK), [0, 0, 0]);
56        assert_eq!(<[u8; 3]>::from(Color::RED), [0xFF, 0, 0]);
57        assert_eq!(<[u8; 3]>::from(Color::GREEN), [0, 0xFF, 0]);
58        assert_eq!(<[u8; 3]>::from(Color::BLUE), [0, 0, 0xFF]);
59        assert_eq!(<[u8; 3]>::from(Color::new(1, 2, 3)), [1, 2, 3]);
60    }
61
62    #[test]
63    fn from_array() {
64        assert_eq!(Color::from([0, 0, 0]), Color::BLACK);
65        assert_eq!(Color::from([0xFF, 0, 0]), Color::RED);
66        assert_eq!(Color::from([0, 0xFF, 0]), Color::GREEN);
67        assert_eq!(Color::from([0, 0, 0xFF]), Color::BLUE);
68        assert_eq!(Color::from([1, 2, 3]), Color::new(1, 2, 3));
69    }
70}