Skip to main content

ntex_util/future/
join.rs

1use std::{future::Future, mem, pin::Pin, task::Context, task::Poll};
2
3use crate::future::MaybeDone;
4
5/// Future for the `join` combinator, waiting for two futures to complete.
6pub fn join<A, B>(fut_a: A, fut_b: B) -> impl Future<Output = (A::Output, B::Output)>
7where
8    A: Future,
9    B: Future,
10{
11    Join {
12        fut_a: MaybeDone::pending(fut_a),
13        fut_b: MaybeDone::pending(fut_b),
14    }
15}
16
17pin_project_lite::pin_project! {
18    pub(crate) struct Join<A: Future, B: Future> {
19        #[pin]
20        fut_a: MaybeDone<A>,
21        #[pin]
22        fut_b: MaybeDone<B>,
23    }
24}
25
26impl<A, B> Future for Join<A, B>
27where
28    A: Future,
29    B: Future,
30{
31    type Output = (A::Output, B::Output);
32
33    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
34        let mut this = self.project();
35        let mut all_done = true;
36        all_done &= this.fut_a.as_mut().poll(cx).is_ready();
37        all_done &= this.fut_b.as_mut().poll(cx).is_ready();
38        if all_done {
39            Poll::Ready((
40                this.fut_a.take_output().unwrap(),
41                this.fut_b.take_output().unwrap(),
42            ))
43        } else {
44            Poll::Pending
45        }
46    }
47}
48
49/// Creates a future which represents a collection of the outputs of the futures
50/// given.
51pub fn join_all<I>(i: I) -> impl Future<Output = Vec<<I::Item as Future>::Output>>
52where
53    I: IntoIterator,
54    I::Item: Future,
55{
56    JoinAll {
57        elems: i
58            .into_iter()
59            .map(|f| MaybeDone::pending(Box::pin(f)))
60            .collect(),
61    }
62}
63
64// Each future is boxed, so elements are `Unpin` and need no slice pin projection.
65pub(crate) struct JoinAll<T: Future> {
66    elems: Box<[MaybeDone<Pin<Box<T>>>]>,
67}
68
69impl<T> Future for JoinAll<T>
70where
71    T: Future,
72{
73    type Output = Vec<T::Output>;
74
75    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
76        let this = self.get_mut();
77        let mut all_done = true;
78
79        for elem in &mut this.elems {
80            if Pin::new(elem).poll(cx).is_pending() {
81                all_done = false;
82            }
83        }
84        if all_done {
85            let result = mem::take(&mut this.elems)
86                .iter_mut()
87                .map(|e| Pin::new(e).take_output().unwrap())
88                .collect();
89            Poll::Ready(result)
90        } else {
91            Poll::Pending
92        }
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use std::future::ready;
99
100    use super::*;
101    use crate::time;
102
103    /// STATEMENT: Join helpers collect all outputs despite different completion times.
104    ///
105    /// HOW:
106    /// - Join an immediately ready value with a sleep and compare the output pair.
107    /// - Join two different-duration sleeps and check both outputs are collected.
108    #[ntex::test]
109    async fn join_tests() {
110        let res = join(ready(Ok::<_, ()>("test")), time::sleep(time::Millis(50))).await;
111        assert_eq!(res, (Ok("test"), ()));
112
113        let res = join_all([time::sleep(time::Millis(50)), time::sleep(time::Millis(60))]).await;
114        assert_eq!(res, vec![(), ()]);
115    }
116
117    /// STATEMENT: `join_all` pin-projects its boxed slice and returns every output in
118    /// input order without undefined behavior.
119    ///
120    /// HOW:
121    /// - Join three futures that stay pending for zero, one and two polls before
122    ///   returning a `String`.
123    /// - Poll with `Waker::noop` and check the first two polls are pending.
124    /// - Check the third poll returns the outputs in input order.
125    #[test]
126    fn miri_join_all_collects_outputs() {
127        let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
128        let futs = (0..3).map(|i| {
129            let mut pending = i;
130            std::future::poll_fn(move |_| {
131                if pending == 0 {
132                    Poll::Ready(i.to_string())
133                } else {
134                    pending -= 1;
135                    Poll::Pending
136                }
137            })
138        });
139        let mut fut = std::pin::pin!(join_all(futs));
140        assert!(fut.as_mut().poll(&mut cx).is_pending());
141        assert!(fut.as_mut().poll(&mut cx).is_pending());
142        assert_eq!(
143            fut.as_mut().poll(&mut cx),
144            Poll::Ready(vec!["0".to_string(), "1".to_string(), "2".to_string()])
145        );
146    }
147}