execution_time/traits/
format_value.rs

1use crate::{SingularPlural, Unit};
2
3/// Trait for formatting floating-point values with their units
4pub trait FormatFloatValue {
5    /// Formats a value with its unit (singular or plural).
6    ///
7    /// ### Arguments
8    ///
9    /// * `decimal` - The number of decimal places to display.
10    /// * `unit` - Unit types with their singular/plural pairs.
11    ///
12    /// ### Returns
13    ///
14    /// A formatted string.
15    fn format_float_unit(&self, decimal: usize, unit: Unit) -> String;
16}
17
18impl FormatFloatValue for f64 {
19    fn format_float_unit(&self, decimal: usize, unit: Unit) -> String {
20        let unit = if *self >= 2.0 {
21            unit.plural()
22        } else {
23            unit.singular()
24        };
25        format!("{self:.decimal$} {unit}")
26    }
27}
28
29/// Trait for formatting integer values with their units
30pub trait FormatIntegerValue {
31    /// Formats a value with its unit (singular or plural).
32    ///
33    /// # Arguments
34    ///
35    /// * `unit` - Unit types with their singular/plural pairs.
36    ///
37    /// # Returns
38    ///
39    /// A formatted string.
40    fn format_unit(&self, unit: Unit) -> String;
41}
42
43impl<T> FormatIntegerValue for T
44where
45    T: std::fmt::Display + PartialOrd + From<u8>,
46{
47    fn format_unit(&self, unit: Unit) -> String {
48        // T::from(2u8) or 2.into()
49        let unit = if *self >= T::from(2u8) {
50            unit.plural()
51        } else {
52            unit.singular()
53        };
54        format!("{self} {unit}")
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61
62    #[test]
63    fn test_integer_formatting() {
64        assert_eq!(0u64.format_unit(Unit::Day), "0 day");
65        assert_eq!(1u64.format_unit(Unit::Day), "1 day");
66        assert_eq!(2u64.format_unit(Unit::Day), "2 days");
67    }
68
69    #[test]
70    fn test_floating_point_formatting() {
71        assert_eq!(2.0f64.format_float_unit(0, Unit::Hour), "2 hours");
72        assert_eq!(0.567f64.format_float_unit(2, Unit::Second), "0.57 second");
73        assert_eq!(1.567f64.format_float_unit(2, Unit::Second), "1.57 second");
74        assert_eq!(2.567f64.format_float_unit(2, Unit::Second), "2.57 seconds");
75    }
76}