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
use futures_core::Stream;
use std::{
future::Future,
pin::Pin,
task::{
Context,
Poll,
},
time::Duration,
};
pub trait StreamTimeoutExt: Stream + Sized {
fn timeout(self, duration: Duration) -> TimeoutStream<Self>;
}
impl<S: Stream> StreamTimeoutExt for S {
fn timeout(self, duration: Duration) -> TimeoutStream<Self> {
TimeoutStream::new(self, duration)
}
}
#[must_use = "streams do nothing unless polled"]
pub struct TimeoutStream<S> {
stream: S,
duration: Duration,
timeout: tokio::time::Sleep,
}
impl<S: Stream> TimeoutStream<S> {
pin_utils::unsafe_pinned!(stream: S);
pin_utils::unsafe_pinned!(timeout: tokio::time::Sleep);
pub fn new(stream: S, duration: Duration) -> Self {
Self {
stream,
duration,
timeout: tokio::time::sleep(duration),
}
}
}
impl<S: Stream> TimeoutStream<S> {
fn reset_timer(self: Pin<&mut Self>) {
let next = tokio::time::Instant::now() + self.duration;
self.timeout().reset(next);
}
}
impl<S: futures_core::TryStream> Stream for TimeoutStream<S> {
type Item = Result<S::Ok, S::Error>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
match self.as_mut().stream().try_poll_next(cx) {
Poll::Ready(None) => Poll::Ready(None),
Poll::Ready(Some(Ok(item))) => {
self.reset_timer();
Poll::Ready(Some(Ok(item)))
},
Poll::Ready(Some(Err(e))) => Poll::Ready(Some(Err(e))),
Poll::Pending => {
match self.timeout().poll(cx) {
Poll::Ready(()) => {
Poll::Ready(None)
},
Poll::Pending => Poll::Pending,
}
},
}
}
}