From ee6bbdb2f64199df55dd3bf3aa9fdf965000ccaa Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Wed, 19 Jul 2017 15:16:34 -0700 Subject: [PATCH] complex: refactor ParseComplexError a little --- complex/src/lib.rs | 49 +++++++++++++++++++++++----------------------- 1 file changed, 25 insertions(+), 24 deletions(-) diff --git a/complex/src/lib.rs b/complex/src/lib.rs index bb30c8c..692311d 100644 --- a/complex/src/lib.rs +++ b/complex/src/lib.rs @@ -811,27 +811,23 @@ impl FromStr for Complex where } else if b.ends_with(imag) { re = a; im = b; } else { - return Err(ParseComplexError { kind: ComplexErrorKind::ExprError }); + return Err(ParseComplexError::new()); } // parse re - let re = try!(T::from_str(re) - .map_err(|e| ParseComplexError { kind: ComplexErrorKind::ParseError(e) })); + let re = try!(T::from_str(re).map_err(ParseComplexError::from_error)); // pop imaginary unit off let mut im = &im[..im.len()-1]; // handle im == "i" or im == "-i" - if im.is_empty() { + if im.is_empty() || im == "+" { im = "1"; } else if im == "-" { im = "-1"; - } else if im == "+" { - im = "1"; } // parse im - let im = try!(T::from_str(im) - .map_err(|e| ParseComplexError { kind: ComplexErrorKind::ParseError(e) })); + let im = try!(T::from_str(im).map_err(ParseComplexError::from_error)); Ok(Complex::new(re, im)) } @@ -873,33 +869,38 @@ enum ComplexErrorKind ExprError } -impl Error for ParseComplexError where - E: Error +impl ParseComplexError { - fn description(&self) -> &str { - self.kind.description() - } + fn new() -> Self { + ParseComplexError { + kind: ComplexErrorKind::ExprError, + } + } + + fn from_error(error: E) -> Self { + ParseComplexError { + kind: ComplexErrorKind::ParseError(error), + } + } } -impl fmt::Display for ParseComplexError where - E: Error -{ - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.description().fmt(f) - } -} - -impl ComplexErrorKind where - E: Error +impl Error for ParseComplexError { fn description(&self) -> &str { - match *self { + match self.kind { ComplexErrorKind::ParseError(ref e) => e.description(), ComplexErrorKind::ExprError => "invalid or unsupported complex expression" } } } +impl fmt::Display for ParseComplexError +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.description().fmt(f) + } +} + #[cfg(test)] fn hash(x: &T) -> u64 { use std::hash::{BuildHasher, Hasher};