Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

time: add Future::timeout method via FutureExt #6276

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions tokio-util/src/time/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
//!
//! This type must be used from within the context of the `Runtime`.

use futures_core::Future;
use std::time::Duration;
use tokio::time::Timeout;

mod wheel;

Expand All @@ -17,6 +19,34 @@ pub mod delay_queue;
#[doc(inline)]
pub use delay_queue::DelayQueue;

/// A trait which contains a variety of convenient adapters and utilities for `Future`s.
pub trait FutureExt: Future {
/// A wrapper around [`tokio::time::timeout`], with the advantage that it is easier to write
/// fluent call chains.
///
/// # Examples
///
/// ```rust
/// use tokio::{sync::oneshot, time::Duration};
/// use tokio_util::time::FutureExt;
///
/// # async fn dox() {
/// let (tx, rx) = oneshot::channel::<()>();
///
/// let res = rx.timeout(Duration::from_millis(10)).await;
/// assert!(res.is_err());
/// # }
/// ```
fn timeout(self, timeout: Duration) -> Timeout<Self>
where
Self: Sized,
{
tokio::time::timeout(timeout, self)
}
}

impl<T: Future + ?Sized> FutureExt for T {}

// ===== Internal utils =====

enum Round {
Expand Down
Loading