Checked Arithmetic On Durations
Enforce duration budgets with checked_add and checked_sub, which return Option instead of wrapping past zero the way Duration cannot go negative.
Code
use std::time::Duration;
fn main() {
let cap = Duration::from_secs(60);
let measured = Duration::from_millis(59_500);
let jitter = Duration::from_millis(900);
// checked_add 在溢出时返回 None:不会绕回成更小的值
match measured.checked_add(jitter) {
Some(total) if total <= cap => println!("within cap: {total:?}"),
Some(total) => println!("exceeds cap: {total:?}"),
None => println!("overflow"),
}
// checked_sub 防止 Duration 下溢(Duration 不可能有负值)
let spent = Duration::from_secs(90);
println!("budget - spent: {:?}", cap.checked_sub(spent));
let small = Duration::from_millis(500);
println!("budget - small: {:?}", cap.checked_sub(small));
}How it works
Checked Arithmetic On Durations comes down to the function main.
A match spells out every case; omit one and the code does not compile.
Points of care
- There is nothing to fetch: every symbol in the file is a language built-in.
Using it
Signature: fn main()
The demo output is labeled (within cap:, exceeds cap:, overflow); each label names the call that printed it.
Key statements
match measured.checked_add(jitter) {
Some(total) if total <= cap => println!("within cap: {total:?}"),
Some(total) => println!("exceeds cap: {total:?}"),
None => println!("overflow"),
}
Interactive Tools for This Topic
Date Add/Subtract CalculatorAdd or subtract days, weeks, months, or years from a date, clamping month ends such as January 31 plus one month.Date Difference CalculatorCalculate the number of days, weeks, whole months, and years between two ISO dates, computed in UTC.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.
FAQ
- What does Checked Arithmetic On Durations print when run?
- Run it as a complete program — the output lines carry labels such as `within cap:`, `exceeds cap:`, `overflow`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.