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 {
#[inline]
pub(crate) fn from(string: String) -> Result<Colour, InvalidRgb> {
let values: Vec<&str> = string.split(',').collect();
pub(crate) fn from(string: &str) -> Result<Colour, InvalidRgb> {
let values: Vec<&str> = string.trim_matches(',').split(',').collect();
if values.len() != 3 {
return Err(InvalidRgb);
@ -39,7 +39,7 @@ mod test {
#[test]
fn test_colour_from_string() {
assert_eq!(
Colour::from("0,255,0".to_string()).unwrap(),
Colour::from("0,255,0").unwrap(),
Colour { red: 0, green: 255, blue: 0 }
);
}
@ -48,4 +48,19 @@ mod test {
fn test_colour_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..]
.iter()
.map(|&line| Colour::from(line.to_string()).unwrap())
.map(|&line| Colour::from(line).unwrap())
.collect();
Palette { id, name, colours }