167. Saturating<T> — Stop Calling .saturating_add() Everywhere
When every step in a loop or formula could overflow, calling .saturating_add() and .saturating_sub() on each one turns one line of math into a paragraph.
std::num::Saturating<T> is a tuple newtype wrapper that overloads the normal operators (+, -, *, +=, …) to use saturating semantics — operations clamp to the type’s MIN or MAX instead of wrapping or panicking. You write a + b, not a.saturating_add(b).
| |
The unwrapped equivalent works, but every operator turns into a method call:
| |
The wrapper really pays off inside a formula or an iterator chain, where you’d otherwise be wrapping each binary op:
| |
There’s a matching std::num::Wrapping<T> when you actually want cyclical math (hashes, CRCs, monotonic counters that should roll over), and both wrappers implement From, Default, Sum, and Product, so you can drop them into structs and iterator chains without ceremony.
Reach for Saturating<T> whenever a value has a logical floor or ceiling — health bars, progress percentages, retry budgets — and overflow should pin to the edge instead of panicking in debug or silently wrapping in release.