embedded_time/
time_int.rs

1use crate::fraction::Fraction;
2use core::{fmt, ops};
3
4/// The core inner-type trait for time-related types
5pub trait TimeInt:
6    Copy
7    + num::Integer
8    + num::Bounded
9    + num::traits::WrappingAdd
10    + num::traits::WrappingSub
11    + num::CheckedAdd
12    + num::CheckedSub
13    + num::CheckedMul
14    + num::CheckedDiv
15    + From<u32>
16    + ops::Mul<Fraction, Output = Self>
17    + ops::Div<Fraction, Output = Self>
18    + fmt::Display
19    + fmt::Debug
20{
21    /// Checked integer × [`Fraction`] = integer
22    ///
23    /// Returns truncated (rounded toward `0`) integer or [`None`] upon failure
24    fn checked_mul_fraction(&self, fraction: &Fraction) -> Option<Self> {
25        self.checked_mul(&(*fraction.numerator()).into())?
26            .checked_div(&(*fraction.denominator()).into())
27    }
28
29    /// Checked integer / [`Fraction`] = integer
30    ///
31    /// Returns truncated (rounded toward `0`) integer or [`None`] upon failure
32    fn checked_div_fraction(&self, fraction: &Fraction) -> Option<Self> {
33        self.checked_mul_fraction(&fraction.recip())
34    }
35}
36
37impl TimeInt for u32 {}
38impl TimeInt for u64 {}
39
40#[cfg(test)]
41mod tests {
42    use crate::{fraction::Fraction, time_int::TimeInt};
43
44    #[test]
45    fn checked_integer_mul_fraction() {
46        assert_eq!(
47            8_u32.checked_mul_fraction(&Fraction::new(1, 2)),
48            Some(4_u32)
49        );
50
51        // the result is not rounded, but truncated (8×(1/3)=2.66)
52        assert_eq!(
53            8_u32.checked_mul_fraction(&Fraction::new(1, 3)),
54            Some(2_u32)
55        );
56    }
57
58    #[test]
59    fn checked_integer_div_fraction() {
60        assert_eq!(
61            8_u32.checked_div_fraction(&Fraction::new(1, 2)),
62            Some(16_u32)
63        );
64
65        // the result is not rounded, but truncated (8/3=2.66)
66        assert_eq!(
67            8_u32.checked_div_fraction(&Fraction::new(3, 1)),
68            Some(2_u32)
69        );
70    }
71}