diff --git a/Cargo.toml b/Cargo.toml index c07b322..b7abddc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,6 +8,7 @@ edition = "2018" [dependencies] env_logger = "0.8.3" +hex = "^0.4.3" image = "0.23.14" log = "0.4.14" pixels = "0.3.0" diff --git a/src/colour.rs b/src/colour.rs index 4d6d1a0..9b87a13 100644 --- a/src/colour.rs +++ b/src/colour.rs @@ -7,8 +7,16 @@ pub struct Colour { pub blue: u8, } -impl Colour { - pub fn from(colours: Vec) -> Colour { +impl From<&str> for Colour { + fn from(str: &str) -> Self { + let rgb = hex::decode(&str[str.len() - 6..]).unwrap(); + + Colour { red: rgb[0], green: rgb[1], blue: rgb[2] } + } +} + +impl From> for Colour { + fn from(colours: Vec) -> Self { const ZERO: u8 = 0; Colour { red: *colours.get(0).unwrap_or(&ZERO), @@ -16,8 +24,10 @@ impl Colour { blue: *colours.get(2).unwrap_or(&ZERO), } } +} - pub fn to_vec(&self) -> Vec { +impl Into> for Colour { + fn into(self) -> Vec { vec![self.red, self.green, self.blue] } } @@ -26,6 +36,15 @@ impl Colour { mod test { use crate::Colour; + #[test] + fn test_colour_from_hex() { + assert_eq!(Colour::from("#ff00ff" ), Colour { red: 255, green: 0, blue: 255 }); + assert_eq!(Colour::from("0xffffff"), Colour { red: 255, green: 255, blue: 255 }); + assert_eq!(Colour::from("ffffff" ), Colour { red: 255, green: 255, blue: 255 }); + assert_eq!(Colour::from("#010203" ), Colour { red: 1, green: 2, blue: 3 }); + assert_eq!(Colour::from("0xa0b0c0"), Colour { red: 160, green: 176, blue: 192 }); + } + #[test] fn test_colour_from_intermediate() { let output = Colour::from(vec![64, 128, 192]); @@ -35,7 +54,7 @@ mod test { #[test] fn test_colour_to_intermediate() { - let output = Colour { red: 64, green: 128, blue: 192 }.to_vec(); + let output: Vec = Colour { red: 64, green: 128, blue: 192 }.into(); let expected = vec![64, 128, 192]; assert_eq!(output, expected); }