diff options
| author | Laurenz <laurmaedje@gmail.com> | 2021-01-15 15:43:59 +0100 |
|---|---|---|
| committer | Laurenz <laurmaedje@gmail.com> | 2021-01-15 15:43:59 +0100 |
| commit | 0f0416054f263b80ccec1a463ce4ab20913bdf71 (patch) | |
| tree | 09cc642c361327c386e88e89f81f512248d59514 /src/geom | |
| parent | 469d78d610085044845f0fba462f1d8170b62cd4 (diff) | |
Move value tests + smarter number formatting 🔢
Diffstat (limited to 'src/geom')
| -rw-r--r-- | src/geom/angle.rs | 11 | ||||
| -rw-r--r-- | src/geom/length.rs | 24 | ||||
| -rw-r--r-- | src/geom/relative.rs | 2 |
3 files changed, 25 insertions, 12 deletions
diff --git a/src/geom/angle.rs b/src/geom/angle.rs index 47541cb8..07471a02 100644 --- a/src/geom/angle.rs +++ b/src/geom/angle.rs @@ -56,7 +56,16 @@ impl Angle { impl Display for Angle { fn fmt(&self, f: &mut Formatter) -> fmt::Result { - write!(f, "{}{}", self.to_deg(), AngularUnit::Deg) + // Format with the unit that yields the shortest output, preferring + // degrees when tied. + let mut buf = ryu::Buffer::new(); + let unit = [AngularUnit::Deg, AngularUnit::Rad] + .iter() + .copied() + .min_by_key(|&unit| buf.format(self.to_unit(unit)).len()) + .unwrap(); + + write!(f, "{}{}", buf.format(self.to_unit(unit)), unit) } } diff --git a/src/geom/length.rs b/src/geom/length.rs index bfb1d668..00803e13 100644 --- a/src/geom/length.rs +++ b/src/geom/length.rs @@ -99,13 +99,16 @@ impl Length { impl Display for Length { fn fmt(&self, f: &mut Formatter) -> fmt::Result { - // Format small lengths as points and large ones as centimeters. - let (val, unit) = if self.to_pt().abs() < 25.0 { - (self.to_pt(), LengthUnit::Pt) - } else { - (self.to_cm(), LengthUnit::Cm) - }; - write!(f, "{}{}", (val * 100.0).round() / 100.0, unit) + // Format with the unit that yields the shortest output, preferring + // larger units when tied. + let mut buf = ryu::Buffer::new(); + let unit = [LengthUnit::Cm, LengthUnit::Mm, LengthUnit::Pt] + .iter() + .copied() + .min_by_key(|&unit| buf.format(self.to_unit(unit)).len()) + .unwrap(); + + write!(f, "{}{}", buf.format(self.to_unit(unit)), unit) } } @@ -229,8 +232,9 @@ mod tests { #[test] fn test_length_formatting() { - assert_eq!(Length::pt(-28.34).to_string(), "-1cm".to_string()); - assert_eq!(Length::pt(23.0).to_string(), "23pt".to_string()); - assert_eq!(Length::cm(12.728).to_string(), "12.73cm".to_string()); + assert_eq!(Length::pt(23.0).to_string(), "23.0pt"); + assert_eq!(Length::pt(-28.3465).to_string(), "-1.0cm"); + assert_eq!(Length::cm(12.728).to_string(), "12.728cm"); + assert_eq!(Length::cm(4.5).to_string(), "4.5cm"); } } diff --git a/src/geom/relative.rs b/src/geom/relative.rs index d39ead3a..e91ea672 100644 --- a/src/geom/relative.rs +++ b/src/geom/relative.rs @@ -37,7 +37,7 @@ impl Relative { impl Display for Relative { fn fmt(&self, f: &mut Formatter) -> fmt::Result { - write!(f, "{}%", (self.0 * 10000.0).round() / 100.0) + write!(f, "{}%", ryu::Buffer::new().format(100.0 * self.0)) } } |
