Arithmetic
Arithmetic helper modules for checked, saturating, overflowing, and wrapping operations.
Plain integer operators are checked by default. +, -, *, unary -, and
compound assignment trap on overflow or underflow; division and remainder trap
on zero divisors and signed minimum divided by -1.
Use std.arith when overflow behavior is part of the algorithm and should be
visible at the call site.
import std.arith;
fn main() {
let checked = arith.checked.add(40 as i8, 2 as i8);
let missing = arith.checked.add(@max(i8), 1 as i8);
let saturated = arith.saturating.add(@max(u8), 1 as u8);
let wrapped = arith.wrapping.add(@max(u8), 1 as u8);
let overflow = arith.overflowing.add(@max(u8), 1 as u8);
assert checked != null;
assert missing == null;
assert saturated == @max(u8);
assert wrapped == 0 as u8;
assert overflow[0] == 0 as u8;
assert overflow[1];
}
| Module | Helpers | Behavior |
|---|---|---|
std.arith.checked | add, sub, mul | Return T?; null means the operation overflowed or underflowed. |
std.arith.overflowing | add, sub, mul | Return (T, bool); the value is wrapped and the flag reports overflow. |
std.arith.saturating | add, sub, shl | Clamp to the numeric minimum or maximum. |
std.arith.wrapping | add, sub, mul | Return the two's-complement wrapped result. |
The facade module re-exports the policy modules:
import std.arith;
fn main() {
assert arith.saturating.sub(0_u8, 1_u8) == 0_u8;
assert arith.wrapping.add(@max(u8), 1_u8) == 0_u8;
}
Use plain operators for ordinary program logic where overflow is a bug and a trap is preferable to silent wraparound.
Use checked before allocation-size math or input-derived bounds where the
caller needs to turn overflow into a domain error.
Use overflowing when the algorithm needs both the wrapped value and the carry
or overflow bit, such as hash tables, encoders, or low-level codecs.
Use saturating for counters, clamped sizes, and arithmetic where the nearest
numeric bound is the intended result.
Use wrapping for algorithms that intentionally operate modulo the integer
width, such as hash functions.
These helpers are for integer scalar types. Floating-point arithmetic follows
the backend IEEE-754 operation for the target; it is not routed through
std.arith.