mdxt/
color.rs

1// use this module to automate the creation of CSS files.
2
3use crate::utils::{into_v32, from_v32};
4use lazy_static::lazy_static;
5
6#[derive(Clone, Debug)]
7pub struct Color {
8    pub name: String,
9    pub r: u8,
10    pub g: u8,
11    pub b: u8
12}
13
14/// It returns the default colors and their names used by the engine.
15pub fn colors() -> Vec<Color> {
16    COLORS.to_vec()
17}
18
19impl Color {
20
21    pub fn new(name: &str, r: u8, g: u8, b: u8) -> Self {
22        Color {
23            name: name.to_string(), r, g, b
24        }
25    }
26
27    pub fn complement(&self) -> Self {
28        Color {
29            name: self.name.clone(),
30            r: 255 - self.r,
31            g: 255 - self.g,
32            b: 255 - self.b
33        }
34    }
35
36    pub fn to_rgb(&self) -> String {
37        format!("rgb({}, {}, {})", self.r, self.g, self.b)
38    }
39
40    pub fn to_hex(&self) -> String {
41        format!(
42            "#{}{}{}",
43            from_v32(&into_v32(&format!("{:#04x}", self.r))[2..4]),
44            from_v32(&into_v32(&format!("{:#04x}", self.g))[2..4]),
45            from_v32(&into_v32(&format!("{:#04x}", self.b))[2..4])
46        )
47    }
48
49}
50
51lazy_static! {
52    pub static ref COLORS: Vec<Color> = vec![
53        Color::new("black", 0, 0, 0),
54        Color::new("dark", 64, 64, 64),
55        Color::new("gray", 128, 128, 128),
56        Color::new("lightgray", 192, 192, 192),
57        Color::new("white", 255, 255, 255),
58        Color::new("red", 192, 32, 32),
59        Color::new("green", 32, 192, 32),
60        Color::new("slateblue", 64, 64, 192),
61        Color::new("blue", 32, 32, 192),
62        Color::new("aqua", 64, 192, 255),
63        Color::new("emerald", 64, 192, 64),
64        Color::new("turquoise", 64, 255, 192),
65        Color::new("seagreen", 32, 192, 192),
66        Color::new("violet", 192, 64, 255),
67        Color::new("pink", 255, 64, 192),
68        Color::new("grassgreen", 192, 255, 64),
69        Color::new("gold", 255, 192, 64),
70        Color::new("brown", 192, 128, 32),
71    ];
72
73    pub static ref COLOR_NAMES: Vec<Vec<u32>> = COLORS.iter().map(
74        |color| into_v32(&color.name)
75    ).collect();
76}
77
78#[cfg(test)]
79mod tests {
80    use crate::color::Color;
81
82    #[test]
83    fn hex_color_test() {
84        assert_eq!(Color::new("", 0, 0, 0).to_hex(), String::from("#000000"));
85        assert_eq!(Color::new("", 0, 255, 0).to_hex(), String::from("#00ff00"));
86        assert_eq!(Color::new("", 64, 255, 64).to_hex(), String::from("#40ff40"));
87    }
88
89}