1 use {Async, Future, Poll};
2 use core::fmt;
3 use stream::Stream;
4
5 /// Future for the `flatten_stream` combinator, flattening a
6 /// future-of-a-stream to get just the result of the final stream as a stream.
7 ///
8 /// This is created by the `Future::flatten_stream` method.
9 #[must_use = "streams do nothing unless polled"]
10 pub struct FlattenStream<F>
11 where F: Future,
12 <F as Future>::Item: Stream<Error=F::Error>,
13 {
14 state: State<F>
15 }
16
17 impl<F> fmt::Debug for FlattenStream<F>
18 where F: Future + fmt::Debug,
19 <F as Future>::Item: Stream<Error=F::Error> + fmt::Debug,
20 {
fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result21 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
22 fmt.debug_struct("FlattenStream")
23 .field("state", &self.state)
24 .finish()
25 }
26 }
27
new<F>(f: F) -> FlattenStream<F> where F: Future, <F as Future>::Item: Stream<Error=F::Error>,28 pub fn new<F>(f: F) -> FlattenStream<F>
29 where F: Future,
30 <F as Future>::Item: Stream<Error=F::Error>,
31 {
32 FlattenStream {
33 state: State::Future(f)
34 }
35 }
36
37 #[derive(Debug)]
38 enum State<F>
39 where F: Future,
40 <F as Future>::Item: Stream<Error=F::Error>,
41 {
42 // future is not yet called or called and not ready
43 Future(F),
44 // future resolved to Stream
45 Stream(F::Item),
46 // EOF after future resolved to error
47 Eof,
48 // after EOF after future resolved to error
49 Done,
50 }
51
52 impl<F> Stream for FlattenStream<F>
53 where F: Future,
54 <F as Future>::Item: Stream<Error=F::Error>,
55 {
56 type Item = <F::Item as Stream>::Item;
57 type Error = <F::Item as Stream>::Error;
58
poll(&mut self) -> Poll<Option<Self::Item>, Self::Error>59 fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
60 loop {
61 let (next_state, ret_opt) = match self.state {
62 State::Future(ref mut f) => {
63 match f.poll() {
64 Ok(Async::NotReady) => {
65 // State is not changed, early return.
66 return Ok(Async::NotReady)
67 },
68 Ok(Async::Ready(stream)) => {
69 // Future resolved to stream.
70 // We do not return, but poll that
71 // stream in the next loop iteration.
72 (State::Stream(stream), None)
73 }
74 Err(e) => {
75 (State::Eof, Some(Err(e)))
76 }
77 }
78 }
79 State::Stream(ref mut s) => {
80 // Just forward call to the stream,
81 // do not track its state.
82 return s.poll();
83 }
84 State::Eof => {
85 (State::Done, Some(Ok(Async::Ready(None))))
86 }
87 State::Done => {
88 panic!("poll called after eof");
89 }
90 };
91
92 self.state = next_state;
93 if let Some(ret) = ret_opt {
94 return ret;
95 }
96 }
97 }
98 }
99
100