iris_lib/
color.rs

1use std::fmt;
2
3/// Represents a color, holding red, green, blue and alpha values as `u8` each.
4///
5#[derive(Debug, Copy, Clone, PartialEq)]
6pub struct Color {
7    pub r: u8,
8    pub g: u8,
9    pub b: u8,
10    pub a: u8,
11}
12
13impl fmt::Display for Color {
14    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
15        write!(f, "{{ R: {}, G: {}, B: {}, A: {} }}", self.r, self.g, self.b, self.a)
16    }
17}
18
19/// Indexing implementation for the `Color` struct using `ColorChannel` as index.
20///
21/// # Examples
22///
23/// ```
24/// use iris_lib::color::{Color, ColorChannel};
25///
26/// let color = Color { r: 1, g: 2, b: 3, a: 4 };
27/// assert_eq!(1, color[ColorChannel::R]);
28/// assert_eq!(2, color[ColorChannel::G]);
29/// assert_eq!(3, color[ColorChannel::B]);
30/// assert_eq!(4, color[ColorChannel::A]);
31/// ```
32///
33impl ::std::ops::Index<ColorChannel> for Color {
34    type Output = u8;
35    fn index(&self, index: ColorChannel) -> &Self::Output {
36        match index {
37            ColorChannel::R => &self.r,
38            ColorChannel::G => &self.g,
39            ColorChannel::B => &self.b,
40            ColorChannel::A => &self.a,
41        }
42    }
43}
44
45/// Represents possible color channels in a RGBA color.
46///
47#[derive(Debug, Copy, Clone, PartialEq)]
48pub enum ColorChannel {
49    R,
50    G,
51    B,
52    A,
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn color_index_ut() {
61        let color = Color { r: 1, g: 2, b: 3, a: 4 };
62        assert_eq!(1, color[ColorChannel::R]);
63        assert_eq!(2, color[ColorChannel::G]);
64        assert_eq!(3, color[ColorChannel::B]);
65        assert_eq!(4, color[ColorChannel::A]);
66    }
67}