complex: refactor ParseComplexError a little

This commit is contained in:
Josh Stone 2017-07-19 15:16:34 -07:00
parent bd22a89a32
commit ee6bbdb2f6
1 changed files with 25 additions and 24 deletions

View File

@ -811,27 +811,23 @@ impl<T> FromStr for Complex<T> where
} else if b.ends_with(imag) { } else if b.ends_with(imag) {
re = a; im = b; re = a; im = b;
} else { } else {
return Err(ParseComplexError { kind: ComplexErrorKind::ExprError }); return Err(ParseComplexError::new());
} }
// parse re // parse re
let re = try!(T::from_str(re) let re = try!(T::from_str(re).map_err(ParseComplexError::from_error));
.map_err(|e| ParseComplexError { kind: ComplexErrorKind::ParseError(e) }));
// pop imaginary unit off // pop imaginary unit off
let mut im = &im[..im.len()-1]; let mut im = &im[..im.len()-1];
// handle im == "i" or im == "-i" // handle im == "i" or im == "-i"
if im.is_empty() { if im.is_empty() || im == "+" {
im = "1"; im = "1";
} else if im == "-" { } else if im == "-" {
im = "-1"; im = "-1";
} else if im == "+" {
im = "1";
} }
// parse im // parse im
let im = try!(T::from_str(im) let im = try!(T::from_str(im).map_err(ParseComplexError::from_error));
.map_err(|e| ParseComplexError { kind: ComplexErrorKind::ParseError(e) }));
Ok(Complex::new(re, im)) Ok(Complex::new(re, im))
} }
@ -873,33 +869,38 @@ enum ComplexErrorKind<E>
ExprError ExprError
} }
impl<E> Error for ParseComplexError<E> where impl<E> ParseComplexError<E>
E: Error
{ {
fn description(&self) -> &str { fn new() -> Self {
self.kind.description() ParseComplexError {
kind: ComplexErrorKind::ExprError,
}
}
fn from_error(error: E) -> Self {
ParseComplexError {
kind: ComplexErrorKind::ParseError(error),
}
} }
} }
impl<E> fmt::Display for ParseComplexError<E> where impl<E: Error> Error for ParseComplexError<E>
E: Error
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.description().fmt(f)
}
}
impl<E> ComplexErrorKind<E> where
E: Error
{ {
fn description(&self) -> &str { fn description(&self) -> &str {
match *self { match self.kind {
ComplexErrorKind::ParseError(ref e) => e.description(), ComplexErrorKind::ParseError(ref e) => e.description(),
ComplexErrorKind::ExprError => "invalid or unsupported complex expression" ComplexErrorKind::ExprError => "invalid or unsupported complex expression"
} }
} }
} }
impl<E: Error> fmt::Display for ParseComplexError<E>
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.description().fmt(f)
}
}
#[cfg(test)] #[cfg(test)]
fn hash<T: hash::Hash>(x: &T) -> u64 { fn hash<T: hash::Hash>(x: &T) -> u64 {
use std::hash::{BuildHasher, Hasher}; use std::hash::{BuildHasher, Hasher};