tokio_util/time/
mod.rs

1//! Additional utilities for tracking time.
2//!
3//! This module provides additional utilities for executing code after a set period
4//! of time. Currently there is only one:
5//!
6//! * `DelayQueue`: A queue where items are returned once the requested delay
7//!   has expired.
8//!
9//! This type must be used from within the context of the `Runtime`.
10
11use std::time::Duration;
12
13mod wheel;
14
15pub mod delay_queue;
16
17// re-export `FutureExt` to avoid breaking change
18#[doc(inline)]
19pub use crate::future::FutureExt;
20
21#[doc(inline)]
22pub use delay_queue::DelayQueue;
23
24// ===== Internal utils =====
25
26enum Round {
27    Up,
28    Down,
29}
30
31/// Convert a `Duration` to milliseconds, rounding up and saturating at
32/// `u64::MAX`.
33///
34/// The saturating is fine because `u64::MAX` milliseconds are still many
35/// million years.
36#[inline]
37fn ms(duration: Duration, round: Round) -> u64 {
38    const NANOS_PER_MILLI: u32 = 1_000_000;
39    const MILLIS_PER_SEC: u64 = 1_000;
40
41    // Round up.
42    let millis = match round {
43        Round::Up => (duration.subsec_nanos() + NANOS_PER_MILLI - 1) / NANOS_PER_MILLI,
44        Round::Down => duration.subsec_millis(),
45    };
46
47    duration
48        .as_secs()
49        .saturating_mul(MILLIS_PER_SEC)
50        .saturating_add(u64::from(millis))
51}