From 7199ca30f9a7a7fdf2987a6e21066fb30467dd38 Mon Sep 17 00:00:00 2001 From: Max Bradbury Date: Sat, 7 Nov 2020 15:44:35 +0000 Subject: [PATCH] colour from hex --- Cargo.toml | 5 +++-- src/colour.rs | 23 ++++++++++++++++++++++- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 3ee0617..848d86f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,5 +12,6 @@ keywords = ["gamedev"] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -radix_fmt = "1.0.0" -loe = "0.2.0" +data-encoding = "^2.3.1" +radix_fmt = "^1.0.0" +loe = "^0.2.0" diff --git a/src/colour.rs b/src/colour.rs index 1a7a62f..e1ed5a5 100644 --- a/src/colour.rs +++ b/src/colour.rs @@ -6,7 +6,7 @@ pub struct Colour { } impl Colour { - pub(crate) fn from(string: &str) -> Result { + pub fn from(string: &str) -> Result { let values: Vec<&str> = string.trim_matches(',').split(',').collect(); if values.len() != 3 { @@ -19,6 +19,13 @@ impl Colour { Ok(Colour { red, green, blue }) } + + pub fn from_hex(hex: &str) -> Result { + let hex = hex.to_lowercase().trim_start_matches('#').to_string(); + let rgb = data_encoding::HEXLOWER.decode(hex.as_bytes()).unwrap(); + + Ok(Colour { red: rgb[0], green: rgb[1], blue: rgb[2], }) + } } impl ToString for Colour { @@ -58,4 +65,18 @@ mod test { fn colour_extraneous_value() { assert!(Colour::from("0,0,0,0").is_err()); } + + #[test] + fn colour_from_hex() { + let output = Colour::from_hex("#ffff00").unwrap(); + let expected = Colour { red: 255, green: 255, blue: 0 }; + assert_eq!(output, expected); + } + + #[test] + fn colour_from_hex_upper() { + let output = Colour::from_hex("#ABCDEF").unwrap(); + let expected = Colour { red: 171, green: 205, blue: 239 }; + assert_eq!(output, expected); + } }