scuffle_future_ext/lib.rs
1//! A crate that extends the `Future` trait with additional methods.
2//!
3//! ## Status
4//!
5//! This crate is currently under development and is not yet stable.
6//!
7//! Unit tests are not yet fully implemented. Use at your own risk.
8//!
9//! ## License
10//!
11//! This project is licensed under the [MIT](./LICENSE.MIT) or [Apache-2.0](./LICENSE.Apache-2.0) license.
12//! You can choose between one of them if you use this work.
13//!
14//! `SPDX-License-Identifier: MIT OR Apache-2.0`
15#![deny(missing_docs)]
16#![deny(unsafe_code)]
17#![deny(unreachable_pub)]
18
19/// The [`FutureExt`] trait is a trait that provides a more ergonomic way to
20/// extend futures with additional functionality. Similar to the `IteratorExt`
21/// trait from the `itertools` crate, but for futures.
22pub trait FutureExt {
23 /// Attach a timeout to the future.
24 ///
25 /// This is a convenience method that wraps the [`tokio::time::timeout`]
26 /// function. The future will automatically cancel after the timeout has
27 /// elapsed. This is equivalent to calling
28 /// `with_timeout_at(tokio::time::Instant::now() + duration)`.
29 fn with_timeout(self, duration: tokio::time::Duration) -> tokio::time::Timeout<Self>
30 where
31 Self: Sized;
32
33 /// Attach a timeout to the future.
34 ///
35 /// This is a convenience method that wraps the [`tokio::time::timeout_at`]
36 /// function. The future will automatically cancel after the timeout has
37 /// elapsed. Unlike the `with_timeout` method, this method allows you to
38 /// specify a deadline instead of a duration.
39 fn with_timeout_at(self, deadline: tokio::time::Instant) -> tokio::time::Timeout<Self>
40 where
41 Self: Sized;
42}
43
44impl<F: std::future::Future> FutureExt for F {
45 fn with_timeout(self, duration: tokio::time::Duration) -> tokio::time::Timeout<Self> {
46 tokio::time::timeout(duration, self)
47 }
48
49 fn with_timeout_at(self, deadline: tokio::time::Instant) -> tokio::time::Timeout<Self> {
50 tokio::time::timeout_at(deadline, self)
51 }
52}