From f138f3da9ebd70ce743e6490270e3dce8198275c Mon Sep 17 00:00:00 2001 From: Sigurd Kolltveit Date: Fri, 26 Feb 2016 16:51:05 +0100 Subject: [PATCH] Add formatting options for Complex --- complex/src/lib.rs | 49 +++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 46 insertions(+), 3 deletions(-) diff --git a/complex/src/lib.rs b/complex/src/lib.rs index 62f74cc..f942b82 100644 --- a/complex/src/lib.rs +++ b/complex/src/lib.rs @@ -616,15 +616,49 @@ impl One for Complex { } } +macro_rules! write_complex { + ($f:ident, $re_fmt:expr, $im_fmt:expr, $re:expr, $im:expr, $( $arg:expr ),*) => { + if $im < Zero::zero() { + write!($f, concat!($re_fmt, "-", $im_fmt), $re, T::zero() - $im.clone(), $( $arg, )*) + } else { + write!($f, concat!($re_fmt, "+", $im_fmt), $re, $im, $( $arg, )*) + } + } +} + /* string conversions */ impl fmt::Display for Complex where T: fmt::Display + Num + PartialOrd + Clone { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if self.im < Zero::zero() { - write!(f, "{}-{}i", self.re, T::zero() - self.im.clone()) + if let Some(precision) = f.precision() { + write_complex!(f, "{0:.2$}", "{1:.2$}i", self.re, self.im, precision) } else { - write!(f, "{}+{}i", self.re, self.im) + write_complex!(f, "{0}", "{1}i", self.re, self.im,) + } + } +} + +impl fmt::LowerExp for Complex where + T: fmt::LowerExp + Num + PartialOrd + Clone +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if let Some(precision) = f.precision() { + write_complex!(f, "{0:.2$e}", "{1:.2$e}i", self.re, self.im, precision) + } else { + write_complex!(f, "{0:e}", "{1:e}i", self.re, self.im,) + } + } +} + +impl fmt::UpperExp for Complex where + T: fmt::UpperExp + Num + PartialOrd + Clone +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if let Some(precision) = f.precision() { + write_complex!(f, "{0:.2$E}", "{1:.2$E}i", self.re, self.im, precision) + } else { + write_complex!(f, "{0:E}", "{1:E}i", self.re, self.im,) } } } @@ -1210,6 +1244,15 @@ mod test { test(_05_05i, "0.5+0.5i".to_string()); } + #[test] + fn test_string_formatting() { + let a: Complex64 = Complex::new(1.234567, 123.4567); + assert_eq!(format!("{}", a), "1.234567+123.4567i"); + assert_eq!(format!("{:.2}", a), "1.23+123.46i"); + assert_eq!(format!("{:.2E}", a), "1.23E0+1.23E2i"); + assert_eq!(format!("{:e}", a), "1.234567e0+1.234567e2i"); + } + #[test] fn test_hash() { let a = Complex::new(0i32, 0i32);