time: rename Delay future to Sleep (#2932)

This commit is contained in:
Juan Alvarez 2020-10-08 22:35:12 -05:00 committed by GitHub
parent b704c53b9c
commit 60d81bbe10
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
25 changed files with 186 additions and 186 deletions

View File

@ -20,7 +20,7 @@
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio::sync::mpsc;
use tokio::time::{self, Delay, Duration, Instant};
use tokio::time::{self, Duration, Instant, Sleep};
use futures_core::ready;
use std::collections::VecDeque;
@ -67,7 +67,7 @@ enum Action {
struct Inner {
actions: VecDeque<Action>,
waiting: Option<Instant>,
sleep: Option<Delay>,
sleep: Option<Sleep>,
read_wait: Option<Waker>,
rx: mpsc::UnboundedReceiver<Action>,
}

View File

@ -18,7 +18,7 @@ fn async_fn() {
}
#[test]
fn test_delay() {
fn test_sleep() {
let deadline = Instant::now() + Duration::from_millis(100);
block_on(async {

View File

@ -7,7 +7,7 @@
use crate::time::wheel::{self, Wheel};
use futures_core::ready;
use tokio::time::{sleep_until, Delay, Duration, Error, Instant};
use tokio::time::{sleep_until, Duration, Error, Instant, Sleep};
use slab::Slab;
use std::cmp;
@ -138,7 +138,7 @@ pub struct DelayQueue<T> {
expired: Stack<T>,
/// Delay expiring when the *first* item in the queue expires
delay: Option<Delay>,
delay: Option<Sleep>,
/// Wheel polling state
wheel_now: u64,

View File

@ -25,7 +25,7 @@
//! provides a few major components:
//!
//! * Tools for [working with asynchronous tasks][tasks], including
//! [synchronization primitives and channels][sync] and [timeouts, delays, and
//! [synchronization primitives and channels][sync] and [timeouts, sleeps, and
//! intervals][time].
//! * APIs for [performing asynchronous I/O][io], including [TCP and UDP][net] sockets,
//! [filesystem][fs] operations, and [process] and [signal] management.
@ -183,13 +183,13 @@
//!
//! The [`tokio::time`] module provides utilities for tracking time and
//! scheduling work. This includes functions for setting [timeouts][timeout] for
//! tasks, [delaying][delay] work to run in the future, or [repeating an operation at an
//! tasks, [sleeping][sleep] work to run in the future, or [repeating an operation at an
//! interval][interval].
//!
//! In order to use `tokio::time`, the "time" feature flag must be enabled.
//!
//! [`tokio::time`]: crate::time
//! [delay]: crate::time::sleep()
//! [sleep]: crate::time::sleep()
//! [interval]: crate::time::interval()
//! [timeout]: crate::time::timeout()
//!

View File

@ -63,9 +63,9 @@
/// Given that `if` preconditions are used to disable `select!` branches, some
/// caution must be used to avoid missing values.
///
/// For example, here is **incorrect** usage of `delay` with `if`. The objective
/// For example, here is **incorrect** usage of `sleep` with `if`. The objective
/// is to repeatedly run an asynchronous task for up to 50 milliseconds.
/// However, there is a potential for the `delay` completion to be missed.
/// However, there is a potential for the `sleep` completion to be missed.
///
/// ```no_run
/// use tokio::time::{self, Duration};
@ -76,11 +76,11 @@
///
/// #[tokio::main]
/// async fn main() {
/// let mut delay = time::sleep(Duration::from_millis(50));
/// let mut sleep = time::sleep(Duration::from_millis(50));
///
/// while !delay.is_elapsed() {
/// while !sleep.is_elapsed() {
/// tokio::select! {
/// _ = &mut delay, if !delay.is_elapsed() => {
/// _ = &mut sleep, if !sleep.is_elapsed() => {
/// println!("operation timed out");
/// }
/// _ = some_async_work() => {
@ -91,11 +91,11 @@
/// }
/// ```
///
/// In the above example, `delay.is_elapsed()` may return `true` even if
/// `delay.poll()` never returned `Ready`. This opens up a potential race
/// condition where `delay` expires between the `while !delay.is_elapsed()`
/// In the above example, `sleep.is_elapsed()` may return `true` even if
/// `sleep.poll()` never returned `Ready`. This opens up a potential race
/// condition where `sleep` expires between the `while !sleep.is_elapsed()`
/// check and the call to `select!` resulting in the `some_async_work()` call to
/// run uninterrupted despite the delay having elapsed.
/// run uninterrupted despite the sleep having elapsed.
///
/// One way to write the above example without the race would be:
///
@ -109,11 +109,11 @@
///
/// #[tokio::main]
/// async fn main() {
/// let mut delay = time::sleep(Duration::from_millis(50));
/// let mut sleep = time::sleep(Duration::from_millis(50));
///
/// loop {
/// tokio::select! {
/// _ = &mut delay => {
/// _ = &mut sleep => {
/// println!("operation timed out");
/// break;
/// }
@ -226,7 +226,7 @@
/// #[tokio::main]
/// async fn main() {
/// let mut stream = stream::iter(vec![1, 2, 3]);
/// let mut delay = time::sleep(Duration::from_secs(1));
/// let mut sleep = time::sleep(Duration::from_secs(1));
///
/// loop {
/// tokio::select! {
@ -237,7 +237,7 @@
/// break;
/// }
/// }
/// _ = &mut delay => {
/// _ = &mut sleep => {
/// println!("timeout");
/// break;
/// }

View File

@ -28,7 +28,7 @@ pub(crate) struct Handle {
impl Handle {
/// Enter the runtime context. This allows you to construct types that must
/// have an executor available on creation such as [`Delay`] or [`TcpStream`].
/// have an executor available on creation such as [`Sleep`] or [`TcpStream`].
/// It will also allow you to call methods such as [`tokio::spawn`].
pub(crate) fn enter<F, R>(&self, f: F) -> R
where

View File

@ -450,10 +450,10 @@ impl Runtime {
}
/// Enter the runtime context. This allows you to construct types that must
/// have an executor available on creation such as [`Delay`] or [`TcpStream`].
/// have an executor available on creation such as [`Sleep`] or [`TcpStream`].
/// It will also allow you to call methods such as [`tokio::spawn`].
///
/// [`Delay`]: struct@crate::time::Delay
/// [`Sleep`]: struct@crate::time::Sleep
/// [`TcpStream`]: struct@crate::net::TcpStream
/// [`tokio::spawn`]: fn@crate::spawn
///

View File

@ -1,7 +1,7 @@
//! Slow down a stream by enforcing a delay between items.
use crate::stream::Stream;
use crate::time::{Delay, Duration, Instant};
use crate::time::{Duration, Instant, Sleep};
use std::future::Future;
use std::marker::Unpin;
@ -17,7 +17,7 @@ where
let delay = if duration == Duration::from_millis(0) {
None
} else {
Some(Delay::new_timeout(Instant::now() + duration, duration))
Some(Sleep::new_timeout(Instant::now() + duration, duration))
};
Throttle {
@ -34,7 +34,7 @@ pin_project! {
#[must_use = "streams do nothing unless polled"]
pub struct Throttle<T> {
// `None` when duration is zero.
delay: Option<Delay>,
delay: Option<Sleep>,
duration: Duration,
// Set to true when `delay` has returned ready, but `stream` hasn't.

View File

@ -1,5 +1,5 @@
use crate::stream::{Fuse, Stream};
use crate::time::{Delay, Elapsed, Instant};
use crate::time::{Elapsed, Instant, Sleep};
use core::future::Future;
use core::pin::Pin;
@ -14,7 +14,7 @@ pin_project! {
pub struct Timeout<S> {
#[pin]
stream: Fuse<S>,
deadline: Delay,
deadline: Sleep,
duration: Duration,
poll_deadline: bool,
}
@ -23,7 +23,7 @@ pin_project! {
impl<S: Stream> Timeout<S> {
pub(super) fn new(stream: S, duration: Duration) -> Self {
let next = Instant::now() + duration;
let deadline = Delay::new_timeout(next, duration);
let deadline = Sleep::new_timeout(next, duration);
Timeout {
stream: Fuse::new(stream),

View File

@ -359,11 +359,11 @@
//! let mut conf = rx.borrow().clone();
//!
//! let mut op_start = Instant::now();
//! let mut delay = time::sleep_until(op_start + conf.timeout);
//! let mut sleep = time::sleep_until(op_start + conf.timeout);
//!
//! loop {
//! tokio::select! {
//! _ = &mut delay => {
//! _ = &mut sleep => {
//! // The operation elapsed. Restart it
//! op.set(my_async_operation());
//!
@ -371,14 +371,14 @@
//! op_start = Instant::now();
//!
//! // Restart the timeout
//! delay = time::sleep_until(op_start + conf.timeout);
//! sleep = time::sleep_until(op_start + conf.timeout);
//! }
//! _ = rx.changed() => {
//! conf = rx.borrow().clone();
//!
//! // The configuration has been updated. Update the
//! // `delay` using the new `timeout` value.
//! delay.reset(op_start + conf.timeout);
//! // `sleep` using the new `timeout` value.
//! sleep.reset(op_start + conf.timeout);
//! }
//! _ = &mut op => {
//! // The operation completed!

View File

@ -58,7 +58,7 @@ cfg_test_util! {
/// The current value of `Instant::now()` is saved and all subsequent calls
/// to `Instant::now()` until the timer wheel is checked again will return the saved value.
/// Once the timer wheel is checked, time will immediately advance to the next registered
/// `Delay`. This is useful for running tests that depend on time.
/// `Sleep`. This is useful for running tests that depend on time.
///
/// # Panics
///

View File

@ -11,7 +11,7 @@ use std::sync::{Arc, Weak};
use std::task::{self, Poll};
use std::u64;
/// Internal state shared between a `Delay` instance and the timer.
/// Internal state shared between a `Sleep` instance and the timer.
///
/// This struct is used as a node in two intrusive data structures:
///
@ -28,7 +28,7 @@ pub(crate) struct Entry {
time: CachePadded<UnsafeCell<Time>>,
/// Timer internals. Using a weak pointer allows the timer to shutdown
/// without all `Delay` instances having completed.
/// without all `Sleep` instances having completed.
///
/// When empty, it means that the entry has not yet been linked with a
/// timer instance.
@ -69,8 +69,8 @@ pub(crate) struct Entry {
/// When the entry expires, relative to the `start` of the timer
/// (Inner::start). This is only used by the timer.
///
/// A `Delay` instance can be reset to a different deadline by the thread
/// that owns the `Delay` instance. In this case, the timer thread will not
/// A `Sleep` instance can be reset to a different deadline by the thread
/// that owns the `Sleep` instance. In this case, the timer thread will not
/// immediately know that this has happened. The timer thread must know the
/// last deadline that it saw as it uses this value to locate the entry in
/// its wheel.
@ -94,7 +94,7 @@ pub(crate) struct Entry {
pub(crate) prev_stack: UnsafeCell<*const Entry>,
}
/// Stores the info for `Delay`.
/// Stores the info for `Sleep`.
#[derive(Debug)]
pub(crate) struct Time {
pub(crate) deadline: Instant,

View File

@ -20,12 +20,12 @@ use std::sync::Arc;
use std::usize;
use std::{cmp, fmt};
/// Time implementation that drives [`Delay`][delay], [`Interval`][interval], and [`Timeout`][timeout].
/// Time implementation that drives [`Sleep`][sleep], [`Interval`][interval], and [`Timeout`][timeout].
///
/// A `Driver` instance tracks the state necessary for managing time and
/// notifying the [`Delay`][delay] instances once their deadlines are reached.
/// notifying the [`Sleep`][sleep] instances once their deadlines are reached.
///
/// It is expected that a single instance manages many individual [`Delay`][delay]
/// It is expected that a single instance manages many individual [`Sleep`][sleep]
/// instances. The `Driver` implementation is thread-safe and, as such, is able
/// to handle callers from across threads.
///
@ -36,9 +36,9 @@ use std::{cmp, fmt};
/// The driver has a resolution of one millisecond. Any unit of time that falls
/// between milliseconds are rounded up to the next millisecond.
///
/// When an instance is dropped, any outstanding [`Delay`][delay] instance that has not
/// When an instance is dropped, any outstanding [`Sleep`][sleep] instance that has not
/// elapsed will be notified with an error. At this point, calling `poll` on the
/// [`Delay`][delay] instance will result in panic.
/// [`Sleep`][sleep] instance will result in panic.
///
/// # Implementation
///
@ -65,14 +65,14 @@ use std::{cmp, fmt};
/// * Level 5: 64 x ~12 day slots.
///
/// When the timer processes entries at level zero, it will notify all the
/// `Delay` instances as their deadlines have been reached. For all higher
/// `Sleep` instances as their deadlines have been reached. For all higher
/// levels, all entries will be redistributed across the wheel at the next level
/// down. Eventually, as time progresses, entries with [`Delay`][delay] instances will
/// down. Eventually, as time progresses, entries with [`Sleep`][sleep] instances will
/// either be canceled (dropped) or their associated entries will reach level
/// zero and be notified.
///
/// [paper]: http://www.cs.columbia.edu/~nahum/w6998/papers/ton97-timing-wheels.pdf
/// [delay]: crate::time::Delay
/// [sleep]: crate::time::Sleep
/// [timeout]: crate::time::Timeout
/// [interval]: crate::time::Interval
#[derive(Debug)]
@ -138,7 +138,7 @@ where
/// Returns a handle to the timer.
///
/// The `Handle` is how `Delay` instances are created. The `Delay` instances
/// The `Handle` is how `Sleep` instances are created. The `Sleep` instances
/// can either be created directly or the `Handle` instance can be passed to
/// `with_default`, setting the timer as the default timer for the execution
/// context.

View File

@ -13,7 +13,7 @@ use std::fmt;
/// succeed in the future.
///
/// * `at_capacity` occurs when a timer operation is attempted, but the timer
/// instance is currently handling its maximum number of outstanding delays.
/// instance is currently handling its maximum number of outstanding sleep instances.
/// In this case, the operation is not able to be performed at the current
/// moment, and `at_capacity` is returned. This is a transient error, i.e., at
/// some point in the future, if the operation is attempted again, it might

View File

@ -1,5 +1,5 @@
use crate::future::poll_fn;
use crate::time::{sleep_until, Delay, Duration, Instant};
use crate::time::{sleep_until, Duration, Instant, Sleep};
use std::future::Future;
use std::pin::Pin;
@ -115,7 +115,7 @@ pub fn interval_at(start: Instant, period: Duration) -> Interval {
#[derive(Debug)]
pub struct Interval {
/// Future that completes the next time the `Interval` yields a value.
delay: Delay,
delay: Sleep,
/// The duration between values yielded by `Interval`.
period: Duration,

View File

@ -3,7 +3,7 @@
//! This module provides a number of types for executing code after a set period
//! of time.
//!
//! * `Delay` is a future that does no work and completes at a specific `Instant`
//! * `Sleep` is a future that does no work and completes at a specific `Instant`
//! in time.
//!
//! * `Interval` is a stream yielding a value at a fixed period. It is
@ -93,8 +93,8 @@ pub(crate) use self::clock::Clock;
#[cfg(feature = "test-util")]
pub use clock::{advance, pause, resume};
mod delay;
pub use delay::{sleep, sleep_until, Delay};
mod sleep;
pub use sleep::{sleep, sleep_until, Sleep};
pub(crate) mod driver;

View File

@ -8,16 +8,16 @@ use std::task::{self, Poll};
/// Waits until `deadline` is reached.
///
/// No work is performed while awaiting on the delay to complete. The delay
/// No work is performed while awaiting on the sleep future to complete. `Sleep`
/// operates at millisecond granularity and should not be used for tasks that
/// require high-resolution timers.
///
/// # Cancellation
///
/// Canceling a delay is done by dropping the returned future. No additional
/// Canceling a sleep instance is done by dropping the returned future. No additional
/// cleanup work is required.
pub fn sleep_until(deadline: Instant) -> Delay {
Delay::new_timeout(deadline, Duration::from_millis(0))
pub fn sleep_until(deadline: Instant) -> Sleep {
Sleep::new_timeout(deadline, Duration::from_millis(0))
}
/// Waits until `duration` has elapsed.
@ -25,7 +25,7 @@ pub fn sleep_until(deadline: Instant) -> Delay {
/// Equivalent to `sleep_until(Instant::now() + duration)`. An asynchronous
/// analog to `std::thread::sleep`.
///
/// No work is performed while awaiting on the delay to complete. The delay
/// No work is performed while awaiting on the sleep future to complete. `Sleep`
/// operates at millisecond granularity and should not be used for tasks that
/// require high-resolution timers.
///
@ -33,7 +33,7 @@ pub fn sleep_until(deadline: Instant) -> Delay {
///
/// # Cancellation
///
/// Canceling a delay is done by dropping the returned future. No additional
/// Canceling a sleep instance is done by dropping the returned future. No additional
/// cleanup work is required.
///
/// # Examples
@ -51,7 +51,7 @@ pub fn sleep_until(deadline: Instant) -> Delay {
/// ```
///
/// [`interval`]: crate::time::interval()
pub fn sleep(duration: Duration) -> Delay {
pub fn sleep(duration: Duration) -> Sleep {
sleep_until(Instant::now() + duration)
}
@ -59,19 +59,19 @@ pub fn sleep(duration: Duration) -> Delay {
/// [`sleep_until`](sleep_until).
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Delay {
/// The link between the `Delay` instance and the timer that drives it.
pub struct Sleep {
/// The link between the `Sleep` instance and the timer that drives it.
///
/// This also stores the `deadline` value.
entry: Arc<Entry>,
}
impl Delay {
pub(crate) fn new_timeout(deadline: Instant, duration: Duration) -> Delay {
impl Sleep {
pub(crate) fn new_timeout(deadline: Instant, duration: Duration) -> Sleep {
let handle = Handle::current();
let entry = Entry::new(&handle, deadline, duration);
Delay { entry }
Sleep { entry }
}
/// Returns the instant at which the future will complete.
@ -79,16 +79,16 @@ impl Delay {
self.entry.time_ref().deadline
}
/// Returns `true` if the `Delay` has elapsed
/// Returns `true` if `Sleep` has elapsed.
///
/// A `Delay` is elapsed when the requested duration has elapsed.
/// A `Sleep` instance is elapsed when the requested duration has elapsed.
pub fn is_elapsed(&self) -> bool {
self.entry.is_elapsed()
}
/// Resets the `Delay` instance to a new deadline.
/// Resets the `Sleep` instance to a new deadline.
///
/// Calling this function allows changing the instant at which the `Delay`
/// Calling this function allows changing the instant at which the `Sleep`
/// future completes without having to create new associated state.
///
/// This function can be called both before and after the future has
@ -112,14 +112,14 @@ impl Delay {
}
}
impl Future for Delay {
impl Future for Sleep {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
// `poll_elapsed` can return an error in two cases:
//
// - AtCapacity: this is a pathological case where far too many
// delays have been scheduled.
// sleep instances have been scheduled.
// - Shutdown: No timer has been setup, which is a mis-use error.
//
// Both cases are extremely rare, and pretty accurately fit into
@ -132,7 +132,7 @@ impl Future for Delay {
}
}
impl Drop for Delay {
impl Drop for Sleep {
fn drop(&mut self) {
Entry::cancel(&self.entry);
}

View File

@ -1,4 +1,4 @@
mod test_delay;
mod test_sleep;
use crate::time::{self, Instant};
use std::time::Duration;
@ -8,15 +8,15 @@ fn assert_sync<T: Sync>() {}
#[test]
fn registration_is_send_and_sync() {
use crate::time::delay::Delay;
use crate::time::sleep::Sleep;
assert_send::<Delay>();
assert_sync::<Delay>();
assert_send::<Sleep>();
assert_sync::<Sleep>();
}
#[test]
#[should_panic]
fn delay_is_eager() {
fn sleep_is_eager() {
let when = Instant::now() + Duration::from_millis(100);
let _ = time::sleep_until(when);
}

View File

@ -25,12 +25,12 @@ fn frozen_utility_returns_correct_advanced_duration() {
}
#[test]
fn immediate_delay() {
fn immediate_sleep() {
let (mut driver, clock, handle) = setup();
let start = clock.now();
let when = clock.now();
let mut e = task::spawn(delay_until(&handle, when));
let mut e = task::spawn(sleep_until(&handle, when));
assert_ready_ok!(poll!(e));
@ -41,15 +41,15 @@ fn immediate_delay() {
}
#[test]
fn delayed_delay_level_0() {
fn delayed_sleep_level_0() {
let (mut driver, clock, handle) = setup();
let start = clock.now();
for &i in &[1, 10, 60] {
// Create a `Delay` that elapses in the future
let mut e = task::spawn(delay_until(&handle, start + ms(i)));
// Create a `Sleep` that elapses in the future
let mut e = task::spawn(sleep_until(&handle, start + ms(i)));
// The delay has not elapsed.
// The sleep instance has not elapsed.
assert_pending!(poll!(e));
assert_ok!(driver.park());
@ -60,13 +60,13 @@ fn delayed_delay_level_0() {
}
#[test]
fn sub_ms_delayed_delay() {
fn sub_ms_delayed_sleep() {
let (mut driver, clock, handle) = setup();
for _ in 0..5 {
let deadline = clock.now() + ms(1) + Duration::new(0, 1);
let mut e = task::spawn(delay_until(&handle, deadline));
let mut e = task::spawn(sleep_until(&handle, deadline));
assert_pending!(poll!(e));
@ -80,14 +80,14 @@ fn sub_ms_delayed_delay() {
}
#[test]
fn delayed_delay_wrapping_level_0() {
fn delayed_sleep_wrapping_level_0() {
let (mut driver, clock, handle) = setup();
let start = clock.now();
assert_ok!(driver.park_timeout(ms(5)));
assert_eq!(clock.now() - start, ms(5));
let mut e = task::spawn(delay_until(&handle, clock.now() + ms(60)));
let mut e = task::spawn(sleep_until(&handle, clock.now() + ms(60)));
assert_pending!(poll!(e));
@ -106,15 +106,15 @@ fn timer_wrapping_with_higher_levels() {
let (mut driver, clock, handle) = setup();
let start = clock.now();
// Set delay to hit level 1
let mut e1 = task::spawn(delay_until(&handle, clock.now() + ms(64)));
// Set sleep to hit level 1
let mut e1 = task::spawn(sleep_until(&handle, clock.now() + ms(64)));
assert_pending!(poll!(e1));
// Turn a bit
assert_ok!(driver.park_timeout(ms(5)));
// Set timeout such that it will hit level 0, but wrap
let mut e2 = task::spawn(delay_until(&handle, clock.now() + ms(60)));
let mut e2 = task::spawn(sleep_until(&handle, clock.now() + ms(60)));
assert_pending!(poll!(e2));
// This should result in s1 firing
@ -131,14 +131,14 @@ fn timer_wrapping_with_higher_levels() {
}
#[test]
fn delay_with_deadline_in_past() {
fn sleep_with_deadline_in_past() {
let (mut driver, clock, handle) = setup();
let start = clock.now();
// Create `Delay` that elapsed immediately.
let mut e = task::spawn(delay_until(&handle, clock.now() - ms(100)));
// Create `Sleep` that elapsed immediately.
let mut e = task::spawn(sleep_until(&handle, clock.now() - ms(100)));
// Even though the delay expires in the past, it is not ready yet
// Even though the `Sleep` expires in the past, it is not ready yet
// because the timer must observe it.
assert_ready_ok!(poll!(e));
@ -150,37 +150,37 @@ fn delay_with_deadline_in_past() {
}
#[test]
fn delayed_delay_level_1() {
fn delayed_sleep_level_1() {
let (mut driver, clock, handle) = setup();
let start = clock.now();
// Create a `Delay` that elapses in the future
let mut e = task::spawn(delay_until(&handle, clock.now() + ms(234)));
// Create a `Sleep` that elapses in the future
let mut e = task::spawn(sleep_until(&handle, clock.now() + ms(234)));
// The delay has not elapsed.
// The sleep has not elapsed.
assert_pending!(poll!(e));
// Turn the timer, this will wake up to cascade the timer down.
assert_ok!(driver.park_timeout(ms(1000)));
assert_eq!(clock.now() - start, ms(192));
// The delay has not elapsed.
// The sleep has not elapsed.
assert_pending!(poll!(e));
// Turn the timer again
assert_ok!(driver.park_timeout(ms(1000)));
assert_eq!(clock.now() - start, ms(234));
// The delay has elapsed.
// The sleep has elapsed.
assert_ready_ok!(poll!(e));
let (mut driver, clock, handle) = setup();
let start = clock.now();
// Create a `Delay` that elapses in the future
let mut e = task::spawn(delay_until(&handle, clock.now() + ms(234)));
// Create a `Sleep` that elapses in the future
let mut e = task::spawn(sleep_until(&handle, clock.now() + ms(234)));
// The delay has not elapsed.
// The sleep has not elapsed.
assert_pending!(poll!(e));
// Turn the timer with a smaller timeout than the cascade.
@ -193,14 +193,14 @@ fn delayed_delay_level_1() {
assert_ok!(driver.park_timeout(ms(1000)));
assert_eq!(clock.now() - start, ms(192));
// The delay has not elapsed.
// The sleep has not elapsed.
assert_pending!(poll!(e));
// Turn the timer again
assert_ok!(driver.park_timeout(ms(1000)));
assert_eq!(clock.now() - start, ms(234));
// The delay has elapsed.
// The sleep has elapsed.
assert_ready_ok!(poll!(e));
}
@ -209,22 +209,22 @@ fn concurrently_set_two_timers_second_one_shorter() {
let (mut driver, clock, handle) = setup();
let start = clock.now();
let mut e1 = task::spawn(delay_until(&handle, clock.now() + ms(500)));
let mut e2 = task::spawn(delay_until(&handle, clock.now() + ms(200)));
let mut e1 = task::spawn(sleep_until(&handle, clock.now() + ms(500)));
let mut e2 = task::spawn(sleep_until(&handle, clock.now() + ms(200)));
// The delay has not elapsed
// The sleep has not elapsed
assert_pending!(poll!(e1));
assert_pending!(poll!(e2));
// Delay until a cascade
// Sleep until a cascade
assert_ok!(driver.park());
assert_eq!(clock.now() - start, ms(192));
// Delay until the second timer.
// Sleep until the second timer.
assert_ok!(driver.park());
assert_eq!(clock.now() - start, ms(200));
// The shorter delay fires
// The shorter sleep fires
assert_ready_ok!(poll!(e2));
assert_pending!(poll!(e1));
@ -233,7 +233,7 @@ fn concurrently_set_two_timers_second_one_shorter() {
assert_pending!(poll!(e1));
// Turn again, this time the time will advance to the second delay
// Turn again, this time the time will advance to the second sleep
assert_ok!(driver.park());
assert_eq!(clock.now() - start, ms(500));
@ -241,37 +241,37 @@ fn concurrently_set_two_timers_second_one_shorter() {
}
#[test]
fn short_delay() {
fn short_sleep() {
let (mut driver, clock, handle) = setup();
let start = clock.now();
// Create a `Delay` that elapses in the future
let mut e = task::spawn(delay_until(&handle, clock.now() + ms(1)));
// Create a `Sleep` that elapses in the future
let mut e = task::spawn(sleep_until(&handle, clock.now() + ms(1)));
// The delay has not elapsed.
// The sleep has not elapsed.
assert_pending!(poll!(e));
// Turn the timer, but not enough time will go by.
assert_ok!(driver.park());
// The delay has elapsed.
// The sleep has elapsed.
assert_ready_ok!(poll!(e));
// The time has advanced to the point of the delay elapsing.
// The time has advanced to the point of the sleep elapsing.
assert_eq!(clock.now() - start, ms(1));
}
#[test]
fn sorta_long_delay_until() {
fn sorta_long_sleep_until() {
const MIN_5: u64 = 5 * 60 * 1000;
let (mut driver, clock, handle) = setup();
let start = clock.now();
// Create a `Delay` that elapses in the future
let mut e = task::spawn(delay_until(&handle, clock.now() + ms(MIN_5)));
// Create a `Sleep` that elapses in the future
let mut e = task::spawn(sleep_until(&handle, clock.now() + ms(MIN_5)));
// The delay has not elapsed.
// The sleep has not elapsed.
assert_pending!(poll!(e));
let cascades = &[262_144, 262_144 + 9 * 4096, 262_144 + 9 * 4096 + 15 * 64];
@ -286,21 +286,21 @@ fn sorta_long_delay_until() {
assert_ok!(driver.park());
assert_eq!(clock.now() - start, ms(MIN_5));
// The delay has elapsed.
// The sleep has elapsed.
assert_ready_ok!(poll!(e));
}
#[test]
fn very_long_delay() {
fn very_long_sleep() {
const MO_5: u64 = 5 * 30 * 24 * 60 * 60 * 1000;
let (mut driver, clock, handle) = setup();
let start = clock.now();
// Create a `Delay` that elapses in the future
let mut e = task::spawn(delay_until(&handle, clock.now() + ms(MO_5)));
// Create a `Sleep` that elapses in the future
let mut e = task::spawn(sleep_until(&handle, clock.now() + ms(MO_5)));
// The delay has not elapsed.
// The sleep has not elapsed.
assert_pending!(poll!(e));
let cascades = &[
@ -320,10 +320,10 @@ fn very_long_delay() {
// Turn the timer, but not enough time will go by.
assert_ok!(driver.park());
// The time has advanced to the point of the delay elapsing.
// The time has advanced to the point of the sleep elapsing.
assert_eq!(clock.now() - start, ms(MO_5));
// The delay has elapsed.
// The sleep has elapsed.
assert_ready_ok!(poll!(e));
}
@ -365,9 +365,9 @@ fn unpark_is_delayed() {
let mut driver = Driver::new(MockPark(clock.clone()), clock.clone());
let handle = driver.handle();
let mut e1 = task::spawn(delay_until(&handle, clock.now() + ms(100)));
let mut e2 = task::spawn(delay_until(&handle, clock.now() + ms(101)));
let mut e3 = task::spawn(delay_until(&handle, clock.now() + ms(200)));
let mut e1 = task::spawn(sleep_until(&handle, clock.now() + ms(100)));
let mut e2 = task::spawn(sleep_until(&handle, clock.now() + ms(101)));
let mut e3 = task::spawn(sleep_until(&handle, clock.now() + ms(200)));
assert_pending!(poll!(e1));
assert_pending!(poll!(e2));
@ -394,7 +394,7 @@ fn set_timeout_at_deadline_greater_than_max_timer() {
assert_ok!(driver.park_timeout(ms(YR_1)));
}
let mut e = task::spawn(delay_until(&handle, clock.now() + ms(1)));
let mut e = task::spawn(sleep_until(&handle, clock.now() + ms(1)));
assert_pending!(poll!(e));
assert_ok!(driver.park_timeout(ms(1000)));
@ -412,7 +412,7 @@ fn setup() -> (Driver<MockPark>, Clock, Handle) {
(driver, clock, handle)
}
fn delay_until(handle: &Handle, when: Instant) -> Arc<Entry> {
fn sleep_until(handle: &Handle, when: Instant) -> Arc<Entry> {
Entry::new(&handle, when, ms(0))
}

View File

@ -4,7 +4,7 @@
//!
//! [`Timeout`]: struct@Timeout
use crate::time::{sleep_until, Delay, Duration, Instant};
use crate::time::{sleep_until, Duration, Instant, Sleep};
use pin_project_lite::pin_project;
use std::fmt;
@ -50,7 +50,7 @@ pub fn timeout<T>(duration: Duration, future: T) -> Timeout<T>
where
T: Future,
{
let delay = Delay::new_timeout(Instant::now() + duration, duration);
let delay = Sleep::new_timeout(Instant::now() + duration, duration);
Timeout::new_with_delay(future, delay)
}
@ -108,7 +108,7 @@ pin_project! {
#[pin]
value: T,
#[pin]
delay: Delay,
delay: Sleep,
}
}
@ -125,7 +125,7 @@ impl Elapsed {
}
impl<T> Timeout<T> {
pub(crate) fn new_with_delay(value: T, delay: Delay) -> Timeout<T> {
pub(crate) fn new_with_delay(value: T, delay: Sleep) -> Timeout<T> {
Timeout { value, delay }
}

View File

@ -47,7 +47,7 @@ pub(crate) struct Wheel {
/// precision of 1 millisecond.
const NUM_LEVELS: usize = 6;
/// The maximum duration of a delay
/// The maximum duration of a `Sleep`
const MAX_DURATION: u64 = (1 << (6 * NUM_LEVELS)) - 1;
#[derive(Debug)]

View File

@ -359,10 +359,10 @@ async fn join_with_select() {
async fn use_future_in_if_condition() {
use tokio::time::{self, Duration};
let mut delay = time::sleep(Duration::from_millis(50));
let mut sleep = time::sleep(Duration::from_millis(50));
tokio::select! {
_ = &mut delay, if !delay.is_elapsed() => {
_ = &mut sleep, if !sleep.is_elapsed() => {
}
_ = async { 1 } => {
}

View File

@ -430,7 +430,7 @@ rt_test! {
}
#[test]
fn delay_at_root() {
fn sleep_at_root() {
let rt = rt();
let now = Instant::now();
@ -444,7 +444,7 @@ rt_test! {
}
#[test]
fn delay_in_spawn() {
fn sleep_in_spawn() {
let rt = rt();
let now = Instant::now();
@ -515,7 +515,7 @@ rt_test! {
}
#[test]
fn delay_from_blocking() {
fn sleep_from_blocking() {
let rt = rt();
rt.block_on(async move {

View File

@ -6,7 +6,7 @@ use tokio_test::*;
use futures::StreamExt as _;
async fn maybe_delay(idx: i32) -> i32 {
async fn maybe_sleep(idx: i32) -> i32 {
if idx % 2 == 0 {
sleep(ms(200)).await;
}
@ -26,7 +26,7 @@ async fn basic_usage() {
//
// [Ok(1), Err(Elapsed), Ok(2), Ok(3), Err(Elapsed), Ok(4)]
let stream = stream::iter(1..=4).then(maybe_delay).timeout(ms(100));
let stream = stream::iter(1..=4).then(maybe_sleep).timeout(ms(100));
let mut stream = task::spawn(stream);
// First item completes immediately
@ -68,7 +68,7 @@ async fn basic_usage() {
async fn return_elapsed_errors_only_once() {
time::pause();
let stream = stream::iter(1..=3).then(maybe_delay).timeout(ms(50));
let stream = stream::iter(1..=3).then(maybe_sleep).timeout(ms(50));
let mut stream = task::spawn(stream);
// First item completes immediately
@ -97,7 +97,7 @@ async fn return_elapsed_errors_only_once() {
#[tokio::test]
async fn no_timeouts() {
let stream = stream::iter(vec![1, 3, 5])
.then(maybe_delay)
.then(maybe_sleep)
.timeout(ms(100));
let mut stream = task::spawn(stream);

View File

@ -20,7 +20,7 @@ macro_rules! assert_elapsed {
}
#[tokio::test]
async fn immediate_delay() {
async fn immediate_sleep() {
time::pause();
let now = Instant::now();
@ -31,7 +31,7 @@ async fn immediate_delay() {
}
#[tokio::test]
async fn delayed_delay_level_0() {
async fn delayed_sleep_level_0() {
time::pause();
for &i in &[1, 10, 60] {
@ -44,7 +44,7 @@ async fn delayed_delay_level_0() {
}
#[tokio::test]
async fn sub_ms_delayed_delay() {
async fn sub_ms_delayed_sleep() {
time::pause();
for _ in 0..5 {
@ -58,7 +58,7 @@ async fn sub_ms_delayed_delay() {
}
#[tokio::test]
async fn delayed_delay_wrapping_level_0() {
async fn delayed_sleep_wrapping_level_0() {
time::pause();
time::sleep(ms(5)).await;
@ -70,96 +70,96 @@ async fn delayed_delay_wrapping_level_0() {
}
#[tokio::test]
async fn reset_future_delay_before_fire() {
async fn reset_future_sleep_before_fire() {
time::pause();
let now = Instant::now();
let mut delay = task::spawn(time::sleep_until(now + ms(100)));
assert_pending!(delay.poll());
let mut sleep = task::spawn(time::sleep_until(now + ms(100)));
assert_pending!(sleep.poll());
let mut delay = delay.into_inner();
let mut sleep = sleep.into_inner();
delay.reset(Instant::now() + ms(200));
delay.await;
sleep.reset(Instant::now() + ms(200));
sleep.await;
assert_elapsed!(now, 200);
}
#[tokio::test]
async fn reset_past_delay_before_turn() {
async fn reset_past_sleep_before_turn() {
time::pause();
let now = Instant::now();
let mut delay = task::spawn(time::sleep_until(now + ms(100)));
assert_pending!(delay.poll());
let mut sleep = task::spawn(time::sleep_until(now + ms(100)));
assert_pending!(sleep.poll());
let mut delay = delay.into_inner();
let mut sleep = sleep.into_inner();
delay.reset(now + ms(80));
delay.await;
sleep.reset(now + ms(80));
sleep.await;
assert_elapsed!(now, 80);
}
#[tokio::test]
async fn reset_past_delay_before_fire() {
async fn reset_past_sleep_before_fire() {
time::pause();
let now = Instant::now();
let mut delay = task::spawn(time::sleep_until(now + ms(100)));
assert_pending!(delay.poll());
let mut sleep = task::spawn(time::sleep_until(now + ms(100)));
assert_pending!(sleep.poll());
let mut delay = delay.into_inner();
let mut sleep = sleep.into_inner();
time::sleep(ms(10)).await;
delay.reset(now + ms(80));
delay.await;
sleep.reset(now + ms(80));
sleep.await;
assert_elapsed!(now, 80);
}
#[tokio::test]
async fn reset_future_delay_after_fire() {
async fn reset_future_sleep_after_fire() {
time::pause();
let now = Instant::now();
let mut delay = time::sleep_until(now + ms(100));
let mut sleep = time::sleep_until(now + ms(100));
(&mut delay).await;
(&mut sleep).await;
assert_elapsed!(now, 100);
delay.reset(now + ms(110));
delay.await;
sleep.reset(now + ms(110));
sleep.await;
assert_elapsed!(now, 110);
}
#[tokio::test]
async fn reset_delay_to_past() {
async fn reset_sleep_to_past() {
time::pause();
let now = Instant::now();
let mut delay = task::spawn(time::sleep_until(now + ms(100)));
assert_pending!(delay.poll());
let mut sleep = task::spawn(time::sleep_until(now + ms(100)));
assert_pending!(sleep.poll());
time::sleep(ms(50)).await;
assert!(!delay.is_woken());
assert!(!sleep.is_woken());
delay.reset(now + ms(40));
sleep.reset(now + ms(40));
assert!(delay.is_woken());
assert!(sleep.is_woken());
assert_ready!(delay.poll());
assert_ready!(sleep.poll());
}
#[test]
#[should_panic]
fn creating_delay_outside_of_context() {
fn creating_sleep_outside_of_context() {
let now = Instant::now();
// This creates a delay outside of the context of a mock timer. This tests