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
87
88
89
90
91
use css_color_parser::Color as CssColor;

use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};
use serde_json::Value;

#[derive(Debug, PartialEq, Copy, Clone)]
pub struct Color {
    pub red: u8,
    pub green: u8,
    pub blue: u8,
    pub alpha: f32,
}

impl Serialize for Color {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&*self.to_string())
    }
}

impl<'de> Deserialize<'de> for Color {
    fn deserialize<D>(deserializer: D) -> Result<Color, D::Error>
    where
        D: Deserializer<'de>,
    {
        match Value::deserialize(deserializer)? {
            Value::String(color) => Ok(color.into()),
            _ => Ok(Color::transparent()),
        }
    }
}

impl Color {
    pub fn new(rgb: [u8; 3], alpha: f32) -> Self {
        Color {
            red: rgb[0],
            green: rgb[1],
            blue: rgb[2],
            alpha: alpha,
        }
    }

    pub fn transparent() -> Color {
        "rgba(0,0,0,0)".into()
    }

    pub fn to_string(&self) -> String {
        format!("rgba({}, {}, {}, {})", self.red, self.green, self.blue, self.alpha as i32)
    }
}

impl From<CssColor> for Color {
    fn from(color: CssColor) -> Color {
        Color {
            alpha: color.a,
            green: color.g,
            blue: color.b,
            red: color.r,
        }
    }
}

impl<'a> From<&'a str> for Color {
    fn from(color: &str) -> Color {
        let default_color = CssColor {
            r: 0,
            g: 0,
            b: 0,
            a: 0.0,
        };

        let color = color.parse::<CssColor>().unwrap_or(default_color);

        Color {
            alpha: color.a,
            green: color.g,
            blue: color.b,
            red: color.r,
        }
    }
}

impl From<String> for Color {
    fn from(color: String) -> Color {
        let color = &*color;
        color.into()
    }
}