futures_util/future/
join_all.rs1use 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_attr(target_os = "none", cfg(target_has_atomic = "ptr"))]
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    unsafe { slice.get_unchecked_mut() }.iter_mut().map(|t| unsafe { Pin::new_unchecked(t) })
23}
24
25#[must_use = "futures do nothing unless you `.await` or poll them"]
26pub struct JoinAll<F>
28where
29    F: Future,
30{
31    kind: JoinAllKind<F>,
32}
33
34#[cfg_attr(target_os = "none", cfg(target_has_atomic = "ptr"))]
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_attr(target_os = "none", cfg(target_has_atomic = "ptr"))]
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 } => {
58                f.debug_struct("JoinAll").field("elems", elems).finish()
59            }
60            #[cfg_attr(target_os = "none", cfg(target_has_atomic = "ptr"))]
61            JoinAllKind::Big { ref fut, .. } => fmt::Debug::fmt(fut, f),
62        }
63    }
64}
65
66pub fn join_all<I>(iter: I) -> JoinAll<I::Item>
103where
104    I: IntoIterator,
105    I::Item: Future,
106{
107    let iter = iter.into_iter();
108
109    #[cfg(target_os = "none")]
110    #[cfg_attr(target_os = "none", cfg(not(target_has_atomic = "ptr")))]
111    {
112        let kind =
113            JoinAllKind::Small { elems: iter.map(MaybeDone::Future).collect::<Box<[_]>>().into() };
114
115        assert_future::<Vec<<I::Item as Future>::Output>, _>(JoinAll { kind })
116    }
117
118    #[cfg_attr(target_os = "none", cfg(target_has_atomic = "ptr"))]
119    {
120        let kind = match iter.size_hint().1 {
121            Some(max) if max <= SMALL => JoinAllKind::Small {
122                elems: iter.map(MaybeDone::Future).collect::<Box<[_]>>().into(),
123            },
124            _ => JoinAllKind::Big { fut: iter.collect::<FuturesOrdered<_>>().collect() },
125        };
126
127        assert_future::<Vec<<I::Item as Future>::Output>, _>(JoinAll { kind })
128    }
129}
130
131impl<F> Future for JoinAll<F>
132where
133    F: Future,
134{
135    type Output = Vec<F::Output>;
136
137    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
138        match &mut self.kind {
139            JoinAllKind::Small { elems } => {
140                let mut all_done = true;
141
142                for elem in iter_pin_mut(elems.as_mut()) {
143                    if elem.poll(cx).is_pending() {
144                        all_done = false;
145                    }
146                }
147
148                if all_done {
149                    let mut elems = mem::replace(elems, Box::pin([]));
150                    let result =
151                        iter_pin_mut(elems.as_mut()).map(|e| e.take_output().unwrap()).collect();
152                    Poll::Ready(result)
153                } else {
154                    Poll::Pending
155                }
156            }
157            #[cfg_attr(target_os = "none", cfg(target_has_atomic = "ptr"))]
158            JoinAllKind::Big { fut } => Pin::new(fut).poll(cx),
159        }
160    }
161}
162
163impl<F: Future> FromIterator<F> for JoinAll<F> {
164    fn from_iter<T: IntoIterator<Item = F>>(iter: T) -> Self {
165        join_all(iter)
166    }
167}