create colour from borrowed str; handle missing end value; tests

This commit is contained in:
Max Bradbury 2020-07-06 13:37:31 +01:00
parent e1398ba803
commit c42d7262da
2 changed files with 19 additions and 4 deletions

View File

@ -10,8 +10,8 @@ pub struct InvalidRgb;
impl Colour { impl Colour {
#[inline] #[inline]
pub(crate) fn from(string: String) -> Result<Colour, InvalidRgb> { pub(crate) fn from(string: &str) -> Result<Colour, InvalidRgb> {
let values: Vec<&str> = string.split(',').collect(); let values: Vec<&str> = string.trim_matches(',').split(',').collect();
if values.len() != 3 { if values.len() != 3 {
return Err(InvalidRgb); return Err(InvalidRgb);
@ -39,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()).unwrap(), Colour::from("0,255,0").unwrap(),
Colour { red: 0, green: 255, blue: 0 } Colour { red: 0, green: 255, blue: 0 }
); );
} }
@ -48,4 +48,19 @@ mod test {
fn test_colour_to_string() { fn test_colour_to_string() {
assert_eq!(Colour { red: 22, green: 33, blue: 44, }.to_string(), "22,33,44".to_string()); assert_eq!(Colour { red: 22, green: 33, blue: 44, }.to_string(), "22,33,44".to_string());
} }
#[test]
fn test_colour_missing_value() {
assert!(Colour::from("0,0").is_err());
}
#[test]
fn test_colour_ambiguous_value() {
assert!(Colour::from("0,0,").is_err());
}
#[test]
fn test_colour_extraneous_value() {
assert!(Colour::from("0,0,0,0").is_err());
}
} }

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()).unwrap()) .map(|&line| Colour::from(line).unwrap())
.collect(); .collect();
Palette { id, name, colours } Palette { id, name, colours }