Answer#
The Rust Book states the rule: when compiling in debug mode, Rust includes checks for integer overflow that cause the program to panic; in release mode, it does not include them, and overflow wraps around in two's complement. That is memory safe, but a wrapped size or amount is a logic bug that can turn into a security bug (a length that wrapped to a small number, a balance that became negative or huge).
The program uses black_box so the compiler cannot compute the sums at compile time and reject them.
use std::hint::black_box;
fn main() {
let a: u8 = black_box(250);
let b: u8 = black_box(10);
println!("checked: {:?}", a.checked_add(b));
println!("wrapping: {}", a.wrapping_add(b));
println!("saturating: {}", a.saturating_add(b));
println!("overflowing: {:?}", a.overflowing_add(b));
// The plain operator: the behaviour depends on the build profile.
let plain = a + b;
println!("plain a + b: {plain}");
}Built in release mode (cargo run --release):
checked: None
wrapping: 4
saturating: 255
overflowing: (4, true)
plain a + b: 4Built in debug mode (cargo run), the same program stops at the plain operator:
checked: None
wrapping: 4
saturating: 255
overflowing: (4, true)
thread 'main' panicked at src\bin\b29.rs:13:17:
attempt to add with overflow| Method | On overflow | Use for |
|---|---|---|
checked_add | None | Anything from outside: lengths, counts, amounts |
saturating_add | stays at the maximum or minimum | Counters and limits where clamping is right |
wrapping_add | wraps, on purpose | Hashes, checksums, ring buffers |
overflowing_add | result and a flag | When you need both |
How to do it#
- Use
checked_operations on every arithmetic step that involves untrusted numbers, and turnNoneinto an error. - Convert between integer types with
try_from, notas;assilently truncates. - Test with large values, not just typical ones.
- If a release build must also fail on overflow, set
overflow-checks = truein[profile.release]ofCargo.toml. It costs some speed; measure it for your program.
Common mistakes#
- Testing only in debug mode and assuming release behaves the same.
- Using
asto shrink au64into au32orusize. - Adding a user-supplied length to an offset before comparing with a limit; compare first (see the thread on length fields).
Related questions#
Does overflow checking apply to unsafe code?#
The arithmetic rules are the same. Where a wrong size feeds an unchecked operation, an overflow can turn into memory corruption, which is a reason to keep size computations checked.
Should I enable overflow-checks in release?#
For services handling money, sizes or counters from outside, many teams do. Measure the cost for your program; the explicit checked_ methods remain the clearest way to express intent.
Sources#
- The Rust Book, "Integer Overflow": https://doc.rust-lang.org/book/ch03-02-data-types.html#integer-overflow
- Standard library, integer methods (
checked_addand others): https://doc.rust-lang.org/std/primitive.u8.html - Cargo Book, profile setting
overflow-checks: https://doc.rust-lang.org/cargo/reference/profiles.html#overflow-checks