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
use futures::{
self,
Async,
Future,
};
use std::{
io,
time::Duration,
};
use tokio_core::reactor::{
Remote,
Timeout,
};
use remote::GetRemote;
pub trait TimeoutTrait: futures::Stream + GetRemote + Sized {
fn timeout(self, duration: Duration) -> io::Result<TimeoutStream<Self>>;
}
impl<S: futures::Stream + GetRemote> TimeoutTrait for S {
fn timeout(self, duration: Duration) -> io::Result<TimeoutStream<Self>> {
TimeoutStream::new(self, duration)
}
}
#[must_use = "streams do nothing unless polled"]
pub struct TimeoutStream<S> {
stream: S,
duration: Duration,
timeout: Option<Timeout>,
}
impl<S: futures::Stream + GetRemote> TimeoutStream<S> {
pub fn new(stream: S, duration: Duration) -> io::Result<Self> {
Ok(TimeoutStream {
stream,
duration,
timeout: None,
})
}
}
#[derive(Debug)]
pub enum TimeoutStreamError<E> {
StreamError(E),
TimeoutError(io::Error),
}
impl<E: Into<io::Error>> TimeoutStreamError<E> {
pub fn into_io_error(self) -> io::Error {
match self {
TimeoutStreamError::StreamError(e) => e.into(),
TimeoutStreamError::TimeoutError(e) => e,
}
}
}
impl<S: futures::Stream + GetRemote> TimeoutStream<S> {
fn reset_timer(&mut self) -> Result<(), TimeoutStreamError<S::Error>> {
let handle = self
.stream
.remote()
.handle()
.expect("couldn't get handle in poll");
self.timeout = Some(match Timeout::new(self.duration, &handle) {
Ok(timeout) => timeout,
Err(e) => return Err(TimeoutStreamError::TimeoutError(e)),
});
Ok(())
}
fn get_timer(
&mut self,
) -> Result<&mut Timeout, TimeoutStreamError<S::Error>> {
if self.timeout.is_none() {
self.reset_timer()?;
}
Ok(self.timeout.as_mut().unwrap())
}
}
impl<S: futures::Stream + GetRemote> futures::Stream for TimeoutStream<S> {
type Error = TimeoutStreamError<S::Error>;
type Item = S::Item;
fn poll(&mut self) -> Result<Async<Option<Self::Item>>, Self::Error> {
match self.stream.poll() {
Ok(Async::Ready(None)) => Ok(Async::Ready(None)), Ok(Async::Ready(item)) => {
self.reset_timer()?;
Ok(Async::Ready(item))
},
Ok(Async::NotReady) => {
match self.get_timer()?.poll() {
Ok(Async::Ready(_)) => {
Ok(Async::Ready(None))
},
Ok(Async::NotReady) => Ok(Async::NotReady),
Err(e) => Err(TimeoutStreamError::TimeoutError(e)),
}
},
Err(e) => Err(TimeoutStreamError::StreamError(e)),
}
}
}
impl<S: futures::Stream + GetRemote> GetRemote for TimeoutStream<S> {
fn remote(&self) -> &Remote {
self.stream.remote()
}
}