scuffle_future_ext/lib.rs
1/// The [`FutureExt`] trait is a trait that provides a more ergonomic way to
2/// extend futures with additional functionality. Similar to the `IteratorExt`
3/// trait from the `itertools` crate, but for futures.
4pub trait FutureExt {
5 /// Attach a timeout to the future.
6 ///
7 /// This is a convenience method that wraps the [`tokio::time::timeout`]
8 /// function. The future will automatically cancel after the timeout has
9 /// elapsed. This is equivalent to calling
10 /// `with_timeout_at(tokio::time::Instant::now() + duration)`.
11 fn with_timeout(self, duration: tokio::time::Duration) -> tokio::time::Timeout<Self>
12 where
13 Self: Sized;
14
15 /// Attach a timeout to the future.
16 ///
17 /// This is a convenience method that wraps the [`tokio::time::timeout_at`]
18 /// function. The future will automatically cancel after the timeout has
19 /// elapsed. Unlike the `with_timeout` method, this method allows you to
20 /// specify a deadline instead of a duration.
21 fn with_timeout_at(self, deadline: tokio::time::Instant) -> tokio::time::Timeout<Self>
22 where
23 Self: Sized;
24}
25
26impl<F: std::future::Future> FutureExt for F {
27 fn with_timeout(self, duration: tokio::time::Duration) -> tokio::time::Timeout<Self> {
28 tokio::time::timeout(duration, self)
29 }
30
31 fn with_timeout_at(self, deadline: tokio::time::Instant) -> tokio::time::Timeout<Self> {
32 tokio::time::timeout_at(deadline, self)
33 }
34}