Skip to content

Commit 054f4fa

Browse files
committed
feat: Add future::delay
1 parent e986e7b commit 054f4fa

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

src/future/delay.rs

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
use std::pin::Pin;
2+
use std::time::Duration;
3+
4+
use futures_timer::Delay;
5+
6+
use crate::future::Future;
7+
use crate::task::{Context, Poll};
8+
9+
/// Creates a future that is delayed before it starts yielding items.
10+
///
11+
/// # Examples
12+
///
13+
/// ```
14+
/// # async_std::task::block_on(async {
15+
/// use async_std::future;
16+
/// use std::time::Duration;
17+
18+
/// let a = future::delay(future::ready(1) ,Duration::from_millis(2000));
19+
/// dbg!(a.await);
20+
/// # })
21+
/// ```
22+
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
23+
#[cfg(any(feature = "unstable", feature = "docs"))]
24+
pub fn delay<F>(f: F, dur: Duration) -> DelayFuture<F>
25+
where
26+
F: Future,
27+
{
28+
DelayFuture::new(f, dur)
29+
}
30+
31+
#[doc(hidden)]
32+
#[derive(Debug)]
33+
pub struct DelayFuture<F> {
34+
future: F,
35+
delay: Delay,
36+
}
37+
38+
impl<F> DelayFuture<F> {
39+
pin_utils::unsafe_pinned!(future: F);
40+
pin_utils::unsafe_pinned!(delay: Delay);
41+
42+
pub fn new(future: F, dur: Duration) -> DelayFuture<F> {
43+
let delay = Delay::new(dur);
44+
45+
DelayFuture { future, delay }
46+
}
47+
}
48+
49+
impl<F: Future> Future for DelayFuture<F> {
50+
type Output = F::Output;
51+
52+
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
53+
match self.as_mut().delay().poll(cx) {
54+
Poll::Pending => Poll::Pending,
55+
Poll::Ready(_) => match self.future().poll(cx) {
56+
Poll::Ready(v) => Poll::Ready(v),
57+
Poll::Pending => Poll::Pending,
58+
},
59+
}
60+
}
61+
}

src/future/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,9 @@ mod timeout;
6565
cfg_if! {
6666
if #[cfg(any(feature = "unstable", feature = "docs"))] {
6767
mod into_future;
68+
mod delay;
6869

6970
pub use into_future::IntoFuture;
71+
pub use delay::delay;
7072
}
7173
}

0 commit comments

Comments
 (0)