futures_util/future/
try_join_all.rs

1//! Definition of the `TryJoinAll` combinator, waiting for all of a list of
2//! futures to finish with either success or error.
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, join_all, IntoFuture, TryFuture, TryMaybeDone};
14
15#[cfg(not(futures_no_atomic_cas))]
16use crate::stream::{FuturesOrdered, TryCollect, TryStreamExt};
17use crate::TryFutureExt;
18
19enum FinalState<E = ()> {
20    Pending,
21    AllDone,
22    Error(E),
23}
24
25/// Future for the [`try_join_all`] function.
26#[must_use = "futures do nothing unless you `.await` or poll them"]
27pub struct TryJoinAll<F>
28where
29    F: TryFuture,
30{
31    kind: TryJoinAllKind<F>,
32}
33
34enum TryJoinAllKind<F>
35where
36    F: TryFuture,
37{
38    Small {
39        elems: Pin<Box<[TryMaybeDone<IntoFuture<F>>]>>,
40    },
41    #[cfg(not(futures_no_atomic_cas))]
42    Big {
43        fut: TryCollect<FuturesOrdered<IntoFuture<F>>, Vec<F::Ok>>,
44    },
45}
46
47impl<F> fmt::Debug for TryJoinAll<F>
48where
49    F: TryFuture + fmt::Debug,
50    F::Ok: fmt::Debug,
51    F::Error: fmt::Debug,
52    F::Output: fmt::Debug,
53{
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        match self.kind {
56            TryJoinAllKind::Small { ref elems } => {
57                f.debug_struct("TryJoinAll").field("elems", elems).finish()
58            }
59            #[cfg(not(futures_no_atomic_cas))]
60            TryJoinAllKind::Big { ref fut, .. } => fmt::Debug::fmt(fut, f),
61        }
62    }
63}
64
65/// Creates a future which represents either a collection of the results of the
66/// futures given or an error.
67///
68/// The returned future will drive execution for all of its underlying futures,
69/// collecting the results into a destination `Vec<T>` in the same order as they
70/// were provided.
71///
72/// If any future returns an error then all other futures will be canceled and
73/// an error will be returned immediately. If all futures complete successfully,
74/// however, then the returned future will succeed with a `Vec` of all the
75/// successful results.
76///
77/// This function is only available when the `std` or `alloc` feature of this
78/// library is activated, and it is activated by default.
79///
80/// # Examples
81///
82/// ```
83/// # futures::executor::block_on(async {
84/// use futures::future::{self, try_join_all};
85///
86/// let futures = vec![
87///     future::ok::<u32, u32>(1),
88///     future::ok::<u32, u32>(2),
89///     future::ok::<u32, u32>(3),
90/// ];
91///
92/// assert_eq!(try_join_all(futures).await, Ok(vec![1, 2, 3]));
93///
94/// let futures = vec![
95///     future::ok::<u32, u32>(1),
96///     future::err::<u32, u32>(2),
97///     future::ok::<u32, u32>(3),
98/// ];
99///
100/// assert_eq!(try_join_all(futures).await, Err(2));
101/// # });
102/// ```
103pub fn try_join_all<I>(iter: I) -> TryJoinAll<I::Item>
104where
105    I: IntoIterator,
106    I::Item: TryFuture,
107{
108    let iter = iter.into_iter().map(TryFutureExt::into_future);
109
110    #[cfg(futures_no_atomic_cas)]
111    {
112        let kind = TryJoinAllKind::Small {
113            elems: iter.map(TryMaybeDone::Future).collect::<Box<[_]>>().into(),
114        };
115
116        assert_future::<Result<Vec<<I::Item as TryFuture>::Ok>, <I::Item as TryFuture>::Error>, _>(
117            TryJoinAll { kind },
118        )
119    }
120
121    #[cfg(not(futures_no_atomic_cas))]
122    {
123        let kind = match iter.size_hint().1 {
124            Some(max) if max <= join_all::SMALL => TryJoinAllKind::Small {
125                elems: iter.map(TryMaybeDone::Future).collect::<Box<[_]>>().into(),
126            },
127            _ => TryJoinAllKind::Big { fut: iter.collect::<FuturesOrdered<_>>().try_collect() },
128        };
129
130        assert_future::<Result<Vec<<I::Item as TryFuture>::Ok>, <I::Item as TryFuture>::Error>, _>(
131            TryJoinAll { kind },
132        )
133    }
134}
135
136impl<F> Future for TryJoinAll<F>
137where
138    F: TryFuture,
139{
140    type Output = Result<Vec<F::Ok>, F::Error>;
141
142    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
143        match &mut self.kind {
144            TryJoinAllKind::Small { elems } => {
145                let mut state = FinalState::AllDone;
146
147                for elem in join_all::iter_pin_mut(elems.as_mut()) {
148                    match elem.try_poll(cx) {
149                        Poll::Pending => state = FinalState::Pending,
150                        Poll::Ready(Ok(())) => {}
151                        Poll::Ready(Err(e)) => {
152                            state = FinalState::Error(e);
153                            break;
154                        }
155                    }
156                }
157
158                match state {
159                    FinalState::Pending => Poll::Pending,
160                    FinalState::AllDone => {
161                        let mut elems = mem::replace(elems, Box::pin([]));
162                        let results = join_all::iter_pin_mut(elems.as_mut())
163                            .map(|e| e.take_output().unwrap())
164                            .collect();
165                        Poll::Ready(Ok(results))
166                    }
167                    FinalState::Error(e) => {
168                        let _ = mem::replace(elems, Box::pin([]));
169                        Poll::Ready(Err(e))
170                    }
171                }
172            }
173            #[cfg(not(futures_no_atomic_cas))]
174            TryJoinAllKind::Big { fut } => Pin::new(fut).poll(cx),
175        }
176    }
177}
178
179impl<F> FromIterator<F> for TryJoinAll<F>
180where
181    F: TryFuture,
182{
183    fn from_iter<T: IntoIterator<Item = F>>(iter: T) -> Self {
184        try_join_all(iter)
185    }
186}