charm_ui/
color.rs

1use sdl2::pixels::Color as SdlColor;
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
4pub struct Color {
5    pub r: u8,
6    pub g: u8,
7    pub b: u8,
8    pub a: u8,
9}
10
11impl From<(u8, u8, u8)> for Color {
12    fn from((r, g, b): (u8, u8, u8)) -> Self {
13        Self { r, g, b, a: 255 }
14    }
15}
16
17impl From<(u8, u8, u8, u8)> for Color {
18    fn from((r, g, b, a): (u8, u8, u8, u8)) -> Self {
19        Self { r, g, b, a }
20    }
21}
22
23impl From<u32> for Color {
24    fn from(input: u32) -> Self {
25        let r = ((input >> 3 * 8) & 0xFF) as u8;
26        let g = ((input >> 2 * 8) & 0xFF) as u8;
27        let b = ((input >> 1 * 8) & 0xFF) as u8;
28        let a = ((input >> 0 * 8) & 0xFF) as u8;
29        Self { r, g, b, a }
30    }
31}
32
33impl From<Color> for SdlColor {
34    fn from(Color { r, g, b, a }: Color) -> Self {
35        SdlColor::RGBA(r, g, b, a)
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    use super::*;
42
43    #[test]
44    fn test_color_from_impl() {
45        let c = Color::from(0xFF0022EE);
46        assert_eq!(c.r, 0xFF);
47        assert_eq!(c.g, 0x00);
48        assert_eq!(c.b, 0x22);
49        assert_eq!(c.a, 0xEE);
50    }
51}