1//! Definition of the `JoinAll` combinator, waiting for all of a list of futures
2//! to finish.
3
4use alloc::boxed::Box;
5use alloc::vec::Vec;
6use core::fmt;
7use core::future::Future;
8use core::iter::FromIterator;
9use core::mem;
10use core::pin::Pin;
11use core::task::{Context, Poll};
12
13use super::{assert_future, MaybeDone};
14
15#[cfg(not(futures_no_atomic_cas))]
16use crate::stream::{Collect, FuturesOrdered, StreamExt};
17
18pub(crate) fn iter_pin_mut<T>(slice: Pin<&mut [T]>) -> impl Iterator<Item = Pin<&mut T>> {
19 // Safety: `std` _could_ make this unsound if it were to decide Pin's
20 // invariants aren't required to transmit through slices. Otherwise this has
21 // the same safety as a normal field pin projection.
22 unsafe { slice.get_unchecked_mut() }.iter_mut().map(|t: &mut T| unsafe { Pin::new_unchecked(pointer:t) })
23}
24
25#[must_use = "futures do nothing unless you `.await` or poll them"]
26/// Future for the [`join_all`] function.
27pub struct JoinAll<F>
28where
29 F: Future,
30{
31 kind: JoinAllKind<F>,
32}
33
34#[cfg(not(futures_no_atomic_cas))]
35pub(crate) const SMALL: usize = 30;
36
37enum JoinAllKind<F>
38where
39 F: Future,
40{
41 Small {
42 elems: Pin<Box<[MaybeDone<F>]>>,
43 },
44 #[cfg(not(futures_no_atomic_cas))]
45 Big {
46 fut: Collect<FuturesOrdered<F>, Vec<F::Output>>,
47 },
48}
49
50impl<F> fmt::Debug for JoinAll<F>
51where
52 F: Future + fmt::Debug,
53 F::Output: fmt::Debug,
54{
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 match self.kind {
57 JoinAllKind::Small { ref elems: &Pin]>> } => {
58 f.debug_struct("JoinAll").field(name:"elems", value:elems).finish()
59 }
60 #[cfg(not(futures_no_atomic_cas))]
61 JoinAllKind::Big { ref fut: &Collect, …>, .. } => fmt::Debug::fmt(self:fut, f),
62 }
63 }
64}
65
66/// Creates a future which represents a collection of the outputs of the futures
67/// given.
68///
69/// The returned future will drive execution for all of its underlying futures,
70/// collecting the results into a destination `Vec<T>` in the same order as they
71/// were provided.
72///
73/// This function is only available when the `std` or `alloc` feature of this
74/// library is activated, and it is activated by default.
75///
76/// # See Also
77///
78/// `join_all` will switch to the more powerful [`FuturesOrdered`] for performance
79/// reasons if the number of futures is large. You may want to look into using it or
80/// it's counterpart [`FuturesUnordered`][crate::stream::FuturesUnordered] directly.
81///
82/// Some examples for additional functionality provided by these are:
83///
84/// * Adding new futures to the set even after it has been started.
85///
86/// * Only polling the specific futures that have been woken. In cases where
87/// you have a lot of futures this will result in much more efficient polling.
88///
89/// # Examples
90///
91/// ```
92/// # futures::executor::block_on(async {
93/// use futures::future::join_all;
94///
95/// async fn foo(i: u32) -> u32 { i }
96///
97/// let futures = vec![foo(1), foo(2), foo(3)];
98///
99/// assert_eq!(join_all(futures).await, [1, 2, 3]);
100/// # });
101/// ```
102pub fn join_all<I>(iter: I) -> JoinAll<I::Item>
103where
104 I: IntoIterator,
105 I::Item: Future,
106{
107 let iter: ::IntoIter = iter.into_iter();
108
109 #[cfg(futures_no_atomic_cas)]
110 {
111 let kind =
112 JoinAllKind::Small { elems: iter.map(MaybeDone::Future).collect::<Box<[_]>>().into() };
113
114 assert_future::<Vec<<I::Item as Future>::Output>, _>(JoinAll { kind })
115 }
116
117 #[cfg(not(futures_no_atomic_cas))]
118 {
119 let kind: JoinAllKind<::Item> = match iter.size_hint().1 {
120 Some(max: usize) if max <= SMALL => JoinAllKind::Small {
121 elems: iter.map(MaybeDone::Future).collect::<Box<[_]>>().into(),
122 },
123 _ => JoinAllKind::Big { fut: iter.collect::<FuturesOrdered<_>>().collect() },
124 };
125
126 assert_future::<Vec<<I::Item as Future>::Output>, _>(JoinAll { kind })
127 }
128}
129
130impl<F> Future for JoinAll<F>
131where
132 F: Future,
133{
134 type Output = Vec<F::Output>;
135
136 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
137 match &mut self.kind {
138 JoinAllKind::Small { elems } => {
139 let mut all_done = true;
140
141 for elem in iter_pin_mut(elems.as_mut()) {
142 if elem.poll(cx).is_pending() {
143 all_done = false;
144 }
145 }
146
147 if all_done {
148 let mut elems = mem::replace(elems, Box::pin([]));
149 let result =
150 iter_pin_mut(elems.as_mut()).map(|e| e.take_output().unwrap()).collect();
151 Poll::Ready(result)
152 } else {
153 Poll::Pending
154 }
155 }
156 #[cfg(not(futures_no_atomic_cas))]
157 JoinAllKind::Big { fut } => Pin::new(fut).poll(cx),
158 }
159 }
160}
161
162impl<F: Future> FromIterator<F> for JoinAll<F> {
163 fn from_iter<T: IntoIterator<Item = F>>(iter: T) -> Self {
164 join_all(iter)
165 }
166}
167