1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
use core::mem;
use {Poll, Async};
use future::Future;
use stream::Stream;
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct Concat<S>
where S: Stream,
{
stream: S,
extend: Inner<S::Item>,
}
pub fn new<S>(s: S) -> Concat<S>
where S: Stream,
S::Item: Extend<<<S as Stream>::Item as IntoIterator>::Item> + IntoIterator,
{
Concat {
stream: s,
extend: Inner::First,
}
}
impl<S> Future for Concat<S>
where S: Stream,
S::Item: Extend<<<S as Stream>::Item as IntoIterator>::Item> + IntoIterator,
{
type Item = S::Item;
type Error = S::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
loop {
match self.stream.poll() {
Ok(Async::Ready(Some(i))) => {
match self.extend {
Inner::First => {
self.extend = Inner::Extending(i);
},
Inner::Extending(ref mut e) => {
e.extend(i);
},
Inner::Done => unreachable!(),
}
},
Ok(Async::Ready(None)) => return Ok(Async::Ready(expect(self.extend.take()))),
Ok(Async::NotReady) => return Ok(Async::NotReady),
Err(e) => {
self.extend.take();
return Err(e)
}
}
}
}
}
#[derive(Debug)]
enum Inner<E> {
First,
Extending(E),
Done,
}
impl<E> Inner<E> {
fn take(&mut self) -> Option<E> {
match mem::replace(self, Inner::Done) {
Inner::Extending(e) => Some(e),
_ => None,
}
}
}
fn expect<T>(opt: Option<T>) -> T {
opt.expect("cannot poll Concat again")
}