tokio_stream/wrappers/
interval.rs

1use crate::Stream;
2use std::pin::Pin;
3use std::task::{Context, Poll};
4use tokio::time::{Instant, Interval};
5
6/// A wrapper around [`Interval`] that implements [`Stream`].
7///
8/// [`Interval`]: struct@tokio::time::Interval
9/// [`Stream`]: trait@crate::Stream
10#[derive(Debug)]
11#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
12pub struct IntervalStream {
13    inner: Interval,
14}
15
16impl IntervalStream {
17    /// Create a new `IntervalStream`.
18    pub fn new(interval: Interval) -> Self {
19        Self { inner: interval }
20    }
21
22    /// Get back the inner `Interval`.
23    pub fn into_inner(self) -> Interval {
24        self.inner
25    }
26}
27
28impl Stream for IntervalStream {
29    type Item = Instant;
30
31    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Instant>> {
32        self.inner.poll_tick(cx).map(Some)
33    }
34
35    fn size_hint(&self) -> (usize, Option<usize>) {
36        (usize::MAX, None)
37    }
38}
39
40impl AsRef<Interval> for IntervalStream {
41    fn as_ref(&self) -> &Interval {
42        &self.inner
43    }
44}
45
46impl AsMut<Interval> for IntervalStream {
47    fn as_mut(&mut self) -> &mut Interval {
48        &mut self.inner
49    }
50}