1//! Slow down a stream by enforcing a delay between items.
23use crate::Stream;
4use tokio::time::{Duration, Instant, Sleep};
56use std::future::Future;
7use std::pin::Pin;
8use std::task::{self, ready, Poll};
910use pin_project_lite::pin_project;
1112pub(super) fn throttle<T>(duration: Duration, stream: T) -> Throttle<T>
13where
14T: Stream,
15{
16 Throttle {
17 delay: tokio::time::sleep_until(Instant::now() + duration),
18 duration,
19 has_delayed: true,
20 stream,
21 }
22}
2324pin_project! {
25/// Stream for the [`throttle`](throttle) function. This object is `!Unpin`. If you need it to
26 /// implement `Unpin` you can pin your throttle like this: `Box::pin(your_throttle)`.
27#[derive(Debug)]
28 #[must_use = "streams do nothing unless polled"]
29pub struct Throttle<T> {
30#[pin]
31delay: Sleep,
32 duration: Duration,
3334// Set to true when `delay` has returned ready, but `stream` hasn't.
35has_delayed: bool,
3637// The stream to throttle
38#[pin]
39stream: T,
40 }
41}
4243impl<T> Throttle<T> {
44/// Acquires a reference to the underlying stream that this combinator is
45 /// pulling from.
46pub fn get_ref(&self) -> &T {
47&self.stream
48 }
4950/// Acquires a mutable reference to the underlying stream that this combinator
51 /// is pulling from.
52 ///
53 /// Note that care must be taken to avoid tampering with the state of the stream
54 /// which may otherwise confuse this combinator.
55pub fn get_mut(&mut self) -> &mut T {
56&mut self.stream
57 }
5859/// Consumes this combinator, returning the underlying stream.
60 ///
61 /// Note that this may discard intermediate state of this combinator, so care
62 /// should be taken to avoid losing resources when this is called.
63pub fn into_inner(self) -> T {
64self.stream
65 }
66}
6768impl<T: Stream> Stream for Throttle<T> {
69type Item = T::Item;
7071fn poll_next(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
72let mut me = self.project();
73let dur = *me.duration;
7475if !*me.has_delayed && !is_zero(dur) {
76ready!(me.delay.as_mut().poll(cx));
77*me.has_delayed = true;
78 }
7980let value = ready!(me.stream.poll_next(cx));
8182if value.is_some() {
83if !is_zero(dur) {
84 me.delay.reset(Instant::now() + dur);
85 }
8687*me.has_delayed = false;
88 }
8990 Poll::Ready(value)
91 }
92}
9394fn is_zero(dur: Duration) -> bool {
95 dur == Duration::from_millis(0)
96}