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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
use std::fmt::{Display, Formatter};

use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum DefaultColor {
    Black,
    DarkBlue,
    DarkGreen,
    DarkAqua,
    DarkRed,
    DarkPurple,
    Gold,
    Gray,
    DarkGray,
    Blue,
    Green,
    Aqua,
    Red,
    LightPurple,
    Yellow,
    White,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(try_from = "String", into = "String")]
pub struct HexColor {
    pub r: u8,
    pub g: u8,
    pub b: u8,
}

#[derive(Debug)]
pub enum HexColorError {
    BadHex
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(untagged)]
pub enum Color {
    Default(DefaultColor),
    Hex(HexColor),
}

impl Display for HexColorError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            HexColorError::BadHex => write!(f, "Bad hex string"),
        }
    }
}

impl TryFrom<String> for HexColor {
    type Error = HexColorError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        match value.len() == 7 {
            true => {
                let value_hex_num = i32::from_str_radix(&value[1..], 16)
                    .map_err(|_| HexColorError::BadHex)?;
                Ok(HexColor {
                    r: (value_hex_num >> 16 & 0xff) as u8,
                    g: (value_hex_num >> 8 & 0xff) as u8,
                    b: (value_hex_num & 0xff) as u8,
                })
            },
            false => Err(HexColorError::BadHex),
        }
    }
}

impl Display for HexColor {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "#{:02x}{:02x}{:02x}", self.r, self.g, self.b)
    }
}

impl From<HexColor> for String {
    fn from(color: HexColor) -> Self {
        color.to_string()
    }
}

impl From<DefaultColor> for Color {
    fn from(color: DefaultColor) -> Self {
        Color::Default(color)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn success_hex_color_test() {
        let hex_color = HexColor::try_from("#0f0f0f".to_string()).unwrap();
        assert_eq!(hex_color.r, 15);
        assert_eq!(hex_color.g, 15);
        assert_eq!(hex_color.b, 15);
        assert_eq!(hex_color.to_string(), "#0f0f0f");
    }

    #[test]
    fn success_color_test() {
        let color: Color = serde_json::from_str("\"#0f0f0f\"").unwrap();
        assert_eq!(color, Color::Hex(HexColor::try_from("#0f0f0f".to_string()).unwrap()))
    }

}