colour from hex
This commit is contained in:
parent
4a05021bdd
commit
7199ca30f9
|
@ -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"
|
||||
|
|
|
@ -6,7 +6,7 @@ pub struct Colour {
|
|||
}
|
||||
|
||||
impl Colour {
|
||||
pub(crate) fn from(string: &str) -> Result<Colour, crate::Error> {
|
||||
pub fn from(string: &str) -> Result<Colour, crate::Error> {
|
||||
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<Colour, crate::Error> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue