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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
// Copyright (c) 2016-2017 Martijn Rijkeboer <[email protected]>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::error;
use std::fmt;
use std::result::Result;

const HEX_STRING_LENGTH: usize = 7;

/// A structure representing a color (RGB).
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
pub struct Color {
    /// Red part of the color.
    pub red: u8,

    /// Green part of the color.
    pub green: u8,

    /// Blue part of the color.
    pub blue: u8,
}

impl Color {
    /// Attempts to create a color from an hex string.
    ///
    /// # Errors
    ///
    /// This function will return an error when the hex string is not a valid
    /// color.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use kpdb::Color;
    /// # use kpdb::ColorError;
    ///
    /// # fn convert() -> Result<(), ColorError> {
    /// let color = Color::from_hex_string("#abcdef")?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_hex_string(hex: &str) -> Result<Color, ColorError> {
        let chars: Vec<char> = hex.chars().collect();
        let count: usize = chars.len();
        if count < HEX_STRING_LENGTH {
            Err(ColorError::HexStringTooShort)
        } else if count > HEX_STRING_LENGTH {
            Err(ColorError::HexStringTooLong)
        } else if !hex.starts_with("#") {
            Err(ColorError::HexStringNoHashSign)
        } else {
            let red = from_hex_string_red(hex)?;
            let green = from_hex_string_green(hex)?;
            let blue = from_hex_string_blue(hex)?;
            Ok(Color {
                red: red,
                green: green,
                blue: blue,
            })
        }
    }

    /// Gets the hex string representation of the supplied color.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use kpdb::Color;
    ///
    /// let color = Color { red: 171, green: 205, blue: 239 };
    /// let hex = color.to_hex_string();
    /// ```
    pub fn to_hex_string(&self) -> String {
        format!("#{0:02x}{1:02x}{2:02x}", self.red, self.green, self.blue)
    }
}

/// Error type for color conversion errors.
#[derive(Debug, PartialEq)]
pub enum ColorError {
    /// The hex string doens't start with a '#' character.
    HexStringNoHashSign,

    /// The hex string is too long.
    HexStringTooLong,

    /// The hex string is too short.
    HexStringTooShort,

    /// The hex string's blue part is an invalid value.
    InvalidBlueValue,

    /// The hex string's green part is an invalid value.
    InvalidGreenValue,

    /// The hex string's red part is an invalid value.
    InvalidRedValue,
}

impl ColorError {
    fn msg(&self) -> &str {
        match *self {
            ColorError::HexStringNoHashSign => "hex string without hash sign",
            ColorError::HexStringTooLong => "hex string too long",
            ColorError::HexStringTooShort => "hex string too short",
            ColorError::InvalidBlueValue => "invalid blue value",
            ColorError::InvalidGreenValue => "invalid green value",
            ColorError::InvalidRedValue => "invalid red value",
        }
    }
}

impl fmt::Display for ColorError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            ColorError::HexStringNoHashSign => write!(f, "Color error: {}", self.msg()),
            ColorError::HexStringTooLong => write!(f, "Color error: {}", self.msg()),
            ColorError::HexStringTooShort => write!(f, "Color error: {}", self.msg()),
            ColorError::InvalidBlueValue => write!(f, "Color error: {}", self.msg()),
            ColorError::InvalidGreenValue => write!(f, "Color error: {}", self.msg()),
            ColorError::InvalidRedValue => write!(f, "Color error: {}", self.msg()),
        }
    }
}

impl error::Error for ColorError {
    fn description(&self) -> &str {
        self.msg()
    }

    fn cause(&self) -> Option<&dyn error::Error> {
        None
    }
}

fn from_hex_string_blue(hex_str: &str) -> Result<u8, ColorError> {
    match u8::from_str_radix(&hex_str[5..7], 16) {
        Ok(val) => Ok(val),
        Err(_) => Err(ColorError::InvalidBlueValue),
    }
}

fn from_hex_string_green(hex_str: &str) -> Result<u8, ColorError> {
    match u8::from_str_radix(&hex_str[3..5], 16) {
        Ok(val) => Ok(val),
        Err(_) => Err(ColorError::InvalidGreenValue),
    }
}

fn from_hex_string_red(hex_str: &str) -> Result<u8, ColorError> {
    match u8::from_str_radix(&hex_str[1..3], 16) {
        Ok(val) => Ok(val),
        Err(_) => Err(ColorError::InvalidRedValue),
    }
}

#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn test_from_hex_string_without_hash_sign_returns_error() {
        let expected = Err(ColorError::HexStringNoHashSign);
        let actual = Color::from_hex_string("1234567");
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_from_hex_string_with_too_short_hex_string_returns_error() {
        let expected = Err(ColorError::HexStringTooShort);
        let actual = Color::from_hex_string("#12345");
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_from_hex_string_with_too_long_hex_string_returns_error() {
        let expected = Err(ColorError::HexStringTooLong);
        let actual = Color::from_hex_string("#1234567");
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_from_hex_string_with_invalid_blue_value_returns_error() {
        let expected = Err(ColorError::InvalidBlueValue);
        let actual = Color::from_hex_string("#0000fg");
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_from_hex_string_with_invalid_green_value_returns_error() {
        let expected = Err(ColorError::InvalidGreenValue);
        let actual = Color::from_hex_string("#00fg00");
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_from_hex_string_with_invalid_red_value_returns_error() {
        let expected = Err(ColorError::InvalidRedValue);
        let actual = Color::from_hex_string("#fg0000");
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_from_hex_string_with_valid_hex_string_returns_color() {
        for tuple in get_test_tuples() {
            let color = Color {
                red: tuple.1,
                green: tuple.2,
                blue: tuple.3,
            };
            let expected = Ok(color);
            let actual = Color::from_hex_string(tuple.0);
            assert_eq!(actual, expected);
        }
    }

    #[test]
    fn test_to_hex_string_with_valid_color_returns_hex_string() {
        for tuple in get_test_tuples() {
            let color = Color {
                red: tuple.1,
                green: tuple.2,
                blue: tuple.3,
            };
            let expected = tuple.0;
            let actual = color.to_hex_string();
            assert_eq!(actual, expected);
        }
    }

    quickcheck! {
        fn test_from_hex_string_inverses_to_hex_string(red: u8, green: u8, blue: u8) -> bool {
            let color = Color { red: red, green: green, blue: blue };
            Color::from_hex_string(&color.to_hex_string()) == Ok(color)
        }
    }

    fn get_test_tuples() -> Vec<(&'static str, u8, u8, u8)> {
        vec![
            ("#000000", 0, 0, 0),
            ("#ff0000", 255, 0, 0),
            ("#00ff00", 0, 255, 0),
            ("#0000ff", 0, 0, 255),
            ("#ffffff", 255, 255, 255),
        ]
    }
}