| 1 | use crate::Stream; |
| 2 | use std::pin::Pin; |
| 3 | use std::task::{Context, Poll}; |
| 4 | use 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" )))] |
| 12 | pub struct IntervalStream { |
| 13 | inner: Interval, |
| 14 | } |
| 15 | |
| 16 | impl 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 | |
| 28 | impl 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 | (std::usize::MAX, None) |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | impl AsRef<Interval> for IntervalStream { |
| 41 | fn as_ref(&self) -> &Interval { |
| 42 | &self.inner |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | impl AsMut<Interval> for IntervalStream { |
| 47 | fn as_mut(&mut self) -> &mut Interval { |
| 48 | &mut self.inner |
| 49 | } |
| 50 | } |
| 51 | |