From 237cfa0315185b339dc23a14faf96cebde478743 Mon Sep 17 00:00:00 2001 From: Yoshua Wuyts Date: Tue, 15 Oct 2019 16:03:49 +0200 Subject: [PATCH] add IntoFuture (#259) * add IntoFuture Signed-off-by: Yoshua Wuyts * blanket impl for IntoFuture Signed-off-by: Yoshua Wuyts * cargo fmt Signed-off-by: Yoshua Wuyts * example Signed-off-by: Yoshua Wuyts * mark as unstable Signed-off-by: Yoshua Wuyts --- src/future/into_future.rs | 54 +++++++++++++++++++++++++++++++++++++++ src/future/mod.rs | 3 +++ 2 files changed, 57 insertions(+) create mode 100644 src/future/into_future.rs diff --git a/src/future/into_future.rs b/src/future/into_future.rs new file mode 100644 index 000000000..58b676615 --- /dev/null +++ b/src/future/into_future.rs @@ -0,0 +1,54 @@ +use crate::future::Future; + +/// Convert a type into a `Future`. +/// +/// # Examples +/// +/// ``` +/// use async_std::future::{Future, IntoFuture}; +/// use async_std::io; +/// use async_std::pin::Pin; +/// +/// struct Client; +/// +/// impl Client { +/// pub async fn send(self) -> io::Result<()> { +/// // Send a request +/// Ok(()) +/// } +/// } +/// +/// impl IntoFuture for Client { +/// type Output = io::Result<()>; +/// +/// type Future = Pin>>; +/// +/// fn into_future(self) -> Self::Future { +/// Box::pin(async { +/// self.send().await +/// }) +/// } +/// } +/// ``` +#[cfg(any(feature = "unstable", feature = "docs"))] +#[cfg_attr(feature = "docs", doc(cfg(unstable)))] +pub trait IntoFuture { + /// The type of value produced on completion. + type Output; + + /// Which kind of future are we turning this into? + type Future: Future; + + /// Create a future from a value + fn into_future(self) -> Self::Future; +} + +impl IntoFuture for T { + type Output = T::Output; + + type Future = T; + + fn into_future(self) -> Self::Future { + self + } +} diff --git a/src/future/mod.rs b/src/future/mod.rs index e5e696dd0..dc9b46621 100644 --- a/src/future/mod.rs +++ b/src/future/mod.rs @@ -63,7 +63,10 @@ mod ready; cfg_if! { if #[cfg(any(feature = "unstable", feature = "docs"))] { + mod into_future; mod timeout; + + pub use into_future::IntoFuture; pub use timeout::{timeout, TimeoutError}; } }