Better debug implementations for numeric types

This commit is contained in:
Laurenz 2022-02-17 12:14:50 +01:00
parent ab95627d87
commit c7a9bac992
7 changed files with 10 additions and 31 deletions

View File

@ -531,7 +531,7 @@ mod tests {
test(Length::pt(5.5), "5.5pt");
test(Angle::deg(90.0), "90deg");
test(Relative::one() / 2.0, "50%");
test(Relative::new(0.3) + Length::cm(2.0), "30% + 2cm");
test(Relative::new(0.3) + Length::cm(2.0), "30% + 56.69pt");
test(Fractional::one() * 7.55, "7.55fr");
test(Color::Rgba(RgbaColor::new(1, 1, 1, 0xff)), "#010101");

View File

@ -58,15 +58,7 @@ impl Angle {
impl Debug for Angle {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
// Format with the unit that yields the shortest output, preferring
// degrees when tied.
let unit = [AngularUnit::Deg, AngularUnit::Rad]
.iter()
.copied()
.min_by_key(|&unit| self.to_unit(unit).to_string().len())
.unwrap();
write!(f, "{}{:?}", self.to_unit(unit), unit)
write!(f, "{}deg", round_2(self.to_deg()))
}
}

View File

@ -48,7 +48,7 @@ impl Fractional {
impl Debug for Fractional {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}fr", self.get())
write!(f, "{}fr", round_2(self.get()))
}
}

View File

@ -139,17 +139,7 @@ impl Length {
impl Debug for Length {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
use LengthUnit::*;
// Format with the unit that yields the shortest output, preferring
// larger / metric units when tied.
let unit = [Cm, Mm, In, Pt]
.iter()
.copied()
.min_by_key(|&unit| self.to_unit(unit).to_string().len())
.unwrap();
write!(f, "{}{:?}", self.to_unit(unit), unit)
write!(f, "{}pt", round_2(self.to_pt()))
}
}
@ -264,12 +254,4 @@ mod tests {
fn test_length_unit_conversion() {
assert!((Length::mm(150.0).to_cm() - 15.0) < 1e-4);
}
#[test]
fn test_length_formatting() {
assert_eq!(format!("{:?}", Length::pt(23.0)), "23pt");
assert_eq!(format!("{:?}", Length::pt(-28.3465)), "-1cm");
assert_eq!(format!("{:?}", Length::cm(12.728)), "12.728cm");
assert_eq!(format!("{:?}", Length::cm(4.5)), "45mm");
}
}

View File

@ -59,3 +59,8 @@ pub trait Get<Index> {
*self.get_mut(index) = component;
}
}
/// Round a float to two decimal places.
fn round_2(value: f64) -> f64 {
(value * 100.0).round() / 100.0
}

View File

@ -51,7 +51,7 @@ impl Relative {
impl Debug for Relative {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}%", 100.0 * self.get())
write!(f, "{}%", round_2(100.0 * self.get()))
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

After

Width:  |  Height:  |  Size: 29 KiB