scuffle_future_ext/
lib.rs

1//! A crate that extends the `Future` trait with additional methods.
2#![cfg_attr(feature = "docs", doc = "\n\nSee the [changelog][changelog] for a full release history.")]
3#![cfg_attr(feature = "docs", doc = "## Feature flags")]
4#![cfg_attr(feature = "docs", doc = document_features::document_features!())]
5//! ## License
6//!
7//! This project is licensed under the MIT or Apache-2.0 license.
8//! You can choose between one of them if you use this work.
9//!
10//! `SPDX-License-Identifier: MIT OR Apache-2.0`
11#![cfg_attr(all(coverage_nightly, test), feature(coverage_attribute))]
12#![cfg_attr(docsrs, feature(doc_auto_cfg))]
13#![deny(missing_docs)]
14#![deny(unsafe_code)]
15#![deny(unreachable_pub)]
16#![deny(clippy::mod_module_files)]
17
18/// The [`FutureExt`] trait is a trait that provides a more ergonomic way to
19/// extend futures with additional functionality. Similar to the `IteratorExt`
20/// trait from the `itertools` crate, but for futures.
21pub trait FutureExt {
22    /// Attach a timeout to the future.
23    ///
24    /// This is a convenience method that wraps the [`tokio::time::timeout`]
25    /// function. The future will automatically cancel after the timeout has
26    /// elapsed. This is equivalent to calling
27    /// `with_timeout_at(tokio::time::Instant::now() + duration)`.
28    fn with_timeout(self, duration: tokio::time::Duration) -> tokio::time::Timeout<Self>
29    where
30        Self: Sized;
31
32    /// Attach a timeout to the future.
33    ///
34    /// This is a convenience method that wraps the [`tokio::time::timeout_at`]
35    /// function. The future will automatically cancel after the timeout has
36    /// elapsed. Unlike the `with_timeout` method, this method allows you to
37    /// specify a deadline instead of a duration.
38    fn with_timeout_at(self, deadline: tokio::time::Instant) -> tokio::time::Timeout<Self>
39    where
40        Self: Sized;
41}
42
43impl<F: std::future::Future> FutureExt for F {
44    fn with_timeout(self, duration: tokio::time::Duration) -> tokio::time::Timeout<Self> {
45        tokio::time::timeout(duration, self)
46    }
47
48    fn with_timeout_at(self, deadline: tokio::time::Instant) -> tokio::time::Timeout<Self> {
49        tokio::time::timeout_at(deadline, self)
50    }
51}
52
53/// Changelogs generated by [scuffle_changelog]
54#[cfg(feature = "docs")]
55#[scuffle_changelog::changelog]
56pub mod changelog {}