futures_util/future/
select_all.rs

1//! Definition of the `SelectAll`, finding the first future in a list that
2//! finishes.
3
4use std::mem;
5use std::prelude::v1::*;
6
7use futures_core::{Future, IntoFuture, Poll, Async};
8use futures_core::task;
9
10/// Future for the `select_all` combinator, waiting for one of any of a list of
11/// futures to complete.
12///
13/// This is created by the `select_all` function.
14#[derive(Debug)]
15#[must_use = "futures do nothing unless polled"]
16pub struct SelectAll<A> where A: Future {
17    inner: Vec<A>,
18}
19
20#[doc(hidden)]
21pub type SelectAllNext<A> = A;
22
23/// Creates a new future which will select over a list of futures.
24///
25/// The returned future will wait for any future within `iter` to be ready. Upon
26/// completion or failure the item resolved will be returned, along with the
27/// index of the future that was ready and the list of all the remaining
28/// futures.
29///
30/// # Panics
31///
32/// This function will panic if the iterator specified contains no items.
33pub fn select_all<I>(iter: I) -> SelectAll<<I::Item as IntoFuture>::Future>
34    where I: IntoIterator,
35          I::Item: IntoFuture,
36{
37    let ret = SelectAll {
38        inner: iter.into_iter()
39                   .map(|a| a.into_future())
40                   .collect(),
41    };
42    assert!(ret.inner.len() > 0);
43    ret
44}
45
46impl<A> Future for SelectAll<A>
47    where A: Future,
48{
49    type Item = (A::Item, usize, Vec<A>);
50    type Error = (A::Error, usize, Vec<A>);
51
52    fn poll(&mut self, cx: &mut task::Context) -> Poll<Self::Item, Self::Error> {
53        let item = self.inner.iter_mut().enumerate().filter_map(|(i, f)| {
54            match f.poll(cx) {
55                Ok(Async::Pending) => None,
56                Ok(Async::Ready(e)) => Some((i, Ok(e))),
57                Err(e) => Some((i, Err(e))),
58            }
59        }).next();
60        match item {
61            Some((idx, res)) => {
62                self.inner.swap_remove(idx);
63                let rest = mem::replace(&mut self.inner, Vec::new());
64                match res {
65                    Ok(e) => Ok(Async::Ready((e, idx, rest))),
66                    Err(e) => Err((e, idx, rest)),
67                }
68            }
69            None => Ok(Async::Pending),
70        }
71    }
72}