|
| 1 | +//! Definition of the `TryxJoinAll` adapter, waiting for all of a list of |
| 2 | +//! futures to finish with either success or error. |
| 3 | +
|
| 4 | +use crate::{ |
| 5 | + stream::{TryStreamExt, TryxCollect}, |
| 6 | + support::assert_future, |
| 7 | +}; |
| 8 | +use alloc::{boxed::Box, vec::Vec}; |
| 9 | +use core::{ |
| 10 | + fmt, |
| 11 | + future::Future, |
| 12 | + iter::FromIterator, |
| 13 | + mem, |
| 14 | + pin::Pin, |
| 15 | + task::{Context, Poll}, |
| 16 | +}; |
| 17 | +use futures_core::future::TryFuture; |
| 18 | +use futures_util::{ |
| 19 | + future::{IntoFuture, MaybeDone, TryFutureExt}, |
| 20 | + stream::FuturesOrdered, |
| 21 | +}; |
| 22 | + |
| 23 | +#[cfg(not(futures_no_atomic_cas))] |
| 24 | +pub(crate) const SMALL: usize = 30; |
| 25 | + |
| 26 | +/// Future for the [`tryx_join_all`] function. |
| 27 | +#[must_use = "futures do nothing unless you `.await` or poll them"] |
| 28 | +pub struct TryxJoinAll<F> |
| 29 | +where |
| 30 | + F: TryFuture, |
| 31 | +{ |
| 32 | + kind: TryxJoinAllKind<F>, |
| 33 | +} |
| 34 | + |
| 35 | +enum TryxJoinAllKind<F> |
| 36 | +where |
| 37 | + F: TryFuture, |
| 38 | +{ |
| 39 | + Small { |
| 40 | + elems: Pin<Box<[MaybeDone<IntoFuture<F>>]>>, |
| 41 | + }, |
| 42 | + #[cfg(not(futures_no_atomic_cas))] |
| 43 | + Big { |
| 44 | + // The use of FuturesOrdered here ensures that in case of errors, the first future listed in |
| 45 | + // the iterator that errors out will be returned. |
| 46 | + fut: TryxCollect<FuturesOrdered<IntoFuture<F>>, Vec<F::Ok>>, |
| 47 | + }, |
| 48 | +} |
| 49 | + |
| 50 | +impl<F> fmt::Debug for TryxJoinAll<F> |
| 51 | +where |
| 52 | + F: TryFuture + fmt::Debug, |
| 53 | + F::Ok: fmt::Debug, |
| 54 | + F::Error: fmt::Debug, |
| 55 | + F::Output: fmt::Debug, |
| 56 | +{ |
| 57 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 58 | + match self.kind { |
| 59 | + TryxJoinAllKind::Small { ref elems } => { |
| 60 | + f.debug_struct("TryxJoinAll").field("elems", elems).finish() |
| 61 | + } |
| 62 | + #[cfg(not(futures_no_atomic_cas))] |
| 63 | + TryxJoinAllKind::Big { ref fut, .. } => fmt::Debug::fmt(fut, f), |
| 64 | + } |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +/// Creates a future which represents either a collection of the results of the futures given or an |
| 69 | +/// error. |
| 70 | +/// |
| 71 | +/// The returned future will drive execution for all of its underlying futures, collecting the |
| 72 | +/// results into a destination `Vec<T>` in the same order as they were provided. |
| 73 | +/// |
| 74 | +/// Unlike [`futures::future::try_join_all`], if any future returns an error then all other futures |
| 75 | +/// will **not** be canceled. Instead, all other futures will be run to completion. |
| 76 | +/// |
| 77 | +/// * If all futures complete successfully, then the returned future will succeed with a |
| 78 | +/// `Vec` of all the successful results. |
| 79 | +/// * If one or more futures fail, then the returned future will error out with the error |
| 80 | +/// for the first future listed that failed. |
| 81 | +/// |
| 82 | +/// This function is only available when the `std` or `alloc` feature of this library is activated, |
| 83 | +/// and it is activated by default. |
| 84 | +/// |
| 85 | +/// # Why use `tryx_join_all`? |
| 86 | +/// |
| 87 | +/// See the documentation for [`tryx_join`](crate::tryx_join) for a discussion of why you might |
| 88 | +/// want to use a `tryx_` adapter. |
| 89 | +/// |
| 90 | +/// # See Also |
| 91 | +/// |
| 92 | +/// `tryx_join_all` will switch to the more powerful [`FuturesOrdered`] for performance reasons if |
| 93 | +/// the number of futures is large. You may want to look into using it or its counterpart |
| 94 | +/// [`FuturesUnordered`][futures::stream::FuturesUnordered] directly. |
| 95 | +/// |
| 96 | +/// Some examples for additional functionality provided by these are: |
| 97 | +/// |
| 98 | +/// * Adding new futures to the set even after it has been started. |
| 99 | +/// |
| 100 | +/// * Only polling the specific futures that have been woken. In cases where you have a lot of |
| 101 | +/// futures this will result in much more efficient polling. |
| 102 | +/// |
| 103 | +/// # Examples |
| 104 | +/// |
| 105 | +/// ``` |
| 106 | +/// # futures::executor::block_on(async { |
| 107 | +/// use futures::future; |
| 108 | +/// use cancel_safe_futures::future::tryx_join_all; |
| 109 | +/// |
| 110 | +/// let futures = vec![ |
| 111 | +/// future::ok::<u32, u32>(1), |
| 112 | +/// future::ok::<u32, u32>(2), |
| 113 | +/// future::ok::<u32, u32>(3), |
| 114 | +/// ]; |
| 115 | +/// |
| 116 | +/// assert_eq!(tryx_join_all(futures).await, Ok(vec![1, 2, 3])); |
| 117 | +/// |
| 118 | +/// let futures = vec![ |
| 119 | +/// future::ok::<u32, u32>(1), |
| 120 | +/// future::err::<u32, u32>(2), |
| 121 | +/// future::ok::<u32, u32>(3), |
| 122 | +/// ]; |
| 123 | +/// |
| 124 | +/// assert_eq!(tryx_join_all(futures).await, Err(2)); |
| 125 | +/// # }); |
| 126 | +/// ``` |
| 127 | +pub fn tryx_join_all<I>(iter: I) -> TryxJoinAll<I::Item> |
| 128 | +where |
| 129 | + I: IntoIterator, |
| 130 | + I::Item: TryFuture, |
| 131 | +{ |
| 132 | + let iter = iter.into_iter().map(TryFutureExt::into_future); |
| 133 | + |
| 134 | + #[cfg(futures_no_atomic_cas)] |
| 135 | + { |
| 136 | + let kind = TryxJoinAllKind::Small { |
| 137 | + elems: iter.map(MaybeDone::Future).collect::<Box<[_]>>().into(), |
| 138 | + }; |
| 139 | + |
| 140 | + assert_future::<Result<Vec<<I::Item as TryFuture>::Ok>, <I::Item as TryFuture>::Error>, _>( |
| 141 | + TryxJoinAll { kind }, |
| 142 | + ) |
| 143 | + } |
| 144 | + |
| 145 | + #[cfg(not(futures_no_atomic_cas))] |
| 146 | + { |
| 147 | + let kind = match iter.size_hint().1 { |
| 148 | + Some(max) if max <= SMALL => TryxJoinAllKind::Small { |
| 149 | + elems: iter.map(MaybeDone::Future).collect::<Box<[_]>>().into(), |
| 150 | + }, |
| 151 | + _ => TryxJoinAllKind::Big { |
| 152 | + fut: iter.collect::<FuturesOrdered<_>>().tryx_collect(), |
| 153 | + }, |
| 154 | + }; |
| 155 | + |
| 156 | + assert_future::<Result<Vec<<I::Item as TryFuture>::Ok>, <I::Item as TryFuture>::Error>, _>( |
| 157 | + TryxJoinAll { kind }, |
| 158 | + ) |
| 159 | + } |
| 160 | +} |
| 161 | + |
| 162 | +impl<F> Future for TryxJoinAll<F> |
| 163 | +where |
| 164 | + F: TryFuture, |
| 165 | +{ |
| 166 | + type Output = Result<Vec<F::Ok>, F::Error>; |
| 167 | + |
| 168 | + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { |
| 169 | + enum FinalState { |
| 170 | + Pending, |
| 171 | + AllDone, |
| 172 | + } |
| 173 | + |
| 174 | + match &mut self.kind { |
| 175 | + TryxJoinAllKind::Small { elems } => { |
| 176 | + let mut state = FinalState::AllDone; |
| 177 | + |
| 178 | + for elem in iter_pin_mut(elems.as_mut()) { |
| 179 | + match elem.poll(cx) { |
| 180 | + Poll::Pending => state = FinalState::Pending, |
| 181 | + Poll::Ready(()) => {} |
| 182 | + } |
| 183 | + } |
| 184 | + |
| 185 | + match state { |
| 186 | + FinalState::Pending => Poll::Pending, |
| 187 | + FinalState::AllDone => { |
| 188 | + let mut elems = mem::replace(elems, Box::pin([])); |
| 189 | + let results: Result<Vec<_>, _> = iter_pin_mut(elems.as_mut()) |
| 190 | + .map(|e| e.take_output().unwrap()) |
| 191 | + .collect(); |
| 192 | + Poll::Ready(results) |
| 193 | + } |
| 194 | + } |
| 195 | + } |
| 196 | + #[cfg(not(futures_no_atomic_cas))] |
| 197 | + TryxJoinAllKind::Big { fut } => Pin::new(fut).poll(cx), |
| 198 | + } |
| 199 | + } |
| 200 | +} |
| 201 | + |
| 202 | +impl<F> FromIterator<F> for TryxJoinAll<F> |
| 203 | +where |
| 204 | + F: TryFuture, |
| 205 | +{ |
| 206 | + fn from_iter<T: IntoIterator<Item = F>>(iter: T) -> Self { |
| 207 | + tryx_join_all(iter) |
| 208 | + } |
| 209 | +} |
| 210 | + |
| 211 | +pub(crate) fn iter_pin_mut<T>(slice: Pin<&mut [T]>) -> impl Iterator<Item = Pin<&mut T>> { |
| 212 | + // Safety: `std` _could_ make this unsound if it were to decide Pin's |
| 213 | + // invariants aren't required to transmit through slices. Otherwise this has |
| 214 | + // the same safety as a normal field pin projection. |
| 215 | + unsafe { slice.get_unchecked_mut() } |
| 216 | + .iter_mut() |
| 217 | + .map(|t| unsafe { Pin::new_unchecked(t) }) |
| 218 | +} |
0 commit comments