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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
#![allow(non_snake_case)]
use core::mem;
use {Future, Poll, IntoFuture, Async};
macro_rules! generate {
($(
$(#[$doc:meta])*
($Join:ident, $new:ident, <A, $($B:ident),*>),
)*) => ($(
$(#[$doc])*
#[must_use = "futures do nothing unless polled"]
pub struct $Join<A, $($B),*>
where A: Future,
$($B: Future<Error=A::Error>),*
{
a: MaybeDone<A>,
$($B: MaybeDone<$B>,)*
}
pub fn $new<A, $($B),*>(a: A, $($B: $B),*) -> $Join<A, $($B),*>
where A: Future,
$($B: Future<Error=A::Error>),*
{
$Join {
a: MaybeDone::NotYet(a),
$($B: MaybeDone::NotYet($B)),*
}
}
impl<A, $($B),*> $Join<A, $($B),*>
where A: Future,
$($B: Future<Error=A::Error>),*
{
fn erase(&mut self) {
self.a = MaybeDone::Gone;
$(self.$B = MaybeDone::Gone;)*
}
}
impl<A, $($B),*> Future for $Join<A, $($B),*>
where A: Future,
$($B: Future<Error=A::Error>),*
{
type Item = (A::Item, $($B::Item),*);
type Error = A::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let mut all_done = match self.a.poll() {
Ok(done) => done,
Err(e) => {
self.erase();
return Err(e)
}
};
$(
all_done = match self.$B.poll() {
Ok(done) => all_done && done,
Err(e) => {
self.erase();
return Err(e)
}
};
)*
if all_done {
Ok(Async::Ready((self.a.take(), $(self.$B.take()),*)))
} else {
Ok(Async::NotReady)
}
}
}
impl<A, $($B),*> IntoFuture for (A, $($B),*)
where A: IntoFuture,
$(
$B: IntoFuture<Error=A::Error>
),*
{
type Future = $Join<A::Future, $($B::Future),*>;
type Item = (A::Item, $($B::Item),*);
type Error = A::Error;
fn into_future(self) -> Self::Future {
match self {
(a, $($B),+) => {
$new(
IntoFuture::into_future(a),
$(IntoFuture::into_future($B)),+
)
}
}
}
}
)*)
}
generate! {
(Join, new, <A, B>),
(Join3, new3, <A, B, C>),
(Join4, new4, <A, B, C, D>),
(Join5, new5, <A, B, C, D, E>),
}
enum MaybeDone<A: Future> {
NotYet(A),
Done(A::Item),
Gone,
}
impl<A: Future> MaybeDone<A> {
fn poll(&mut self) -> Result<bool, A::Error> {
let res = match *self {
MaybeDone::NotYet(ref mut a) => try!(a.poll()),
MaybeDone::Done(_) => return Ok(true),
MaybeDone::Gone => panic!("cannot poll Join twice"),
};
match res {
Async::Ready(res) => {
*self = MaybeDone::Done(res);
Ok(true)
}
Async::NotReady => Ok(false),
}
}
fn take(&mut self) -> A::Item {
match mem::replace(self, MaybeDone::Gone) {
MaybeDone::Done(a) => a,
_ => panic!(),
}
}
}