1 //! Definition of the `JoinAll` combinator, waiting for all of a list of futures
2 //! to finish.
3 
4 use core::fmt;
5 use core::future::Future;
6 use core::iter::FromIterator;
7 use core::mem;
8 use core::pin::Pin;
9 use core::task::{Context, Poll};
10 use alloc::boxed::Box;
11 use alloc::vec::Vec;
12 
13 use super::MaybeDone;
14 
iter_pin_mut<T>(slice: Pin<&mut [T]>) -> impl Iterator<Item = Pin<&mut T>>15 fn iter_pin_mut<T>(slice: Pin<&mut [T]>) -> impl Iterator<Item = Pin<&mut T>> {
16     // Safety: `std` _could_ make this unsound if it were to decide Pin's
17     // invariants aren't required to transmit through slices. Otherwise this has
18     // the same safety as a normal field pin projection.
19     unsafe { slice.get_unchecked_mut() }
20         .iter_mut()
21         .map(|t| unsafe { Pin::new_unchecked(t) })
22 }
23 
24 /// Future for the [`join_all`] function.
25 #[must_use = "futures do nothing unless you `.await` or poll them"]
26 pub struct JoinAll<F>
27 where
28     F: Future,
29 {
30     elems: Pin<Box<[MaybeDone<F>]>>,
31 }
32 
33 impl<F> fmt::Debug for JoinAll<F>
34 where
35     F: Future + fmt::Debug,
36     F::Output: fmt::Debug,
37 {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result38     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39         f.debug_struct("JoinAll")
40             .field("elems", &self.elems)
41             .finish()
42     }
43 }
44 
45 /// Creates a future which represents a collection of the outputs of the futures
46 /// given.
47 ///
48 /// The returned future will drive execution for all of its underlying futures,
49 /// collecting the results into a destination `Vec<T>` in the same order as they
50 /// were provided.
51 ///
52 /// This function is only available when the `std` or `alloc` feature of this
53 /// library is activated, and it is activated by default.
54 ///
55 /// # See Also
56 ///
57 /// This is purposefully a very simple API for basic use-cases. In a lot of
58 /// cases you will want to use the more powerful
59 /// [`FuturesOrdered`][crate::stream::FuturesOrdered] APIs, or, if order does
60 /// not matter, [`FuturesUnordered`][crate::stream::FuturesUnordered].
61 ///
62 /// Some examples for additional functionality provided by these are:
63 ///
64 ///  * Adding new futures to the set even after it has been started.
65 ///
66 ///  * Only polling the specific futures that have been woken. In cases where
67 ///    you have a lot of futures this will result in much more efficient polling.
68 ///
69 /// # Examples
70 ///
71 /// ```
72 /// # futures::executor::block_on(async {
73 /// use futures::future::join_all;
74 ///
75 /// async fn foo(i: u32) -> u32 { i }
76 ///
77 /// let futures = vec![foo(1), foo(2), foo(3)];
78 ///
79 /// assert_eq!(join_all(futures).await, [1, 2, 3]);
80 /// # });
81 /// ```
join_all<I>(i: I) -> JoinAll<I::Item> where I: IntoIterator, I::Item: Future,82 pub fn join_all<I>(i: I) -> JoinAll<I::Item>
83 where
84     I: IntoIterator,
85     I::Item: Future,
86 {
87     let elems: Box<[_]> = i.into_iter().map(MaybeDone::Future).collect();
88     JoinAll { elems: elems.into() }
89 }
90 
91 impl<F> Future for JoinAll<F>
92 where
93     F: Future,
94 {
95     type Output = Vec<F::Output>;
96 
poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>97     fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
98         let mut all_done = true;
99 
100         for elem in iter_pin_mut(self.elems.as_mut()) {
101             if elem.poll(cx).is_pending() {
102                 all_done = false;
103             }
104         }
105 
106         if all_done {
107             let mut elems = mem::replace(&mut self.elems, Box::pin([]));
108             let result = iter_pin_mut(elems.as_mut())
109                 .map(|e| e.take_output().unwrap())
110                 .collect();
111             Poll::Ready(result)
112         } else {
113             Poll::Pending
114         }
115     }
116 }
117 
118 impl<F: Future> FromIterator<F> for JoinAll<F> {
from_iter<T: IntoIterator<Item = F>>(iter: T) -> Self119     fn from_iter<T: IntoIterator<Item = F>>(iter: T) -> Self {
120         join_all(iter)
121     }
122 }
123