named_colour/
to_hex.rs

1use rgb::Rgb;
2
3/// Implement the `ToHex` trait
4///
5/// Provides interfaces for functions to display hex versions of RGB colours
6///
7/// An implementation is provided for `Rgb<u8>`
8///
9pub trait ToHex {
10    /// Return the colour code as an uppercase hex string with a # prefix
11    fn as_hex(&self) -> String;
12    /// Return the colour code as a lowercase hex string with no prefix
13    fn to_hex_string(&self) -> String;
14}
15
16impl ToHex for Rgb<u8> {
17    fn as_hex(&self) -> String {
18        format!("#{:02X}{:02X}{:02X}", self.r, self.g, self.b)
19    }
20
21    fn to_hex_string(&self) -> String {
22        format!("{:02x}{:02x}{:02x}", self.r, self.g, self.b)
23    }
24}
25
26#[cfg(test)]
27mod tests {
28    use super::ToHex;
29    use rgb::Rgb;
30
31    #[test]
32    fn print_valid_hex_string_for_rgb_u8() {
33        assert_eq!("#CCCCCC", &Rgb::new(204, 204, 204).as_hex());
34        let colour = Rgb::new(12, 24, 48);
35        assert_eq!("#0C1830", colour.as_hex());
36        let colour = Rgb::new(12, 4, 8);
37        assert_eq!("#0C0408", colour.as_hex());
38    }
39
40    #[test]
41    fn test_to_hex_string_for_rgb_u8() {
42        let colour = Rgb::new(12, 24, 48);
43        assert_eq!("0c1830", colour.to_hex_string());
44        let colour = Rgb::new(12, 4, 8);
45        assert_eq!("0c0408", colour.to_hex_string());
46    }
47}