1 use core::ColorInterface;
2 use HSL;
3 
4 #[derive(Debug, Copy, Clone, PartialEq)]
5 pub struct RGB {
6     // range 0 -255
7     r: u8,
8     g: u8,
9     b: u8,
10 }
11 
12 impl RGB {
new(r: u8, g: u8, b: u8) -> RGB13     pub fn new(r: u8, g: u8, b: u8) -> RGB {
14         RGB { r, g, b }
15     }
16 
unpack(&self) -> (u8, u8, u8)17     pub fn unpack(&self) -> (u8, u8, u8) {
18         (self.r, self.g, self.b)
19     }
20 
rgb_to_hsl(&self) -> HSL21     pub fn rgb_to_hsl(&self) -> HSL {
22         let (r, g, b) = self.unpack();
23         let r = r as f32 / 255.0;
24         let g = g as f32 / 255.0;
25         let b = b as f32 / 255.0;
26 
27         let max = r.max(g).max(b);
28         let min = r.min(g).min(b);
29         let mut h: f32 = 0.0;
30         let mut s: f32 = 0.0;
31         let l = (max + min) / 2.0;
32 
33         if max != min {
34             let d = max - min;
35             s = if l > 0.5 { d / (2.0 - max - min) } else { d / (max + min) };
36             if max == r {
37                 h = (g - b) / d + (if g < b { 6.0 } else { 0.0 });
38             } else if max == g {
39                 h = (b - r) / d + 2.0;
40             } else {
41                 h = (r - g) / d + 4.0;
42             }
43             h /= 6.0;
44         }
45         return HSL::new(h, s, l);
46     }
47 }
48 
49 impl ColorInterface for RGB {
to_color_str(&self) -> String50     fn to_color_str(&self) -> String {
51         format!("{};{};{}", self.r, self.g, self.b)
52     }
to_hsl(&self) -> HSL53     fn to_hsl(&self) -> HSL { self.rgb_to_hsl() }
54 }
55 
56 #[cfg(test)]
57 mod tests {
58     use super::*;
59 
60     #[test]
test_rgb_2_hsl_1()61     fn test_rgb_2_hsl_1() {
62         let hsl = HSL::new(0.69934636, 0.49999997, 0.60);
63         let rgb = RGB::new(122, 102, 204);
64 
65         assert_eq!(hsl, rgb.rgb_to_hsl());
66     }
67 
68     #[test]
test_rgb_2_hsl_2()69     fn test_rgb_2_hsl_2() {
70         let hsl = HSL::new(0.0, 0.0, 0.60);
71         let rgb = RGB::new(153, 153, 153);
72         assert_eq!(hsl, rgb.rgb_to_hsl());
73     }
74 
75     #[test]
test_rgb_2_hsl_3()76     fn test_rgb_2_hsl_3() {
77         let hsl = HSL::new(0.7012987, 0.50326794, 0.30);
78         let rgb = RGB::new(54, 38, 115);
79 
80         assert_eq!(hsl, rgb.rgb_to_hsl());
81     }
82 
83     #[test]
test_rgb_2_hsl_4()84     fn test_rgb_2_hsl_4() {
85         let hsl = HSL::new(0.08333334, 1.0, 0.6862745);
86         let rgb = RGB::new(255, 175, 95);
87 
88         assert_eq!(hsl, rgb.rgb_to_hsl());
89     }
90 }