1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#![allow(non_snake_case)]

/// Get luminance from rgb.
///
/// # Examples
///
/// ```
/// let lum = luminance([255, 0, 255]);
/// assert_eq!(6, lum);
/// ```
pub fn luminance(rgb: [u8; 3]) -> f64 {
    let mut arr = [0.; 3];
    for i in 0..=2 {
        let color = (rgb[i] as f64) / 255.;
        arr[i] = if color <= 0.03928 {
            color / 12.92
        } else {
            ((color + 0.055) / 1.055).powf(2.4)
        };
    }
    arr[0] * 0.2126 + arr[1] * 0.7152 + arr[2] * 0.0722
}

/// Create new rgb.
/// ```
///     let rgb = RGB([0, 0, 0]);
/// ```
#[derive(Debug)]
pub struct RGB(pub [u8; 3]);

impl RGB {
    pub fn value(&self) -> [u8; 3] {
        self.0
    }
    /// inverted rgb color.
    /// ```
    ///     let inverted_rgb = rgb.inverted();
    ///     assert_eq!([255, 255, 255], rgb.0);
    /// ```
    pub fn inverted(&mut self) -> &mut Self {
        let rgb = &mut self.0;
        for color in rgb.iter_mut() {
            *color = 255 - *color;
        }
        self
    }
    /// convart rgb to hex.
    /// ```
    ///     let color_hex = rgb.to_hex();
    ///     assert_eq!("ffffff", color_hex);
    /// ```
    pub fn to_hex(&self) -> String {
        let rgb = self.0;
        format!("{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2])
    }
    /// Get contrast ratio.
    /// ```
    ///     let contrast = rgb.contrast_ratio([0, 0, 0]);
    ///     assert_eq!(21, contrast);
    /// ```
    pub fn contrast_ratio(&self, rgb: [u8; 3]) -> f64 {
        let lum1 = luminance(rgb);
        let lum2 = luminance(self.0);
        (lum1.max(lum2) + 0.05) / (lum1.min(lum2) + 0.05)
    }
    /// Create RGB from hex.
    /// ```
    ///     let rgb2 = RGB::from_hex("#00ff00");
    ///     assert_eq!([0, 255, 00], rgb2.0);
    /// ```
    pub fn from_hex(hex_value: &str) -> Result<Self, &str> {
        let hex = hex_value.trim_start_matches("#");
        let mut rgb = [0u8; 3];
        if hex.len() != 6 {
            return Err("Invalid Color");
        }
        for i in 0..=2 {
            let x = i * 2;
            match u8::from_str_radix(&hex[x..(x + 2)], 16) {
                Ok(color) => rgb[i] = color,
                Err(_) => return Err("Invalid Digit"),
            }
        }
        Ok(Self(rgb))
    }
}