Color/
lib.rs

1#![allow(non_snake_case)]
2
3/// Get luminance from rgb.
4///
5/// # Examples
6///
7/// ```
8/// let lum = luminance([255, 0, 255]);
9/// assert_eq!(6, lum);
10/// ```
11pub fn luminance(rgb: [u8; 3]) -> f64 {
12    let mut arr = [0.; 3];
13    for i in 0..=2 {
14        let color = (rgb[i] as f64) / 255.;
15        arr[i] = if color <= 0.03928 {
16            color / 12.92
17        } else {
18            ((color + 0.055) / 1.055).powf(2.4)
19        };
20    }
21    arr[0] * 0.2126 + arr[1] * 0.7152 + arr[2] * 0.0722
22}
23
24/// Create new rgb.
25/// ```
26///     let rgb = RGB([0, 0, 0]);
27/// ```
28#[derive(Debug)]
29pub struct RGB(pub [u8; 3]);
30
31impl RGB {
32    pub fn value(&self) -> [u8; 3] {
33        self.0
34    }
35    /// inverted rgb color.
36    /// ```
37    ///     let inverted_rgb = rgb.inverted();
38    ///     assert_eq!([255, 255, 255], rgb.0);
39    /// ```
40    pub fn inverted(&mut self) -> &mut Self {
41        let rgb = &mut self.0;
42        for color in rgb.iter_mut() {
43            *color = 255 - *color;
44        }
45        self
46    }
47    /// convart rgb to hex.
48    /// ```
49    ///     let color_hex = rgb.to_hex();
50    ///     assert_eq!("ffffff", color_hex);
51    /// ```
52    pub fn to_hex(&self) -> String {
53        let rgb = self.0;
54        format!("{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2])
55    }
56    /// Get contrast ratio.
57    /// ```
58    ///     let contrast = rgb.contrast_ratio([0, 0, 0]);
59    ///     assert_eq!(21, contrast);
60    /// ```
61    pub fn contrast_ratio(&self, rgb: [u8; 3]) -> f64 {
62        let lum1 = luminance(rgb);
63        let lum2 = luminance(self.0);
64        (lum1.max(lum2) + 0.05) / (lum1.min(lum2) + 0.05)
65    }
66    /// Create RGB from hex.
67    /// ```
68    ///     let rgb2 = RGB::from_hex("#00ff00");
69    ///     assert_eq!([0, 255, 00], rgb2.0);
70    /// ```
71    pub fn from_hex(hex_value: &str) -> Result<Self, &str> {
72        let hex = hex_value.trim_start_matches("#");
73        let mut rgb = [0u8; 3];
74        if hex.len() != 6 {
75            return Err("Invalid Color");
76        }
77        for i in 0..=2 {
78            let x = i * 2;
79            match u8::from_str_radix(&hex[x..(x + 2)], 16) {
80                Ok(color) => rgb[i] = color,
81                Err(_) => return Err("Invalid Digit"),
82            }
83        }
84        Ok(Self(rgb))
85    }
86}