diff --git a/exercises/conversions/from_str.rs b/exercises/conversions/from_str.rs index 34472c32..52b9d235 100644 --- a/exercises/conversions/from_str.rs +++ b/exercises/conversions/from_str.rs @@ -31,8 +31,6 @@ enum ParsePersonError { ParseInt(ParseIntError), } -// I AM NOT DONE - // Steps: // 1. If the length of the provided string is 0, an error should be returned // 2. Split the given string on the commas present in it @@ -52,6 +50,26 @@ enum ParsePersonError { impl FromStr for Person { type Err = ParsePersonError; fn from_str(s: &str) -> Result { + if s.len() > 0 { + let splits : Vec<&str> = s.split(',').collect(); + if splits.len() == 2 { + let n = splits[0]; + let a = splits[1]; + if n.len() > 0 { + match a.parse::() { + Ok(age) => Ok(Person { name : n.to_string(), age}), + Err(err) => Err(ParsePersonError::ParseInt(err)) + } + } else { + Err(ParsePersonError::NoName) + } + + } else { + Err(ParsePersonError::BadLen) + } + } else { + Err(ParsePersonError::Empty) + } } } diff --git a/exercises/conversions/try_from_into.rs b/exercises/conversions/try_from_into.rs index 32d6ef39..14ca14cd 100644 --- a/exercises/conversions/try_from_into.rs +++ b/exercises/conversions/try_from_into.rs @@ -27,8 +27,6 @@ enum IntoColorError { IntConversion, } -// I AM NOT DONE - // Your task is to complete this implementation and return an Ok result of inner // type Color. You need to create an implementation for a tuple of three // integers, an array of three integers, and a slice of integers. @@ -37,10 +35,19 @@ enum IntoColorError { // time, but the slice implementation needs to check the slice length! Also note // that correct RGB color values must be integers in the 0..=255 range. +// TRICK: +// First filter and then convert. + // Tuple implementation impl TryFrom<(i16, i16, i16)> for Color { type Error = IntoColorError; fn try_from(tuple: (i16, i16, i16)) -> Result { + let vv = vec!(tuple.0, tuple.1, tuple.2); + if vv.iter().all(|&x| x >= 0 && x <= 255) { + Ok(Self { red: vv[0] as u8, green: vv[1] as u8, blue: vv[2] as u8 }) + } else { + Err(IntoColorError::IntConversion) + } } } @@ -48,6 +55,11 @@ impl TryFrom<(i16, i16, i16)> for Color { impl TryFrom<[i16; 3]> for Color { type Error = IntoColorError; fn try_from(arr: [i16; 3]) -> Result { + if arr.iter().all(|&x| x >= 0 && x <= 255) { + Ok(Self { red: arr[0] as u8, green: arr[1] as u8, blue: arr[2] as u8 }) + } else { + Err(IntoColorError::IntConversion) + } } } @@ -55,6 +67,15 @@ impl TryFrom<[i16; 3]> for Color { impl TryFrom<&[i16]> for Color { type Error = IntoColorError; fn try_from(slice: &[i16]) -> Result { + if slice.len() == 3 { + if slice.iter().all(|&x| x >= 0 && x <= 255) { + Ok(Self { red: slice[0] as u8, green: slice[1] as u8, blue: slice[2] as u8 }) + } else { + Err(IntoColorError::IntConversion) + } + } else { + Err(IntoColorError::BadLen) + } } }