|
| 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 | +} |
0 commit comments