1#![allow(non_snake_case)]
2
3pub 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#[derive(Debug)]
29pub struct RGB(pub [u8; 3]);
30
31impl RGB {
32 pub fn value(&self) -> [u8; 3] {
33 self.0
34 }
35 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 pub fn to_hex(&self) -> String {
53 let rgb = self.0;
54 format!("{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2])
55 }
56 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 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}