Skip to main content

verif_arithmetic/
checked.rs

1//! Total integer arithmetic: the operations that *cannot* overflow.
2//!
3//! Every function here returns an `Option`, and `None` is exactly the case the
4//! machine's `+`/`-`/`*` would have wrapped (or, in debug, panicked). [`crate::prove`]
5//! carries the proof that the flag is exact rather than a heuristic.
6
7/// `a + b`, or `None` on overflow. Total: no panic, no wrap-around.
8pub const fn checked_add(a: u32, b: u32) -> Option<u32> {
9    a.checked_add(b)
10}
11
12/// `a - b`, or `None` on underflow.
13pub const fn checked_sub(a: u32, b: u32) -> Option<u32> {
14    a.checked_sub(b)
15}
16
17/// `a * b`, or `None` on overflow.
18pub const fn checked_mul(a: u32, b: u32) -> Option<u32> {
19    a.checked_mul(b)
20}
21
22/// `a + b`, clamped to the type's maximum.
23pub const fn saturating_add(a: u32, b: u32) -> u32 {
24    a.saturating_add(b)
25}
26
27/// `a - b`, clamped at zero.
28pub const fn saturating_sub(a: u32, b: u32) -> u32 {
29    a.saturating_sub(b)
30}
31
32/// `a * b / d` without overflow in the intermediate product, using a 64-bit
33/// widening. Returns `None` when `d == 0` or the true quotient exceeds `u32`.
34///
35/// The naive `a * b / d` is wrong for exactly the PID-shaped inputs it is used
36/// on: at `a = b = 1000` the product `10^6` is fine, but at `a = b = 100_000`
37/// the product `10^10` wraps a `u32` before the division can bring it back. The
38/// widening is the whole point of the function, and `prove::mul_div_is_exact`
39/// is the obligation that says the widened result is the true quotient.
40pub const fn mul_div(a: u32, b: u32, d: u32) -> Option<u32> {
41    if d == 0 {
42        return None;
43    }
44    let wide = (a as u64) * (b as u64);
45    let q = wide / (d as u64);
46    if q > u32::MAX as u64 {
47        None
48    } else {
49        Some(q as u32)
50    }
51}