colour from hex; use From and Into traits

This commit is contained in:
Max Bradbury 2021-05-15 23:08:31 +01:00
parent ea136148f9
commit f1a0c5ce61
2 changed files with 24 additions and 4 deletions

View File

@ -8,6 +8,7 @@ edition = "2018"
[dependencies] [dependencies]
env_logger = "0.8.3" env_logger = "0.8.3"
hex = "^0.4.3"
image = "0.23.14" image = "0.23.14"
log = "0.4.14" log = "0.4.14"
pixels = "0.3.0" pixels = "0.3.0"

View File

@ -7,8 +7,16 @@ pub struct Colour {
pub blue: u8, pub blue: u8,
} }
impl Colour { impl From<&str> for Colour {
pub fn from(colours: Vec<u8>) -> 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<Vec<u8>> for Colour {
fn from(colours: Vec<u8>) -> Self {
const ZERO: u8 = 0; const ZERO: u8 = 0;
Colour { Colour {
red: *colours.get(0).unwrap_or(&ZERO), red: *colours.get(0).unwrap_or(&ZERO),
@ -16,8 +24,10 @@ impl Colour {
blue: *colours.get(2).unwrap_or(&ZERO), blue: *colours.get(2).unwrap_or(&ZERO),
} }
} }
}
pub fn to_vec(&self) -> Vec<u8> { impl Into<Vec<u8>> for Colour {
fn into(self) -> Vec<u8> {
vec![self.red, self.green, self.blue] vec![self.red, self.green, self.blue]
} }
} }
@ -26,6 +36,15 @@ impl Colour {
mod test { mod test {
use crate::Colour; 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] #[test]
fn test_colour_from_intermediate() { fn test_colour_from_intermediate() {
let output = Colour::from(vec![64, 128, 192]); let output = Colour::from(vec![64, 128, 192]);
@ -35,7 +54,7 @@ mod test {
#[test] #[test]
fn test_colour_to_intermediate() { fn test_colour_to_intermediate() {
let output = Colour { red: 64, green: 128, blue: 192 }.to_vec(); let output: Vec<u8> = Colour { red: 64, green: 128, blue: 192 }.into();
let expected = vec![64, 128, 192]; let expected = vec![64, 128, 192];
assert_eq!(output, expected); assert_eq!(output, expected);
} }