Skip to main content

tuwunel_core/utils/future/
ext_ext.rs

1//! Extended external extensions to futures::FutureExt
2
3use std::time::{Duration, Instant};
4
5use futures::{
6	FutureExt, future,
7	future::{Select, lazy},
8};
9
10/// Adds a stop-future race and a completion timer to ordinary futures.
11///
12/// `until` hands back a selector over the receiver and a stopping future;
13/// `timed` hands back the receiver's output with how long it took.
14pub trait ExtExt<T>
15where
16	Self: Future<Output = T> + Send,
17{
18	/// Races the receiver against a unit-output stopping future.
19	///
20	/// `f` constructs the stopping future when the selector is created. The
21	/// returned [`Select`] preserves whichever future has not completed.
22	fn until<A, B, F>(self, f: F) -> Select<A, B>
23	where
24		Self: Sized,
25		F: FnOnce() -> B,
26		A: Future<Output = T> + From<Self> + Send + Unpin,
27		B: Future<Output = ()> + Send + Unpin;
28
29	/// Resolves to the receiver's output and how long it took.
30	///
31	/// The clock starts when the returned future is first polled, so time spent
32	/// before it is awaited does not count.
33	fn timed(self) -> impl Future<Output = (T, Duration)> + Send
34	where
35		Self: Sized;
36}
37
38impl<T, Fut> ExtExt<T> for Fut
39where
40	Fut: Future<Output = T> + Send,
41{
42	#[inline]
43	fn until<A, B, F>(self, f: F) -> Select<A, B>
44	where
45		Self: Sized,
46		F: FnOnce() -> B,
47		A: Future<Output = T> + From<Self> + Send + Unpin,
48		B: Future<Output = ()> + Send + Unpin,
49	{
50		future::select(self.into(), f())
51	}
52
53	#[inline]
54	fn timed(self) -> impl Future<Output = (T, Duration)> + Send
55	where
56		Self: Sized,
57	{
58		lazy(|_| Instant::now())
59			.then(move |started| self.map(move |output| (output, started.elapsed())))
60	}
61}