Skip to content

Commit 206bedf

Browse files
authored
Merge pull request #349 from k-nasa/add_future_delay
Add future::delay
2 parents 4ecf49f + 1545d24 commit 206bedf

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

src/future/future.rs

+30
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,11 @@
1+
cfg_unstable! {
2+
mod delay;
3+
4+
use std::time::Duration;
5+
6+
use delay::DelayFuture;
7+
}
8+
19
extension_trait! {
210
use std::pin::Pin;
311
use std::ops::{Deref, DerefMut};
@@ -99,6 +107,28 @@ extension_trait! {
99107
}
100108

101109
pub trait FutureExt: std::future::Future {
110+
/// Returns a Future that delays execution for a specified time.
111+
///
112+
/// # Examples
113+
///
114+
/// ```
115+
/// # async_std::task::block_on(async {
116+
/// use async_std::prelude::*;
117+
/// use async_std::future;
118+
/// use std::time::Duration;
119+
///
120+
/// let a = future::ready(1).delay(Duration::from_millis(2000));
121+
/// dbg!(a.await);
122+
/// # })
123+
/// ```
124+
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
125+
#[cfg(any(feature = "unstable", feature = "docs"))]
126+
fn delay(self, dur: Duration) -> impl Future<Output = Self::Output> [DelayFuture<Self>]
127+
where
128+
Self: Future + Sized
129+
{
130+
DelayFuture::new(self, dur)
131+
}
102132
}
103133

104134
impl<F: Future + Unpin + ?Sized> Future for Box<F> {

src/future/future/delay.rs

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
use std::pin::Pin;
2+
use std::time::Duration;
3+
4+
use futures_timer::Delay;
5+
use pin_project_lite::pin_project;
6+
7+
use crate::future::Future;
8+
use crate::task::{Context, Poll};
9+
10+
pin_project! {
11+
#[doc(hidden)]
12+
#[derive(Debug)]
13+
pub struct DelayFuture<F> {
14+
#[pin]
15+
future: F,
16+
#[pin]
17+
delay: Delay,
18+
}
19+
}
20+
21+
impl<F> DelayFuture<F> {
22+
pub fn new(future: F, dur: Duration) -> DelayFuture<F> {
23+
let delay = Delay::new(dur);
24+
25+
DelayFuture { future, delay }
26+
}
27+
}
28+
29+
impl<F: Future> Future for DelayFuture<F> {
30+
type Output = F::Output;
31+
32+
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
33+
let this = self.project();
34+
35+
match this.delay.poll(cx) {
36+
Poll::Pending => Poll::Pending,
37+
Poll::Ready(_) => match this.future.poll(cx) {
38+
Poll::Ready(v) => Poll::Ready(v),
39+
Poll::Pending => Poll::Pending,
40+
},
41+
}
42+
}
43+
}

0 commit comments

Comments
 (0)