summaryrefslogtreecommitdiff
path: root/src/geom/length.rs
diff options
context:
space:
mode:
authorLaurenz <laurmaedje@gmail.com>2021-01-15 15:43:59 +0100
committerLaurenz <laurmaedje@gmail.com>2021-01-15 15:43:59 +0100
commit0f0416054f263b80ccec1a463ce4ab20913bdf71 (patch)
tree09cc642c361327c386e88e89f81f512248d59514 /src/geom/length.rs
parent469d78d610085044845f0fba462f1d8170b62cd4 (diff)
Move value tests + smarter number formatting 🔢
Diffstat (limited to 'src/geom/length.rs')
-rw-r--r--src/geom/length.rs24
1 files changed, 14 insertions, 10 deletions
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");
}
}