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
use crate::fraction::Fraction;
use core::{fmt, ops};
#[doc(hidden)]
pub trait TimeInt:
Copy
+ num::Integer
+ num::Bounded
+ num::traits::WrappingAdd
+ num::traits::WrappingSub
+ num::CheckedAdd
+ num::CheckedSub
+ num::CheckedMul
+ num::CheckedDiv
+ From<u32>
+ ops::Mul<Fraction, Output = Self>
+ ops::Div<Fraction, Output = Self>
+ fmt::Display
+ fmt::Debug
{
fn checked_mul_fraction(&self, fraction: &Fraction) -> Option<Self> {
self.checked_mul(&(*fraction.numerator()).into())?
.checked_div(&(*fraction.denominator()).into())
}
fn checked_div_fraction(&self, fraction: &Fraction) -> Option<Self> {
self.checked_mul_fraction(&fraction.recip())
}
}
impl TimeInt for u32 {}
impl TimeInt for u64 {}
#[cfg(test)]
mod tests {
use crate::{fraction::Fraction, time_int::TimeInt};
#[test]
fn checked_integer_mul_fraction() {
assert_eq!(
8_u32.checked_mul_fraction(&Fraction::new(1, 2)),
Some(4_u32)
);
assert_eq!(
8_u32.checked_mul_fraction(&Fraction::new(1, 3)),
Some(2_u32)
);
}
#[test]
fn checked_integer_div_fraction() {
assert_eq!(
8_u32.checked_div_fraction(&Fraction::new(1, 2)),
Some(16_u32)
);
assert_eq!(
8_u32.checked_div_fraction(&Fraction::new(3, 1)),
Some(2_u32)
);
}
}