Skip to content

Commit 01f8584

Browse files
committed
add stream::interval
Signed-off-by: Yoshua Wuyts <[email protected]>
1 parent e75c3a9 commit 01f8584

File tree

4 files changed

+236
-3
lines changed

4 files changed

+236
-3
lines changed

Diff for: Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ crossbeam-channel = "0.3.9"
3232
crossbeam-deque = "0.7.1"
3333
futures-core-preview = "=0.3.0-alpha.19"
3434
futures-io-preview = "=0.3.0-alpha.19"
35-
futures-timer = "0.4.0"
35+
futures-timer = "1.0.0"
3636
lazy_static = "1.4.0"
3737
log = { version = "0.4.8", features = ["kv_unstable"] }
3838
memchr = "2.2.1"

Diff for: src/io/timeout.rs

+47-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
use std::time::Duration;
2+
use std::task::{Context, Poll};
3+
use std::pin::Pin;
24

3-
use futures_timer::TryFutureExt;
5+
use futures_timer::Delay;
6+
use pin_utils::unsafe_pinned;
47

58
use crate::future::Future;
69
use crate::io;
@@ -33,5 +36,47 @@ pub async fn timeout<F, T>(dur: Duration, f: F) -> io::Result<T>
3336
where
3437
F: Future<Output = io::Result<T>>,
3538
{
36-
f.timeout(dur).await
39+
Timeout {
40+
timeout: Delay::new(dur),
41+
future: f,
42+
}.await
43+
}
44+
45+
/// Future returned by the `FutureExt::timeout` method.
46+
#[derive(Debug)]
47+
pub struct Timeout<F, T>
48+
where
49+
F: Future<Output = io::Result<T>>,
50+
{
51+
future: F,
52+
timeout: Delay,
53+
}
54+
55+
impl<F, T> Timeout<F, T>
56+
where
57+
F: Future<Output = io::Result<T>>,
58+
{
59+
unsafe_pinned!(future: F);
60+
unsafe_pinned!(timeout: Delay);
61+
}
62+
63+
impl<F, T> Future for Timeout<F, T>
64+
where
65+
F: Future<Output = io::Result<T>>,
66+
{
67+
type Output = io::Result<T>;
68+
69+
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
70+
match self.as_mut().future().poll(cx) {
71+
Poll::Pending => {}
72+
other => return other,
73+
}
74+
75+
if self.timeout().poll(cx).is_ready() {
76+
let err = Err(io::Error::new(io::ErrorKind::TimedOut, "future timed out").into());
77+
Poll::Ready(err)
78+
} else {
79+
Poll::Pending
80+
}
81+
}
3782
}

Diff for: src/stream/interval.rs

+186
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
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+
}

Diff for: src/stream/mod.rs

+2
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,13 @@ cfg_if! {
4040
mod extend;
4141
mod from_stream;
4242
mod into_stream;
43+
mod interval;
4344

4445
pub use double_ended_stream::DoubleEndedStream;
4546
pub use extend::Extend;
4647
pub use from_stream::FromStream;
4748
pub use into_stream::IntoStream;
49+
pub use interval::{interval, Interval};
4850

4951
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
5052
#[doc(inline)]

0 commit comments

Comments
 (0)