Files
bitsy-parser/src/colour.rs

65 lines
1.4 KiB
Rust
Raw Normal View History

2020-05-31 16:12:23 +01:00
#[derive(Clone, Debug, Eq, PartialEq)]
2020-04-12 12:35:39 +01:00
pub struct Colour {
pub red: u8,
pub green: u8,
pub blue: u8,
2020-04-12 12:35:39 +01:00
}
2020-04-12 12:22:20 +01:00
2020-07-06 13:06:10 +01:00
#[derive(Debug)]
pub struct InvalidRgb;
impl Colour {
pub(crate) fn from(string: &str) -> Result<Colour, InvalidRgb> {
let values: Vec<&str> = string.trim_matches(',').split(',').collect();
2020-04-12 12:22:20 +01:00
2020-07-06 13:06:10 +01:00
if values.len() != 3 {
return Err(InvalidRgb);
}
2020-04-18 15:58:30 +00:00
let red: u8 = values[0].parse().unwrap_or(0);
2020-04-12 12:35:39 +01:00
let green: u8 = values[1].parse().unwrap_or(0);
2020-04-18 15:58:30 +00:00
let blue: u8 = values[2].parse().unwrap_or(0);
2020-04-12 12:22:20 +01:00
2020-07-06 13:06:10 +01:00
Ok(Colour { red, green, blue })
2020-04-12 12:22:20 +01:00
}
2020-04-12 12:35:39 +01:00
}
2020-04-12 12:22:20 +01:00
2020-04-12 12:35:39 +01:00
impl ToString for Colour {
fn to_string(&self) -> String {
format!("{},{},{}", self.red, self.green, self.blue)
2020-04-12 12:22:20 +01:00
}
}
2020-04-19 08:13:55 +01:00
#[cfg(test)]
mod test {
use crate::colour::Colour;
#[test]
2020-07-26 12:37:41 +01:00
fn colour_from_string() {
2020-04-19 08:13:55 +01:00
assert_eq!(
Colour::from("0,255,0").unwrap(),
2020-04-19 08:13:55 +01:00
Colour { red: 0, green: 255, blue: 0 }
);
}
2020-04-12 12:22:20 +01:00
2020-04-19 08:13:55 +01:00
#[test]
2020-07-26 12:37:41 +01:00
fn colour_to_string() {
2020-04-19 08:13:55 +01:00
assert_eq!(Colour { red: 22, green: 33, blue: 44, }.to_string(), "22,33,44".to_string());
}
#[test]
2020-07-26 12:37:41 +01:00
fn colour_missing_value() {
assert!(Colour::from("0,0").is_err());
}
#[test]
2020-07-26 12:37:41 +01:00
fn colour_ambiguous_value() {
assert!(Colour::from("0,0,").is_err());
}
#[test]
2020-07-26 12:37:41 +01:00
fn colour_extraneous_value() {
assert!(Colour::from("0,0,0,0").is_err());
}
2020-04-12 12:22:20 +01:00
}