Skip to content

Commit f00d32e

Browse files
committed
Add TimeoutStream struct
1 parent e986e7b commit f00d32e

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

src/stream/stream/timeout.rs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
use std::error::Error;
2+
use std::fmt;
3+
use std::pin::Pin;
4+
use std::time::Duration;
5+
6+
use futures_timer::Delay;
7+
8+
use crate::future::Future;
9+
use crate::stream::Stream;
10+
use crate::task::{Context, Poll};
11+
12+
#[doc(hidden)]
13+
#[derive(Debug)]
14+
pub struct TimeoutStream<S> {
15+
stream: S,
16+
delay: Delay,
17+
}
18+
19+
impl<S> TimeoutStream<S> {
20+
pin_utils::unsafe_pinned!(stream: S);
21+
pin_utils::unsafe_pinned!(delay: Delay);
22+
23+
pub fn new(stream: S, dur: Duration) -> TimeoutStream<S> {
24+
let delay = Delay::new(dur);
25+
26+
TimeoutStream { stream, delay }
27+
}
28+
}
29+
30+
impl<S: Stream> Stream for TimeoutStream<S> {
31+
type Item = Result<S::Item, TimeoutError>;
32+
33+
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
34+
match self.as_mut().stream().poll_next(cx) {
35+
Poll::Ready(Some(v)) => Poll::Ready(Some(Ok(v))),
36+
Poll::Ready(None) => Poll::Ready(None),
37+
Poll::Pending => match self.delay().poll(cx) {
38+
Poll::Ready(_) => Poll::Ready(Some(Err(TimeoutError))),
39+
Poll::Pending => Poll::Pending,
40+
},
41+
}
42+
}
43+
}
44+
45+
/// An error returned when a stream times out.
46+
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
47+
#[cfg(any(feature = "unstable", feature = "docs"))]
48+
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
49+
pub struct TimeoutError;
50+
51+
impl Error for TimeoutError {}
52+
53+
impl fmt::Display for TimeoutError {
54+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55+
"stream has timed out".fmt(f)
56+
}
57+
}

0 commit comments

Comments
 (0)