futures_rx/stream_ext/
timing.rs

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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
use std::{
    pin::Pin,
    task::{Context, Poll},
    time::{Duration, Instant},
};

use futures::{
    stream::{Fuse, FusedStream},
    Stream, StreamExt,
};
use pin_project_lite::pin_project;

pin_project! {
    /// Stream for the [`timing`](RxStreamExt::timing) method.
    #[must_use = "streams do nothing unless polled"]
    pub struct Timing<S: Stream> {
        #[pin]
        stream: Fuse<S>,
        last_time: Option<Instant>,
    }
}

impl<S: Stream> Timing<S> {
    pub(crate) fn new(stream: S) -> Self {
        Self {
            stream: stream.fuse(),
            last_time: None,
        }
    }
}

impl<S: Stream> FusedStream for Timing<S> {
    fn is_terminated(&self) -> bool {
        self.stream.is_terminated()
    }
}

impl<S: Stream> Stream for Timing<S> {
    type Item = Timed<S::Item>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.project();

        match this.stream.poll_next(cx) {
            Poll::Ready(Some(event)) => {
                let timestamp = Instant::now();
                let interval = this.last_time.map(|it| timestamp.duration_since(it));

                *this.last_time = Some(timestamp);

                Poll::Ready(Some(Timed {
                    event,
                    timestamp,
                    interval,
                }))
            }
            Poll::Ready(None) => Poll::Ready(None),
            Poll::Pending => Poll::Pending,
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.stream.size_hint()
    }
}

#[derive(Debug, Clone)]
pub struct Timed<T> {
    pub event: T,
    pub timestamp: Instant,
    pub interval: Option<Duration>,
}

#[cfg(test)]
mod test {
    use std::time::Instant;

    use futures::{executor::block_on, stream, Stream, StreamExt};
    use futures_time::{future::FutureExt, time::Duration};

    use crate::RxExt;

    #[test]
    fn smoke() {
        block_on(async {
            let stream = create_stream();
            let start = Instant::now();
            let all_events = stream.timing().collect::<Vec<_>>().await;
            let timestamps = all_events
                .iter()
                .map(|it| it.timestamp)
                .enumerate()
                .collect::<Vec<_>>();
            let intervals = all_events
                .iter()
                .map(|it| it.interval)
                .enumerate()
                .collect::<Vec<_>>();

            for (index, timestamp) in timestamps {
                assert!(
                    timestamp.duration_since(start).as_millis() >= (50 * index).try_into().unwrap()
                );
            }

            for (index, interval) in intervals {
                if index == 0 {
                    assert!(interval.is_none());
                } else {
                    assert!(interval.expect("interval is None!").as_millis() >= 50);
                }
            }
        });
    }

    fn create_stream() -> impl Stream<Item = usize> {
        stream::unfold(0, move |count| async move {
            if count < 10 {
                async { true }.delay(Duration::from_millis(50)).await;

                Some((count, count + 1))
            } else {
                None
            }
        })
    }
}