Saturating Arithmetic Clamps At Bounds

saturating_add, sub, and mul clamp at MIN and MAX instead of panicking or wrapping, unlike checked (Option) and overflowing (carry) variants.

RustData Integrity

Code

rustsnippet
22 lines
fn main() {
    // saturating arithmetic 在类型边界处钳制(bounds):不 panic 不回绕
    let top: u8 = 250;
    let added = top.saturating_add(10);
    println!("250 + 10 = {added}");
    println!("wrapping gives: {}", top.wrapping_add(10));

    let floor: u8 = 3;
    let floored = floor.saturating_sub(5);
    println!("3 - 5 = {floored}");

    let big: i32 = i32::MAX;
    let doubled = big.saturating_mul(2);
    println!("max * 2 = {doubled}");

    let small: i32 = i32::MIN;
    let lowered = small.saturating_sub(1);
    println!("min - 1 = {lowered}");

    // 对照:checked_* 返回 Option,溢出即 None
    println!("checked_add(10) on 250u8: {:?}", top.checked_add(10));
}

How it works

Saturating Arithmetic Clamps At Bounds is built around the function main.

Applying it

The run emits 6 labeled sections — 250 + 10 =, wrapping gives:, 3 - 5 =, max * 2 =, min - 1 =, checked_add(10) on 250u8: — one per step.

Statements that matter

let floored = floor.saturating_sub(5);
let lowered = small.saturating_sub(1);
let doubled = big.saturating_mul(2);

Interactive Tools for This Topic

FAQ

What does Saturating Arithmetic Clamps At Bounds print when run?
Run it as a complete program — the output lines carry labels such as `250 + 10 =`, `wrapping gives:`, `3 - 5 =`.