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
use crate::{deadline::TimedOutError, IntoDeadline};
use core::future::Future;
use core::pin::Pin;
use futures_core::Stream;
use pin_project_lite::pin_project;
use std::task::{Context, Poll};
pub trait StreamExt: Stream {
fn until<T, D>(self, target: T) -> Stop<Self, D>
where
Self: Sized,
T: IntoDeadline<Deadline = D>,
{
Stop {
stream: self,
deadline: target.into_deadline(),
}
}
}
impl<S: Stream> StreamExt for S {}
pin_project! {
#[must_use = "Futures do nothing unless polled or .awaited"]
#[derive(Debug)]
pub struct Stop<S, D> {
#[pin]
stream: S,
#[pin]
deadline: D,
}
}
impl<S, D> Stop<S, D> {
pub fn into_inner(self) -> S {
self.stream
}
}
impl<S, D> Stream for Stop<S, D>
where
S: Stream,
D: Future<Output = ()>,
{
type Item = Result<S::Item, TimedOutError>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.project();
if let Poll::Ready(()) = this.deadline.poll(cx) {
return Poll::Ready(Some(Err(TimedOutError::new())));
}
this.stream.poll_next(cx).map(|el| el.map(|el| Ok(el)))
}
}