1 use {Future, Poll, Async};
2
3 /// Future for the `select` combinator, waiting for one of two futures to
4 /// complete.
5 ///
6 /// This is created by the `Future::select` method.
7 #[derive(Debug)]
8 #[must_use = "futures do nothing unless polled"]
9 pub struct Select<A, B> where A: Future, B: Future<Item=A::Item, Error=A::Error> {
10 inner: Option<(A, B)>,
11 }
12
13 /// Future yielded as the second result in a `Select` future.
14 ///
15 /// This sentinel future represents the completion of the second future to a
16 /// `select` which finished second.
17 #[derive(Debug)]
18 #[must_use = "futures do nothing unless polled"]
19 pub struct SelectNext<A, B> where A: Future, B: Future<Item=A::Item, Error=A::Error> {
20 inner: OneOf<A, B>,
21 }
22
23 #[derive(Debug)]
24 enum OneOf<A, B> where A: Future, B: Future {
25 A(A),
26 B(B),
27 }
28
new<A, B>(a: A, b: B) -> Select<A, B> where A: Future, B: Future<Item=A::Item, Error=A::Error>29 pub fn new<A, B>(a: A, b: B) -> Select<A, B>
30 where A: Future,
31 B: Future<Item=A::Item, Error=A::Error>
32 {
33 Select {
34 inner: Some((a, b)),
35 }
36 }
37
38 impl<A, B> Future for Select<A, B>
39 where A: Future,
40 B: Future<Item=A::Item, Error=A::Error>,
41 {
42 type Item = (A::Item, SelectNext<A, B>);
43 type Error = (A::Error, SelectNext<A, B>);
44
poll(&mut self) -> Poll<Self::Item, Self::Error>45 fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
46 let (ret, is_a) = match self.inner {
47 Some((ref mut a, ref mut b)) => {
48 match a.poll() {
49 Err(a) => (Err(a), true),
50 Ok(Async::Ready(a)) => (Ok(a), true),
51 Ok(Async::NotReady) => {
52 match b.poll() {
53 Err(a) => (Err(a), false),
54 Ok(Async::Ready(a)) => (Ok(a), false),
55 Ok(Async::NotReady) => return Ok(Async::NotReady),
56 }
57 }
58 }
59 }
60 None => panic!("cannot poll select twice"),
61 };
62
63 let (a, b) = self.inner.take().unwrap();
64 let next = if is_a {OneOf::B(b)} else {OneOf::A(a)};
65 let next = SelectNext { inner: next };
66 match ret {
67 Ok(a) => Ok(Async::Ready((a, next))),
68 Err(e) => Err((e, next)),
69 }
70 }
71 }
72
73 impl<A, B> Future for SelectNext<A, B>
74 where A: Future,
75 B: Future<Item=A::Item, Error=A::Error>,
76 {
77 type Item = A::Item;
78 type Error = A::Error;
79
poll(&mut self) -> Poll<Self::Item, Self::Error>80 fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
81 match self.inner {
82 OneOf::A(ref mut a) => a.poll(),
83 OneOf::B(ref mut b) => b.poll(),
84 }
85 }
86 }
87