Skip to main content

Deadline

Struct Deadline 

Source
pub struct Deadline { /* private fields */ }
Expand description

A time budget pinned to a monotonic timeline.

A Deadline is a start instant plus a budget; it expires at start + budget. It never reads the clock — pass now to the query methods. All arithmetic saturates, so a backwards-moving clock or an overflowing start + budget cannot panic.

A zero budget expires immediately at start. For the same reason, Deadline::default (start and budget both 0) is already expired — it is not an “infinite” deadline.

Implementations§

Source§

impl Deadline

Source

pub const fn new(start: u64, budget: u64) -> Self

Creates a deadline that expires budget units after start.

Source

pub const fn start(&self) -> u64

The start instant.

Source

pub const fn budget(&self) -> u64

The budget (the length of the deadline).

Source

pub const fn expiry(&self) -> u64

The instant the deadline expires, i.e. start + budget (saturating).

Examples found in repository?
examples/basic.rs (line 18)
9fn main() {
10    // A 1-second budget for the whole operation.
11    let policy = Timeout::new(1_000);
12
13    // Pretend the operation starts at t = 0.
14    let deadline: Deadline = policy.start(0);
15    println!(
16        "budget: {} ms, expires at t = {}",
17        policy.budget(),
18        deadline.expiry()
19    );
20
21    // A fake monotonic clock and a fixed retry delay.
22    let mut now = 0;
23    let attempt_cost = 250; // each attempt + wait advances the clock by this much
24
25    for attempt in 1.. {
26        match deadline.check(now) {
27            None => {
28                println!(
29                    "t = {now}: deadline expired, giving up after {} attempts",
30                    attempt - 1
31                );
32                break;
33            }
34            Some(remaining) => {
35                // Never wait longer than the time left in the budget.
36                let wait = deadline.clamp(now, attempt_cost);
37                println!("t = {now}: attempt {attempt} ({remaining} ms left, waiting {wait} ms)");
38                now += attempt_cost;
39            }
40        }
41    }
42}
Source

pub const fn elapsed(&self, now: u64) -> u64

Time elapsed since start at now.

Saturates to 0 when now is before start.

Source

pub const fn remaining(&self, now: u64) -> u64

Time left until expiry at now.

Saturates to 0 once the deadline has expired.

Source

pub const fn is_expired(&self, now: u64) -> bool

Whether the deadline has expired at now (now >= expiry).

Source

pub const fn check(&self, now: u64) -> Option<u64>

Returns the remaining time if the deadline is still live at now, or None once it has expired.

Examples found in repository?
examples/basic.rs (line 26)
9fn main() {
10    // A 1-second budget for the whole operation.
11    let policy = Timeout::new(1_000);
12
13    // Pretend the operation starts at t = 0.
14    let deadline: Deadline = policy.start(0);
15    println!(
16        "budget: {} ms, expires at t = {}",
17        policy.budget(),
18        deadline.expiry()
19    );
20
21    // A fake monotonic clock and a fixed retry delay.
22    let mut now = 0;
23    let attempt_cost = 250; // each attempt + wait advances the clock by this much
24
25    for attempt in 1.. {
26        match deadline.check(now) {
27            None => {
28                println!(
29                    "t = {now}: deadline expired, giving up after {} attempts",
30                    attempt - 1
31                );
32                break;
33            }
34            Some(remaining) => {
35                // Never wait longer than the time left in the budget.
36                let wait = deadline.clamp(now, attempt_cost);
37                println!("t = {now}: attempt {attempt} ({remaining} ms left, waiting {wait} ms)");
38                now += attempt_cost;
39            }
40        }
41    }
42}
Source

pub const fn allows(&self, now: u64, duration: u64) -> bool

Whether an operation that needs duration units can finish before the deadline at now (remaining(now) >= duration).

A duration of 0 is always allowed, even once the deadline has expired.

Source

pub const fn clamp(&self, now: u64, duration: u64) -> u64

Caps duration so it does not run past the deadline: the smaller of duration and remaining at now.

Handy for bounding a backoff delay by the time left in the budget.

Examples found in repository?
examples/basic.rs (line 36)
9fn main() {
10    // A 1-second budget for the whole operation.
11    let policy = Timeout::new(1_000);
12
13    // Pretend the operation starts at t = 0.
14    let deadline: Deadline = policy.start(0);
15    println!(
16        "budget: {} ms, expires at t = {}",
17        policy.budget(),
18        deadline.expiry()
19    );
20
21    // A fake monotonic clock and a fixed retry delay.
22    let mut now = 0;
23    let attempt_cost = 250; // each attempt + wait advances the clock by this much
24
25    for attempt in 1.. {
26        match deadline.check(now) {
27            None => {
28                println!(
29                    "t = {now}: deadline expired, giving up after {} attempts",
30                    attempt - 1
31                );
32                break;
33            }
34            Some(remaining) => {
35                // Never wait longer than the time left in the budget.
36                let wait = deadline.clamp(now, attempt_cost);
37                println!("t = {now}: attempt {attempt} ({remaining} ms left, waiting {wait} ms)");
38                now += attempt_cost;
39            }
40        }
41    }
42}
Source§

impl Deadline

Convenience methods that read the current time from a Clock instead of taking an explicit now: u64.

Available with the core feature. Each forwards to the matching now-taking method, which remains the primitive API.

Source

pub fn elapsed_now<C: Clock>(&self, clock: &C) -> u64

Like elapsed, reading the time from clock.

Source

pub fn remaining_now<C: Clock>(&self, clock: &C) -> u64

Like remaining, reading the time from clock.

Source

pub fn is_expired_now<C: Clock>(&self, clock: &C) -> bool

Like is_expired, reading the time from clock.

Source

pub fn check_now<C: Clock>(&self, clock: &C) -> Option<u64>

Like check, reading the time from clock.

Source

pub fn allows_now<C: Clock>(&self, clock: &C, duration: u64) -> bool

Like allows, reading the time from clock.

Source

pub fn clamp_now<C: Clock>(&self, clock: &C, duration: u64) -> u64

Like clamp, reading the time from clock.

Trait Implementations§

Source§

impl Clone for Deadline

Source§

fn clone(&self) -> Deadline

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for Deadline

Source§

impl Debug for Deadline

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Deadline

Source§

fn default() -> Deadline

Returns the “default value” for a type. Read more
Source§

impl Eq for Deadline

Source§

impl Hash for Deadline

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Deadline

Source§

fn eq(&self, other: &Deadline) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl StructuralPartialEq for Deadline

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.