forked from mirror/async-std
commit
206bedfd12
2 changed files with 73 additions and 0 deletions
|
@ -1,3 +1,11 @@
|
||||||
|
cfg_unstable! {
|
||||||
|
mod delay;
|
||||||
|
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use delay::DelayFuture;
|
||||||
|
}
|
||||||
|
|
||||||
extension_trait! {
|
extension_trait! {
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
use std::ops::{Deref, DerefMut};
|
use std::ops::{Deref, DerefMut};
|
||||||
|
@ -99,6 +107,28 @@ extension_trait! {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait FutureExt: std::future::Future {
|
pub trait FutureExt: std::future::Future {
|
||||||
|
/// Returns a Future that delays execution for a specified time.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// # async_std::task::block_on(async {
|
||||||
|
/// use async_std::prelude::*;
|
||||||
|
/// use async_std::future;
|
||||||
|
/// use std::time::Duration;
|
||||||
|
///
|
||||||
|
/// let a = future::ready(1).delay(Duration::from_millis(2000));
|
||||||
|
/// dbg!(a.await);
|
||||||
|
/// # })
|
||||||
|
/// ```
|
||||||
|
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||||
|
#[cfg(any(feature = "unstable", feature = "docs"))]
|
||||||
|
fn delay(self, dur: Duration) -> impl Future<Output = Self::Output> [DelayFuture<Self>]
|
||||||
|
where
|
||||||
|
Self: Future + Sized
|
||||||
|
{
|
||||||
|
DelayFuture::new(self, dur)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<F: Future + Unpin + ?Sized> Future for Box<F> {
|
impl<F: Future + Unpin + ?Sized> Future for Box<F> {
|
||||||
|
|
43
src/future/future/delay.rs
Normal file
43
src/future/future/delay.rs
Normal file
|
@ -0,0 +1,43 @@
|
||||||
|
use std::pin::Pin;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use futures_timer::Delay;
|
||||||
|
use pin_project_lite::pin_project;
|
||||||
|
|
||||||
|
use crate::future::Future;
|
||||||
|
use crate::task::{Context, Poll};
|
||||||
|
|
||||||
|
pin_project! {
|
||||||
|
#[doc(hidden)]
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct DelayFuture<F> {
|
||||||
|
#[pin]
|
||||||
|
future: F,
|
||||||
|
#[pin]
|
||||||
|
delay: Delay,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<F> DelayFuture<F> {
|
||||||
|
pub fn new(future: F, dur: Duration) -> DelayFuture<F> {
|
||||||
|
let delay = Delay::new(dur);
|
||||||
|
|
||||||
|
DelayFuture { future, delay }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<F: Future> Future for DelayFuture<F> {
|
||||||
|
type Output = F::Output;
|
||||||
|
|
||||||
|
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
|
let this = self.project();
|
||||||
|
|
||||||
|
match this.delay.poll(cx) {
|
||||||
|
Poll::Pending => Poll::Pending,
|
||||||
|
Poll::Ready(_) => match this.future.poll(cx) {
|
||||||
|
Poll::Ready(v) => Poll::Ready(v),
|
||||||
|
Poll::Pending => Poll::Pending,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue