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
extern crate ring as crypto;

use crypto::rand::SystemRandom;
use crypto::rand::SecureRandom;
use crypto::digest;

#[derive(Debug)]
pub struct Color (u8, u8, u8);

impl Color {
    pub fn from(input: &str) -> Color {
        let mut color = Color(0, 0, 0);
        color.update(input);
        color
    }

    pub fn rand() -> Color {
        let buf: &mut [u8] = &mut [0, 0, 0];

        SystemRandom::new().fill(buf).unwrap();

        Color(buf[0], buf[1], buf[2])
    }

    pub fn update(&mut self, input: &str) -> &Color {
        let raw = digest::digest(&digest::SHA256, input.as_bytes());
        let raw = raw.as_ref();

        self.0 = raw[0];
        self.1 = raw[1];
        self.2 = raw[2];
        self
    }

    // FIXME: Implement fmt::Display
    // REF https://stackoverflow.com/a/27650405/2684355
    pub fn to_color_string(&self) -> String {
        format!("#{:02X}{:02X}{:02X}", self.0, self.1, self.2)
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_hashes() {
        let color = super::Color::from("foo~");
        assert_eq!((6, 203, 178), (color.0, color.1, color.2));
    }

    #[test]
    fn is_correct_length() {
        let color = super::Color::from("foo~");
        assert_eq!(7, color.to_color_string().len());
    }
}