futures_util/future/
flatten.rs

1use core::fmt;
2
3use futures_core::{Future, IntoFuture, Poll};
4use futures_core::task;
5
6use super::chain::Chain;
7
8/// Future for the `flatten` combinator.
9///
10/// This combinator turns a `Future`-of-a-`Future` into a single `Future`.
11///
12/// This is created by the `Future::flatten` method.
13#[must_use = "futures do nothing unless polled"]
14pub struct Flatten<A> where A: Future, A::Item: IntoFuture {
15    state: Chain<A, <A::Item as IntoFuture>::Future, ()>,
16}
17
18impl<A> fmt::Debug for Flatten<A>
19    where A: Future + fmt::Debug,
20          A::Item: IntoFuture,
21          <<A as Future>::Item as IntoFuture>::Future: fmt::Debug,
22{
23    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
24        fmt.debug_struct("Flatten")
25            .field("state", &self.state)
26            .finish()
27    }
28}
29
30pub fn new<A>(future: A) -> Flatten<A>
31    where A: Future,
32          A::Item: IntoFuture,
33{
34    Flatten {
35        state: Chain::new(future, ()),
36    }
37}
38
39impl<A> Future for Flatten<A>
40    where A: Future,
41          A::Item: IntoFuture,
42          <<A as Future>::Item as IntoFuture>::Error: From<<A as Future>::Error>
43{
44    type Item = <<A as Future>::Item as IntoFuture>::Item;
45    type Error = <<A as Future>::Item as IntoFuture>::Error;
46
47    fn poll(&mut self, cx: &mut task::Context) -> Poll<Self::Item, Self::Error> {
48        self.state.poll(cx, |a, ()| {
49            let future = a?.into_future();
50            Ok(Err(future))
51        })
52    }
53}