Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement core::future::lazy #91648

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions library/core/src/future/lazy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};

/// A future that lazily executes a closure.
#[derive(Debug, Clone)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
#[unstable(feature = "future_lazy", issue = "91647")]
pub struct Lazy<F>(Option<F>);

#[unstable(feature = "future_lazy", issue = "91647")]
impl<F> Unpin for Lazy<F> {}

/// Creates a new future that lazily executes a closure.
///
/// The provided closure is only run once the future is polled.
///
/// # Examples
///
/// ```
/// #![feature(future_lazy)]
///
/// # let _ = async {
/// use std::future;
///
/// let a = future::lazy(|_| 1);
/// assert_eq!(a.await, 1);
///
/// let b = future::lazy(|_| -> i32 {
/// panic!("oh no!")
/// });
/// drop(b); // closure is never run
/// # };
/// ```
#[unstable(feature = "future_lazy", issue = "91647")]
pub fn lazy<F, R>(f: F) -> Lazy<F>
where
F: FnOnce(&mut Context<'_>) -> R,
{
Lazy(Some(f))
}

#[unstable(feature = "future_lazy", issue = "91647")]
impl<F, R> Future for Lazy<F>
where
F: FnOnce(&mut Context<'_>) -> R,
{
type Output = R;

fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<R> {
let f = self.0.take().expect("`Lazy` polled after completion");
Poll::Ready((f)(cx))
}
}
4 changes: 4 additions & 0 deletions library/core/src/future/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use crate::{

mod future;
mod into_future;
mod lazy;
mod pending;
mod poll_fn;
mod ready;
Expand All @@ -29,6 +30,9 @@ pub use ready::{ready, Ready};
#[unstable(feature = "future_poll_fn", issue = "72302")]
pub use poll_fn::{poll_fn, PollFn};

#[unstable(feature = "future_lazy", issue = "91647")]
pub use self::lazy::{lazy, Lazy};

/// This type is needed because:
///
/// a) Generators cannot implement `for<'a, 'b> Generator<&'a mut Context<'b>>`, so we need to pass
Expand Down