Wrapping Arithmetic With Wrapping

Use Wrapping to make overflow deliberate, comparing wrapping_add, checked_add, and saturating_add near the integer limit.

RustData Integrity

Code

rustsnippet
26 lines
use std::num::Wrapping;

fn main() {
    let max = u8::MAX;
    let one = Wrapping(1u8);

    // 普通加法在 debug 构建会 panic,Wrapping 明确环绕
    let wrapped = Wrapping(max) + one;
    println!("wrapped: {}", wrapped.0);
    println!("matches wrapping_add: {}", max.wrapping_add(1) == wrapped.0);

    // 乘法同样环绕:200 * 2 对 256 取模
    let product = Wrapping(200u8) * Wrapping(2u8);
    println!("product: {}", product.0);

    // 三种策略对比:checked 返回 None,saturating 停在边界
    println!("checked: {:?}", max.checked_add(1));
    println!("saturating: {}", max.saturating_add(1));
    println!("overflowing: {:?}", max.overflowing_add(1));

    // 迭代器折叠时计数器自然回绕
    let sum = (0u8..=255)
        .map(Wrapping)
        .fold(Wrapping(0u8), |acc, value| acc + value);
    println!("sum mod 256: {}", sum.0);
}

What the code does

Wrapping Arithmetic With Wrapping keeps everything in the function main.

Applying it

The run emits 7 labeled sections — wrapped:, matches wrapping_add:, product:, checked:, saturating:, overflowing:, sum mod 256: — one per step.

Statements that matter

.fold(Wrapping(0u8), |acc, value| acc + value);

Interactive Tools for This Topic

FAQ

What does Wrapping Arithmetic With Wrapping print when run?
No setup needed: run the file and look for labeled lines like `wrapped:`, `matches wrapping_add:`, `product:` in the output.