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.

RustResilience

Code

rustsnippet
21 lines
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

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`.