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
17/// The [`FutureExt`] trait is a trait that provides a more ergonomic way to
18/// extend futures with additional functionality. Similar to the `IteratorExt`
19/// trait from the `itertools` crate, but for futures.
20pub trait FutureExt {
21 /// Attach a timeout to the future.
22 ///
23 /// This is a convenience method that wraps the [`tokio::time::timeout`]
24 /// function. The future will automatically cancel after the timeout has
25 /// elapsed. This is equivalent to calling
26 /// `with_timeout_at(tokio::time::Instant::now() + duration)`.
27 fn with_timeout(self, duration: tokio::time::Duration) -> tokio::time::Timeout<Self>
28 where
29 Self: Sized;
30
31 /// Attach a timeout to the future.
32 ///
33 /// This is a convenience method that wraps the [`tokio::time::timeout_at`]
34 /// function. The future will automatically cancel after the timeout has
35 /// elapsed. Unlike the `with_timeout` method, this method allows you to
36 /// specify a deadline instead of a duration.
37 fn with_timeout_at(self, deadline: tokio::time::Instant) -> tokio::time::Timeout<Self>
38 where
39 Self: Sized;
40}
41
42impl<F: std::future::Future> FutureExt for F {
43 fn with_timeout(self, duration: tokio::time::Duration) -> tokio::time::Timeout<Self> {
44 tokio::time::timeout(duration, self)
45 }
46
47 fn with_timeout_at(self, deadline: tokio::time::Instant) -> tokio::time::Timeout<Self> {
48 tokio::time::timeout_at(deadline, self)
49 }
50}
51
52/// Changelogs generated by [scuffle_changelog]
53#[cfg(feature = "docs")]
54#[scuffle_changelog::changelog]
55pub mod changelog {}