execution_time/traits/
format_value.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
use crate::{SingularPlural, Unit};

/// Trait for formatting floating-point values with their units
pub trait FormatFloatValue {
    /// Formats a value with its unit (singular or plural).
    ///
    /// # Arguments
    ///
    /// * `decimal` - The number of decimal places to display.
    /// * `unit` - Unit types with their singular/plural pairs.
    ///
    /// # Returns
    ///
    /// A formatted string.
    fn format_unit(&self, decimal: usize, unit: Unit) -> String;
}

impl FormatFloatValue for f64 {
    fn format_unit(&self, decimal: usize, unit: Unit) -> String {
        let unit = if *self >= 2.0 {
            unit.plural()
        } else {
            unit.singular()
        };
        format!("{self:.decimal$} {unit}")
    }
}

/// Trait for formatting integer values with their units
pub trait FormatIntegerValue {
    /// Formats a value with its unit (singular or plural).
    ///
    /// # Arguments
    ///
    /// * `unit` - Unit types with their singular/plural pairs.
    ///
    /// # Returns
    ///
    /// A formatted string.
    fn format_unit(&self, unit: Unit) -> String;
}

impl FormatIntegerValue for u64 {
    fn format_unit(&self, unit: Unit) -> String {
        let unit = if *self >= 2 {
            unit.plural()
        } else {
            unit.singular()
        };
        format!("{self} {unit}")
    }
}

impl FormatIntegerValue for u8 {
    fn format_unit(&self, unit: Unit) -> String {
        let unit = if *self >= 2 {
            unit.plural()
        } else {
            unit.singular()
        };
        format!("{self} {unit}")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_integer_formatting() {
        assert_eq!(0u64.format_unit(Unit::Day), "0 day");
        assert_eq!(1u64.format_unit(Unit::Foot), "1 foot");
        assert_eq!(2u64.format_unit(Unit::Foot), "2 feet");
        assert_eq!(8u8.format_unit(Unit::Ox), "8 oxen");
    }

    #[test]
    fn test_floating_point_formatting() {
        assert_eq!(1.5f64.format_unit(1, Unit::Second), "1.5 second");
        assert_eq!(2.0f64.format_unit(0, Unit::Hour), "2 hours");
        assert_eq!(1.0.format_unit(1, Unit::Meter), "1.0 meter");
        assert_eq!(2.5.format_unit(2, Unit::Meter), "2.50 meters");
        assert_eq!(7.123501.format_unit(3, Unit::Foot), "7.124 feet");
    }
}