Clamp Overflow With std::num::Saturating

Wrap counter and budget fields in std::num::Saturating<T> so +, -, *, and += operators clamp cleanly at type bounds without panicking on overflow.

RustResilience

Code

snippet
use std::num::Saturating;

#[derive(Debug, Default)]
struct BucketMetrics {
    hits: Saturating<u16>,
    budget: Saturating<u16>,
}

impl BucketMetrics {
    fn record(&mut self, count: u16, cost: u16) {
        self.hits += Saturating(count);
        self.budget -= Saturating(cost);
    }
}

fn main() {
    let mut metrics = BucketMetrics {
        hits: Saturating(65_500),
        budget: Saturating(50),
    };

    metrics.record(20, 30);
    println!("normal update: hits={} budget={}", metrics.hits.0, metrics.budget.0);

    // Standard += and -= saturate at u16::MAX and 0 instead of panicking
    metrics.record(100, 99);
    println!("clamped update: hits={} budget={}", metrics.hits.0, metrics.budget.0);

    let scaled = Saturating(100_i8) * Saturating(2);
    let floor = Saturating(-120_i8) - Saturating(25);
    println!("signed clamp: mul={} sub={}", scaled.0, floor.0);
}

Mechanics trace — Clamp Overflow With std::num::Saturating

Everything happens inside the functions record and main.

What to watch for

  • Designed dependency-free — requires zero remote registry access and zero lockfile additions.

Using it

Signature: fn record(&mut self, count: u16, cost: u16)

The run emits 3 labeled sections — normal update: hits=, clamped update: hits=, signed clamp: mul= — one per step.

main is the driver: it invokes record before returning.

Key statements

fn record(&mut self, count: u16, cost: u16) {
    self.hits += Saturating(count);
    self.budget -= Saturating(cost);
}

Interactive Tools for This Topic

FAQ

What does Clamp Overflow With std::num::Saturating print when run?
Run it as a complete program — the output lines carry labels such as `normal update: hits=`, `clamped update: hits=`, `signed clamp: mul=`.