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.
Code
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
CSS clamp() GeneratorGenerate responsive clamp(MIN, PREFERRED, MAX) values with automatic calc() wrapping for expressions.Date Add/Subtract CalculatorAdd or subtract days, weeks, months, or years from a date, clamping month ends such as January 31 plus one month.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.URL Safety CheckerEvaluate a URL against common phishing red flags such as plain HTTP, embedded credentials, IP hosts, Punycode, and risky top-level domains.
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=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.