|
| 1 | +use std::future::Future; |
| 2 | +use std::pin::Pin; |
| 3 | +use std::time::Duration; |
| 4 | + |
| 5 | +use futures_timer::Delay; |
| 6 | + |
| 7 | +use crate::stream::Stream; |
| 8 | +use crate::task::{Context, Poll}; |
| 9 | + |
| 10 | +/// A stream that only yields one element once every `duration`, and drops all others. |
| 11 | +/// #[doc(hidden)] |
| 12 | +#[allow(missing_debug_implementations)] |
| 13 | +pub struct Throttle<S> { |
| 14 | + stream: S, |
| 15 | + duration: Duration, |
| 16 | + delay: Option<Delay>, |
| 17 | +} |
| 18 | + |
| 19 | +impl<S: Unpin> Unpin for Throttle<S> {} |
| 20 | + |
| 21 | +impl<S: Stream> Throttle<S> { |
| 22 | + pin_utils::unsafe_pinned!(stream: S); |
| 23 | + pin_utils::unsafe_unpinned!(duration: Duration); |
| 24 | + pin_utils::unsafe_pinned!(delay: Option<Delay>); |
| 25 | + |
| 26 | + pub(super) fn new(stream: S, duration: Duration) -> Self { |
| 27 | + Throttle { |
| 28 | + stream, |
| 29 | + duration, |
| 30 | + delay: None, |
| 31 | + } |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +impl<S: Stream> Stream for Throttle<S> { |
| 36 | + type Item = S::Item; |
| 37 | + |
| 38 | + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<S::Item>> { |
| 39 | + match self.as_mut().stream().poll_next(cx) { |
| 40 | + Poll::Ready(v) => match self.as_mut().delay().as_pin_mut() { |
| 41 | + None => { |
| 42 | + *self.as_mut().delay() = Some(Delay::new(self.duration)); |
| 43 | + Poll::Ready(v) |
| 44 | + } |
| 45 | + Some(d) => match d.poll(cx) { |
| 46 | + Poll::Ready(_) => { |
| 47 | + *self.as_mut().delay() = Some(Delay::new(self.duration)); |
| 48 | + Poll::Ready(v) |
| 49 | + } |
| 50 | + Poll::Pending => Poll::Pending, |
| 51 | + }, |
| 52 | + }, |
| 53 | + Poll::Pending => Poll::Pending, |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments