In Rust, how do `checked_add`, `wrapping_add`, `saturating_add` and `overflowing_add` differ when summing untrusted `u64` token amounts in a ledger?
answer
- four policies for one operator
- Option, wrap, clamp, pair
- the same in every build
- money needs an error path
basics
~10 schecked_add returns None on overflow, wrapping_add wraps modulo 2^64, saturating_add clamps at u64::MAX, and overflowing_add returns the wrapped value plus a bool. For untrusted ledger amounts, use checked_add and reject the batch.
solid answer
~40 sThe four methods give `+` an explicit overflow policy that does not change between debug and release builds. `checked_add` returns `Option<u64>`: `Some(sum)` or `None`, so a ledger can turn `None` into a rejected transaction, and `?` makes summing a batch one line. `wrapping_add` computes modulo 2^64 on purpose, which suits hashes and sequence numbers but would silently corrupt a balance. `saturating_add` stops at `u64::MAX` (or 0 for `saturating_sub`), fine for a metrics counter but wrong for money because it records a different amount than was sent. `overflowing_add` returns `(wrapped, did_overflow)` for code that needs both, such as multi-word arithmetic. The same families exist for `sub`, `mul`, `div`, `pow` and more, and `std::num::Wrapping<T>` and `Saturating<T>` make the policy part of the type.
code
rust · 22 linesuse std::num::Wrapping;
fn batch_total(amounts: &[u64]) -> Option<u64> {
let mut total: u64 = 0;
for &amount in amounts {
total = total.checked_add(amount)?;
}
Some(total)
}
fn main() {
let balance: u64 = u64::MAX - 5;
println!("{:?}", balance.checked_add(10)); // None
println!("{}", balance.wrapping_add(10)); // 4
println!("{}", balance.saturating_add(10)); // 18446744073709551615
println!("{:?}", balance.overflowing_add(10)); // (4, true)
println!("{:?}", 3u64.checked_sub(5)); // None
println!("{:?}", batch_total(&[40, 2])); // Some(42)
println!("{:?}", batch_total(&[u64::MAX, 1])); // None
let checksum = Wrapping(u64::MAX) + Wrapping(10);
println!("{}", checksum.0); // 9
}go deeper
Recall the four results: None, the wrapped value, the clamped maximum, and a value-and-bool pair, and that they behave the same in debug and release.
Match each policy to a domain: checked for untrusted input and money, wrapping for hashes, saturating for meters and budgets, overflowing for carries in multi-word math.
Show the failure each wrong choice causes in production: a wrapped or clamped balance stored silently, or an unwrap that turns attacker input into a panic.
Decide where the policy lives, per call or in newtypes like Wrapping, Saturating or a domain amount type, so reviewers cannot miss a plain operator.
## The problem with plain `+` On a fixed-width integer, `a + b` has two behaviours: a debug build panics on overflow, a default release build wraps in two's complement. Neither is a decision. For a ledger that sums `u64` token amounts arriving from untrusted transactions, the sum can genuinely exceed `u64::MAX` if an attacker submits huge values, and the code has to say what happens then. The integer types carry four method families that make the choice explicit and behave **identically in every build**. ## The four policies side by side For `balance = u64::MAX - 5` and `amount = 10`: | Call | Result | Meaning | |---|---|---| | `balance.checked_add(10)` | `None` | overflow detected, no value | | `balance.wrapping_add(10)` | `4` | arithmetic modulo 2^64 | | `balance.saturating_add(10)` | `18446744073709551615` | clamped at `u64::MAX` | | `balance.overflowing_add(10)` | `(4, true)` | wrapped value plus an overflow flag | Subtraction mirrors this at the bottom of the range: `3u64.checked_sub(5)` is `None` and `3u64.saturating_sub(5)` is `0`. ## Choosing one - **`checked_*`** returns `Option<T>`. It is the right default for **untrusted input and money**: overflow becomes a value the caller must handle, typically by rejecting the transaction. `checked_sub` doubles as an insufficient-funds check on an unsigned balance. - **`wrapping_*`** is for arithmetic that is **meant to be modular**: hash functions, checksums, ring-buffer sequence numbers, pseudo-random generators. Using it on a balance converts an attack into a silent wrong number. - **`saturating_*`** clamps at `MIN` or `MAX`. It suits **measurements and budgets** where "as much as possible" is a sensible answer: a retry counter, a rate-limiter token bucket, a progress gauge. On a ledger it is a quiet bug, because the stored balance no longer equals the sum of the transfers. - **`overflowing_*`** returns `(T, bool)`. It is the building block for **multi-word arithmetic** (carry propagation) and for code that wants the wrapped value and the fact of overflow at once. Note that the first element is the wrapped value, not the true sum. The families also cover `sub`, `mul`, `div`, `rem`, `neg`, `pow`, `shl`, `shr` and `abs` where they make sense. ## Summing a batch `checked_add` composes with `?` inside a function returning `Option`, so rejecting a whole batch on the first overflow takes one line in the loop: ```rust fn batch_total(amounts: &[u64]) -> Option<u64> { let mut total: u64 = 0; for &amount in amounts { total = total.checked_add(amount)?; } Some(total) } ``` `batch_total(&[40, 2])` is `Some(42)` and `batch_total(&[u64::MAX, 1])` is `None`. Converting `None` into a domain error with `ok_or` is the Option material's subject; the arithmetic decision is made here. ## Putting the policy in the type When every operation on a value should wrap, writing `wrapping_add` everywhere is noisy and easy to forget once. `std::num::Wrapping<T>` is a newtype whose `+`, `-`, `*` and compound assignments always wrap, and `std::num::Saturating<T>` does the same for clamping: ```rust use std::num::Wrapping; fn main() { let checksum = Wrapping(u64::MAX) + Wrapping(10); assert_eq!(checksum.0, 9); } ``` The standard library has no checked counterpart: a checked result is an `Option`, which does not chain through further operators the way `a + b + c` does, so a ledger typically wraps the amount in its own newtype whose methods return `Result`. ## Cost and the build profile The explicit methods are not slower in any way that matters for a ledger. `checked_add` typically compiles to the add plus a branch on the overflow result, the same check a debug build inserts for `+`; `wrapping_add` is the bare add that a default release build emits for `+`. The difference is that the explicit form behaves **the same in debug, release and tests**. A test suite that exercises an overflowing batch therefore sees the same `None` that production sees, instead of a debug-only panic that hides how the release binary would have wrapped. ## Common mistakes 1. Assuming release builds check overflow, and writing `+` on untrusted amounts. 2. Reaching for `saturating_add` because it "cannot overflow", and storing a balance that is silently wrong. 3. Treating `overflowing_add`'s first element as the correct sum. 4. Unwrapping `checked_add` immediately, which turns an attacker's input into a panic in a service.
- Why is `saturating_add` wrong for a balance but fine for a rate limiter's token bucket?A balance must equal the sum of its transfers; clamping at `u64::MAX` stores a number nobody sent, with no error raised. A token bucket's question is only "how much budget remains, up to a cap", so stopping at the cap is the correct answer rather than a hidden failure.
- When would you choose `overflowing_add` over `checked_add`?When the wrapped value is still useful. Adding two 128-bit numbers stored as pairs of `u64` needs the low word's wrapped sum and the carry flag to add into the high word; `overflowing_add` returns both. `checked_add` throws the value away on overflow.
- What does `Wrapping<u32>` give you that `wrapping_add` does not?It makes the policy part of the type: every `+`, `-`, `*` and `+=` on `Wrapping<u32>` wraps, so a later edit cannot slip a plain overflowing `+` into a hash routine. You read the inner value through the public `.0` field.
- saturating_add is the safe choice for account balances.
- wrapping_add still panics in debug builds, like the + operator.
- checked_add returns a Result carrying an overflow error.
- overflowing_add returns the true mathematical sum plus a flag.
- Plain + is fine on untrusted amounts because release builds check overflow.