futures_concurrency/future/
futures_ext.rs

1use crate::future::Join;
2use crate::future::Race;
3use core::future::IntoFuture;
4use futures_core::Future;
5
6use super::join::tuple::Join2;
7use super::race::tuple::Race2;
8use super::WaitUntil;
9
10/// An extension trait for the `Future` trait.
11pub trait FutureExt: Future {
12    /// Wait for both futures to complete.
13    fn join<S2>(self, other: S2) -> Join2<Self, S2::IntoFuture>
14    where
15        Self: Future + Sized,
16        S2: IntoFuture;
17
18    /// Wait for the first future to complete.
19    fn race<T, S2>(self, other: S2) -> Race2<T, Self, S2::IntoFuture>
20    where
21        Self: Future<Output = T> + Sized,
22        S2: IntoFuture<Output = T>;
23
24    /// Delay resolving the future until the given deadline.
25    ///
26    /// The underlying future will not be polled until the deadline has expired. In addition
27    /// to using a time source as a deadline, any future can be used as a
28    /// deadline too. When used in combination with a multi-consumer channel,
29    /// this method can be used to synchronize the start of multiple futures and streams.
30    ///
31    /// # Example
32    ///
33    /// ```
34    /// # #[cfg(miri)]fn main() {}
35    /// # #[cfg(not(miri))]
36    /// # fn main() {
37    /// use async_io::Timer;
38    /// use futures_concurrency::prelude::*;
39    /// use futures_lite::future::block_on;
40    /// use std::time::{Duration, Instant};
41    ///
42    /// block_on(async {
43    ///     let now = Instant::now();
44    ///     let duration = Duration::from_millis(100);
45    ///
46    ///     async { "meow" }
47    ///         .wait_until(Timer::after(duration))
48    ///         .await;
49    ///
50    ///     assert!(now.elapsed() >= duration);
51    /// });
52    /// # }
53    /// ```
54    fn wait_until<D>(self, deadline: D) -> WaitUntil<Self, D::IntoFuture>
55    where
56        Self: Sized,
57        D: IntoFuture,
58    {
59        WaitUntil::new(self, deadline.into_future())
60    }
61}
62
63impl<F1> FutureExt for F1
64where
65    F1: Future,
66{
67    fn join<F2>(self, other: F2) -> Join2<Self, F2::IntoFuture>
68    where
69        Self: Future + Sized,
70        F2: IntoFuture,
71    {
72        Join::join((self, other))
73    }
74
75    fn race<T, S2>(self, other: S2) -> Race2<T, Self, S2::IntoFuture>
76    where
77        Self: Future<Output = T> + Sized,
78        S2: IntoFuture<Output = T>,
79    {
80        Race::race((self, other))
81    }
82}