From 5f724516dab85efd1ad9f1b3f71da7c25f765710 Mon Sep 17 00:00:00 2001 From: Stanislav Pankrashin Date: Thu, 23 Jun 2022 17:03:18 +1200 Subject: [PATCH] finished --- exercises/advanced_errors/advanced_errs2.rs | 26 ++++++++++++++++----- 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/exercises/advanced_errors/advanced_errs2.rs b/exercises/advanced_errors/advanced_errs2.rs index 54e669fd..3a2de83c 100644 --- a/exercises/advanced_errors/advanced_errs2.rs +++ b/exercises/advanced_errors/advanced_errs2.rs @@ -16,8 +16,6 @@ // 4. Complete the partial implementation of `Display` for // `ParseClimateError`. -// I AM NOT DONE - use std::error::Error; use std::fmt::{self, Display, Formatter}; use std::num::{ParseFloatError, ParseIntError}; @@ -38,7 +36,7 @@ enum ParseClimateError { // `ParseIntError` values. impl From for ParseClimateError { fn from(e: ParseIntError) -> Self { - Self::ParseInt(e) + ParseClimateError::ParseInt(e) } } @@ -46,12 +44,15 @@ impl From for ParseClimateError { // `ParseFloatError` values. impl From for ParseClimateError { fn from(e: ParseFloatError) -> Self { - // TODO: Complete this function + ParseClimateError::ParseFloat(e) } } // TODO: Implement a missing trait so that `main()` below will compile. It // is not necessary to implement any methods inside the missing trait. +impl Error for ParseClimateError { + +} // The `Display` trait allows for other code to obtain the error formatted // as a user-visible string. @@ -64,6 +65,9 @@ impl Display for ParseClimateError { match self { NoCity => write!(f, "no city name"), ParseFloat(e) => write!(f, "error parsing temperature: {}", e), + Empty => write!(f, "empty input"), + BadLen => write!(f, "incorrect number of fields"), + ParseInt(e) => write!(f, "error parsing year: {}", e), } } } @@ -88,13 +92,23 @@ impl FromStr for Climate { // TODO: Complete this function by making it handle the missing error // cases. fn from_str(s: &str) -> Result { + if s.len() == 0 { + return Err(ParseClimateError::Empty); + } let v: Vec<_> = s.split(',').collect(); let (city, year, temp) = match &v[..] { + [city, _, _] if city.len() == 0 => return Err(ParseClimateError::NoCity), [city, year, temp] => (city.to_string(), year, temp), _ => return Err(ParseClimateError::BadLen), }; - let year: u32 = year.parse()?; - let temp: f32 = temp.parse()?; + let year: u32 = match year.parse() { + Ok(year) => year, + Err(err) => return Err(ParseClimateError::ParseInt(err)), + }; + let temp: f32 = match temp.parse() { + Ok(temp) => temp, + Err(err) => return Err(ParseClimateError::ParseFloat(err)), + }; Ok(Climate { city, year, temp }) } }