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
//! Future types

use crate::{
    error::{Closed, Error},
    message,
};
use futures::{Async, Future, Poll};

/// Future eventually completed with the response to the original request.
pub struct ResponseFuture<T> {
    state: ResponseState<T>,
}

enum ResponseState<T> {
    Failed(Option<Error>),
    Rx(message::Rx<T>),
    Poll(T),
}

impl<T> ResponseFuture<T>
where
    T: Future,
    T::Error: Into<Error>,
{
    pub(crate) fn new(rx: message::Rx<T>) -> Self {
        ResponseFuture {
            state: ResponseState::Rx(rx),
        }
    }

    pub(crate) fn failed(err: Error) -> Self {
        ResponseFuture {
            state: ResponseState::Failed(Some(err)),
        }
    }
}

impl<T> Future for ResponseFuture<T>
where
    T: Future,
    T::Error: Into<Error>,
{
    type Item = T::Item;
    type Error = Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        use self::ResponseState::*;

        loop {
            let fut;

            match self.state {
                Failed(ref mut e) => {
                    return Err(e.take().expect("polled after error"));
                }
                Rx(ref mut rx) => match rx.poll() {
                    Ok(Async::Ready(Ok(f))) => fut = f,
                    Ok(Async::Ready(Err(e))) => return Err(e.into()),
                    Ok(Async::NotReady) => return Ok(Async::NotReady),
                    Err(_) => return Err(Closed::new().into()),
                },
                Poll(ref mut fut) => {
                    return fut.poll().map_err(Into::into);
                }
            }

            self.state = Poll(fut);
        }
    }
}