error handing for Colour

This commit is contained in:
Max Bradbury 2020-07-06 13:06:10 +01:00
parent 5d40222120
commit e1398ba803
2 changed files with 12 additions and 5 deletions

View File

@ -5,16 +5,23 @@ pub struct Colour {
pub blue: u8, pub blue: u8,
} }
impl From<String> for Colour { #[derive(Debug)]
pub struct InvalidRgb;
impl Colour {
#[inline] #[inline]
fn from(string: String) -> Colour { pub(crate) fn from(string: String) -> Result<Colour, InvalidRgb> {
let values: Vec<&str> = string.split(',').collect(); let values: Vec<&str> = string.split(',').collect();
if values.len() != 3 {
return Err(InvalidRgb);
}
let red: u8 = values[0].parse().unwrap_or(0); let red: u8 = values[0].parse().unwrap_or(0);
let green: u8 = values[1].parse().unwrap_or(0); let green: u8 = values[1].parse().unwrap_or(0);
let blue: u8 = values[2].parse().unwrap_or(0); let blue: u8 = values[2].parse().unwrap_or(0);
Colour { red, green, blue } Ok(Colour { red, green, blue })
} }
} }
@ -32,7 +39,7 @@ mod test {
#[test] #[test]
fn test_colour_from_string() { fn test_colour_from_string() {
assert_eq!( assert_eq!(
Colour::from("0,255,0".to_string()), Colour::from("0,255,0".to_string()).unwrap(),
Colour { red: 0, green: 255, blue: 0 } Colour { red: 0, green: 255, blue: 0 }
); );
} }

View File

@ -23,7 +23,7 @@ impl From<String> for Palette {
let colours = lines[colour_start_index..] let colours = lines[colour_start_index..]
.iter() .iter()
.map(|&line| Colour::from(line.to_string())) .map(|&line| Colour::from(line.to_string()).unwrap())
.collect(); .collect();
Palette { id, name, colours } Palette { id, name, colours }