|
| 1 | +use std::pin::Pin; |
| 2 | +use std::task::{Context, Poll}; |
| 3 | +use std::time::{Duration, Instant}; |
| 4 | + |
| 5 | +use futures_core::future::Future; |
| 6 | +use futures_core::stream::Stream; |
| 7 | +use pin_utils::unsafe_pinned; |
| 8 | + |
| 9 | +use futures_timer::Delay; |
| 10 | + |
| 11 | +/// Creates a new stream that yields at a set interval. |
| 12 | +/// |
| 13 | +/// The first stream first yields after `dur`, and continues to yield every |
| 14 | +/// `dur` after that. The stream accounts for time elapsed between calls, and |
| 15 | +/// will adjust accordingly to prevent time skews. |
| 16 | +/// |
| 17 | +/// Note that intervals are not intended for high resolution timers, but rather |
| 18 | +/// they will likely fire some granularity after the exact instant that they're |
| 19 | +/// otherwise indicated to fire at. |
| 20 | +/// |
| 21 | +/// # Examples |
| 22 | +/// |
| 23 | +/// Basic example: |
| 24 | +/// |
| 25 | +/// ```no_run |
| 26 | +/// use std::time::Duration; |
| 27 | +/// use futures::prelude::*; |
| 28 | +/// |
| 29 | +/// let interval = Interval::new(Duration::from_secs(4)); |
| 30 | +/// while let Some(_) = interval.next().await { |
| 31 | +/// println!("prints every four seconds")); |
| 32 | +/// } |
| 33 | +/// ``` |
| 34 | +#[cfg_attr(feature = "docs", doc(cfg(unstable)))] |
| 35 | +#[doc(inline)] |
| 36 | +pub fn interval(dur: Duration) -> Interval { |
| 37 | + Interval { |
| 38 | + delay: Delay::new(dur), |
| 39 | + interval: dur, |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +/// A stream representing notifications at fixed interval |
| 44 | +/// |
| 45 | +#[derive(Debug)] |
| 46 | +#[cfg_attr(feature = "docs", doc(cfg(unstable)))] |
| 47 | +#[doc(inline)] |
| 48 | +pub struct Interval { |
| 49 | + delay: Delay, |
| 50 | + interval: Duration, |
| 51 | +} |
| 52 | + |
| 53 | +impl Interval { |
| 54 | + unsafe_pinned!(delay: Delay); |
| 55 | +} |
| 56 | + |
| 57 | +impl Stream for Interval { |
| 58 | + type Item = (); |
| 59 | + |
| 60 | + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { |
| 61 | + if Pin::new(&mut *self).delay().poll(cx).is_pending() { |
| 62 | + return Poll::Pending; |
| 63 | + } |
| 64 | + let when = Instant::now(); |
| 65 | + let next = next_interval(when, Instant::now(), self.interval); |
| 66 | + self.delay.reset_at(next); |
| 67 | + Poll::Ready(Some(())) |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +/// Converts Duration object to raw nanoseconds if possible |
| 72 | +/// |
| 73 | +/// This is useful to divide intervals. |
| 74 | +/// |
| 75 | +/// While technically for large duration it's impossible to represent any |
| 76 | +/// duration as nanoseconds, the largest duration we can represent is about |
| 77 | +/// 427_000 years. Large enough for any interval we would use or calculate in |
| 78 | +/// tokio. |
| 79 | +fn duration_to_nanos(dur: Duration) -> Option<u64> { |
| 80 | + dur.as_secs() |
| 81 | + .checked_mul(1_000_000_000) |
| 82 | + .and_then(|v| v.checked_add(u64::from(dur.subsec_nanos()))) |
| 83 | +} |
| 84 | + |
| 85 | +fn next_interval(prev: Instant, now: Instant, interval: Duration) -> Instant { |
| 86 | + let new = prev + interval; |
| 87 | + if new > now { |
| 88 | + return new; |
| 89 | + } |
| 90 | + |
| 91 | + let spent_ns = duration_to_nanos(now.duration_since(prev)).expect("interval should be expired"); |
| 92 | + let interval_ns = |
| 93 | + duration_to_nanos(interval).expect("interval is less that 427 thousand years"); |
| 94 | + let mult = spent_ns / interval_ns + 1; |
| 95 | + assert!( |
| 96 | + mult < (1 << 32), |
| 97 | + "can't skip more than 4 billion intervals of {:?} \ |
| 98 | + (trying to skip {})", |
| 99 | + interval, |
| 100 | + mult |
| 101 | + ); |
| 102 | + prev + interval * (mult as u32) |
| 103 | +} |
| 104 | + |
| 105 | +#[cfg(test)] |
| 106 | +mod test { |
| 107 | + use super::next_interval; |
| 108 | + use std::time::{Duration, Instant}; |
| 109 | + |
| 110 | + struct Timeline(Instant); |
| 111 | + |
| 112 | + impl Timeline { |
| 113 | + fn new() -> Timeline { |
| 114 | + Timeline(Instant::now()) |
| 115 | + } |
| 116 | + fn at(&self, millis: u64) -> Instant { |
| 117 | + self.0 + Duration::from_millis(millis) |
| 118 | + } |
| 119 | + fn at_ns(&self, sec: u64, nanos: u32) -> Instant { |
| 120 | + self.0 + Duration::new(sec, nanos) |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + fn dur(millis: u64) -> Duration { |
| 125 | + Duration::from_millis(millis) |
| 126 | + } |
| 127 | + |
| 128 | + // The math around Instant/Duration isn't 100% precise due to rounding |
| 129 | + // errors, see #249 for more info |
| 130 | + fn almost_eq(a: Instant, b: Instant) -> bool { |
| 131 | + if a == b { |
| 132 | + true |
| 133 | + } else if a > b { |
| 134 | + a - b < Duration::from_millis(1) |
| 135 | + } else { |
| 136 | + b - a < Duration::from_millis(1) |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + #[test] |
| 141 | + fn norm_next() { |
| 142 | + let tm = Timeline::new(); |
| 143 | + assert!(almost_eq( |
| 144 | + next_interval(tm.at(1), tm.at(2), dur(10)), |
| 145 | + tm.at(11) |
| 146 | + )); |
| 147 | + assert!(almost_eq( |
| 148 | + next_interval(tm.at(7777), tm.at(7788), dur(100)), |
| 149 | + tm.at(7877) |
| 150 | + )); |
| 151 | + assert!(almost_eq( |
| 152 | + next_interval(tm.at(1), tm.at(1000), dur(2100)), |
| 153 | + tm.at(2101) |
| 154 | + )); |
| 155 | + } |
| 156 | + |
| 157 | + #[test] |
| 158 | + fn fast_forward() { |
| 159 | + let tm = Timeline::new(); |
| 160 | + assert!(almost_eq( |
| 161 | + next_interval(tm.at(1), tm.at(1000), dur(10)), |
| 162 | + tm.at(1001) |
| 163 | + )); |
| 164 | + assert!(almost_eq( |
| 165 | + next_interval(tm.at(7777), tm.at(8888), dur(100)), |
| 166 | + tm.at(8977) |
| 167 | + )); |
| 168 | + assert!(almost_eq( |
| 169 | + next_interval(tm.at(1), tm.at(10000), dur(2100)), |
| 170 | + tm.at(10501) |
| 171 | + )); |
| 172 | + } |
| 173 | + |
| 174 | + /// TODO: this test actually should be successful, but since we can't |
| 175 | + /// multiply Duration on anything larger than u32 easily we decided |
| 176 | + /// to allow it to fail for now |
| 177 | + #[test] |
| 178 | + #[should_panic(expected = "can't skip more than 4 billion intervals")] |
| 179 | + fn large_skip() { |
| 180 | + let tm = Timeline::new(); |
| 181 | + assert_eq!( |
| 182 | + next_interval(tm.at_ns(0, 1), tm.at_ns(25, 0), Duration::new(0, 2)), |
| 183 | + tm.at_ns(25, 1) |
| 184 | + ); |
| 185 | + } |
| 186 | +} |
0 commit comments