futures_util/future/
select_all.rsuse super::assert_future;
use crate::future::FutureExt;
use alloc::vec::Vec;
use core::iter::FromIterator;
use core::mem;
use core::pin::Pin;
use futures_core::future::Future;
use futures_core::task::{Context, Poll};
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct SelectAll<Fut> {
inner: Vec<Fut>,
}
impl<Fut: Unpin> Unpin for SelectAll<Fut> {}
pub fn select_all<I>(iter: I) -> SelectAll<I::Item>
where
I: IntoIterator,
I::Item: Future + Unpin,
{
let ret = SelectAll { inner: iter.into_iter().collect() };
assert!(!ret.inner.is_empty());
assert_future::<(<I::Item as Future>::Output, usize, Vec<I::Item>), _>(ret)
}
impl<Fut> SelectAll<Fut> {
pub fn into_inner(self) -> Vec<Fut> {
self.inner
}
}
impl<Fut: Future + Unpin> Future for SelectAll<Fut> {
type Output = (Fut::Output, usize, Vec<Fut>);
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let item = self.inner.iter_mut().enumerate().find_map(|(i, f)| match f.poll_unpin(cx) {
Poll::Pending => None,
Poll::Ready(e) => Some((i, e)),
});
match item {
Some((idx, res)) => {
#[allow(clippy::let_underscore_future)]
let _ = self.inner.swap_remove(idx);
let rest = mem::take(&mut self.inner);
Poll::Ready((res, idx, rest))
}
None => Poll::Pending,
}
}
}
impl<Fut: Future + Unpin> FromIterator<Fut> for SelectAll<Fut> {
fn from_iter<T: IntoIterator<Item = Fut>>(iter: T) -> Self {
select_all(iter)
}
}