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
#![allow(clippy::assign_op_pattern)]
#![allow(clippy::ptr_offset_with_cast)]
#![allow(clippy::reversed_empty_ranges)]
use uint::construct_uint;
construct_uint! {
pub struct U128(2);
}
pub fn mul_div_u64(a: u64, b: u64, divisor: u64) -> Option<u64> {
let result = U128::from(a)
.checked_mul(b.into())?
.checked_div(divisor.into())?;
if result.0[1] != 0 {
None
} else {
Some(result.0[0])
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_good() {
assert_eq!(mul_div_u64(u64::MAX, 0, 1), Some(0));
assert_eq!(mul_div_u64(10, 10, 10), Some(10));
assert_eq!(mul_div_u64(1_000, 3, 2), Some(1_500));
assert_eq!(mul_div_u64(1_000, 2, 3), Some(666));
}
#[test]
fn test_div_zero() {
assert_eq!(mul_div_u64(1, 1, 0), None);
}
#[test]
fn test_overflow_u128() {
assert_eq!(mul_div_u64(u64::MAX, u64::MAX, 0), None);
assert_eq!(mul_div_u64(u64::MAX, u64::MAX, 1), None);
}
}