summaryrefslogtreecommitdiffstats
path: root/library/core/src/future
diff options
context:
space:
mode:
Diffstat (limited to 'library/core/src/future')
-rw-r--r--library/core/src/future/future.rs126
-rw-r--r--library/core/src/future/into_future.rs139
-rw-r--r--library/core/src/future/join.rs193
-rw-r--r--library/core/src/future/mod.rs110
-rw-r--r--library/core/src/future/pending.rs58
-rw-r--r--library/core/src/future/poll_fn.rs63
-rw-r--r--library/core/src/future/ready.rs46
7 files changed, 735 insertions, 0 deletions
diff --git a/library/core/src/future/future.rs b/library/core/src/future/future.rs
new file mode 100644
index 000000000..f29d3e1e9
--- /dev/null
+++ b/library/core/src/future/future.rs
@@ -0,0 +1,126 @@
+#![stable(feature = "futures_api", since = "1.36.0")]
+
+use crate::marker::Unpin;
+use crate::ops;
+use crate::pin::Pin;
+use crate::task::{Context, Poll};
+
+/// A future represents an asynchronous computation obtained by use of [`async`].
+///
+/// A future is a value that might not have finished computing yet. This kind of
+/// "asynchronous value" makes it possible for a thread to continue doing useful
+/// work while it waits for the value to become available.
+///
+/// # The `poll` method
+///
+/// The core method of future, `poll`, *attempts* to resolve the future into a
+/// final value. This method does not block if the value is not ready. Instead,
+/// the current task is scheduled to be woken up when it's possible to make
+/// further progress by `poll`ing again. The `context` passed to the `poll`
+/// method can provide a [`Waker`], which is a handle for waking up the current
+/// task.
+///
+/// When using a future, you generally won't call `poll` directly, but instead
+/// `.await` the value.
+///
+/// [`async`]: ../../std/keyword.async.html
+/// [`Waker`]: crate::task::Waker
+#[doc(notable_trait)]
+#[must_use = "futures do nothing unless you `.await` or poll them"]
+#[stable(feature = "futures_api", since = "1.36.0")]
+#[lang = "future_trait"]
+#[rustc_on_unimplemented(
+ label = "`{Self}` is not a future",
+ message = "`{Self}` is not a future",
+ note = "{Self} must be a future or must implement `IntoFuture` to be awaited"
+)]
+pub trait Future {
+ /// The type of value produced on completion.
+ #[stable(feature = "futures_api", since = "1.36.0")]
+ type Output;
+
+ /// Attempt to resolve the future to a final value, registering
+ /// the current task for wakeup if the value is not yet available.
+ ///
+ /// # Return value
+ ///
+ /// This function returns:
+ ///
+ /// - [`Poll::Pending`] if the future is not ready yet
+ /// - [`Poll::Ready(val)`] with the result `val` of this future if it
+ /// finished successfully.
+ ///
+ /// Once a future has finished, clients should not `poll` it again.
+ ///
+ /// When a future is not ready yet, `poll` returns `Poll::Pending` and
+ /// stores a clone of the [`Waker`] copied from the current [`Context`].
+ /// This [`Waker`] is then woken once the future can make progress.
+ /// For example, a future waiting for a socket to become
+ /// readable would call `.clone()` on the [`Waker`] and store it.
+ /// When a signal arrives elsewhere indicating that the socket is readable,
+ /// [`Waker::wake`] is called and the socket future's task is awoken.
+ /// Once a task has been woken up, it should attempt to `poll` the future
+ /// again, which may or may not produce a final value.
+ ///
+ /// Note that on multiple calls to `poll`, only the [`Waker`] from the
+ /// [`Context`] passed to the most recent call should be scheduled to
+ /// receive a wakeup.
+ ///
+ /// # Runtime characteristics
+ ///
+ /// Futures alone are *inert*; they must be *actively* `poll`ed to make
+ /// progress, meaning that each time the current task is woken up, it should
+ /// actively re-`poll` pending futures that it still has an interest in.
+ ///
+ /// The `poll` function is not called repeatedly in a tight loop -- instead,
+ /// it should only be called when the future indicates that it is ready to
+ /// make progress (by calling `wake()`). If you're familiar with the
+ /// `poll(2)` or `select(2)` syscalls on Unix it's worth noting that futures
+ /// typically do *not* suffer the same problems of "all wakeups must poll
+ /// all events"; they are more like `epoll(4)`.
+ ///
+ /// An implementation of `poll` should strive to return quickly, and should
+ /// not block. Returning quickly prevents unnecessarily clogging up
+ /// threads or event loops. If it is known ahead of time that a call to
+ /// `poll` may end up taking awhile, the work should be offloaded to a
+ /// thread pool (or something similar) to ensure that `poll` can return
+ /// quickly.
+ ///
+ /// # Panics
+ ///
+ /// Once a future has completed (returned `Ready` from `poll`), calling its
+ /// `poll` method again may panic, block forever, or cause other kinds of
+ /// problems; the `Future` trait places no requirements on the effects of
+ /// such a call. However, as the `poll` method is not marked `unsafe`,
+ /// Rust's usual rules apply: calls must never cause undefined behavior
+ /// (memory corruption, incorrect use of `unsafe` functions, or the like),
+ /// regardless of the future's state.
+ ///
+ /// [`Poll::Ready(val)`]: Poll::Ready
+ /// [`Waker`]: crate::task::Waker
+ /// [`Waker::wake`]: crate::task::Waker::wake
+ #[lang = "poll"]
+ #[stable(feature = "futures_api", since = "1.36.0")]
+ fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
+}
+
+#[stable(feature = "futures_api", since = "1.36.0")]
+impl<F: ?Sized + Future + Unpin> Future for &mut F {
+ type Output = F::Output;
+
+ fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+ F::poll(Pin::new(&mut **self), cx)
+ }
+}
+
+#[stable(feature = "futures_api", since = "1.36.0")]
+impl<P> Future for Pin<P>
+where
+ P: ops::DerefMut<Target: Future>,
+{
+ type Output = <<P as ops::Deref>::Target as Future>::Output;
+
+ fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+ <P::Target as Future>::poll(self.as_deref_mut(), cx)
+ }
+}
diff --git a/library/core/src/future/into_future.rs b/library/core/src/future/into_future.rs
new file mode 100644
index 000000000..649b43387
--- /dev/null
+++ b/library/core/src/future/into_future.rs
@@ -0,0 +1,139 @@
+use crate::future::Future;
+
+/// Conversion into a `Future`.
+///
+/// By implementing `IntoFuture` for a type, you define how it will be
+/// converted to a future.
+///
+/// # `.await` desugaring
+///
+/// The `.await` keyword desugars into a call to `IntoFuture::into_future`
+/// first before polling the future to completion. `IntoFuture` is implemented
+/// for all `T: Future` which means the `into_future` method will be available
+/// on all futures.
+///
+/// ```no_run
+/// use std::future::IntoFuture;
+///
+/// # async fn foo() {
+/// let v = async { "meow" };
+/// let mut fut = v.into_future();
+/// assert_eq!("meow", fut.await);
+/// # }
+/// ```
+///
+/// # Async builders
+///
+/// When implementing futures manually there will often be a choice between
+/// implementing `Future` or `IntoFuture` for a type. Implementing `Future` is a
+/// good choice in most cases. But implementing `IntoFuture` is most useful when
+/// implementing "async builder" types, which allow their values to be modified
+/// multiple times before being `.await`ed.
+///
+/// ```rust
+/// use std::future::{ready, Ready, IntoFuture};
+///
+/// /// Eventually multiply two numbers
+/// pub struct Multiply {
+/// num: u16,
+/// factor: u16,
+/// }
+///
+/// impl Multiply {
+/// /// Construct a new instance of `Multiply`.
+/// pub fn new(num: u16, factor: u16) -> Self {
+/// Self { num, factor }
+/// }
+///
+/// /// Set the number to multiply by the factor.
+/// pub fn number(mut self, num: u16) -> Self {
+/// self.num = num;
+/// self
+/// }
+///
+/// /// Set the factor to multiply the number with.
+/// pub fn factor(mut self, factor: u16) -> Self {
+/// self.factor = factor;
+/// self
+/// }
+/// }
+///
+/// impl IntoFuture for Multiply {
+/// type Output = u16;
+/// type IntoFuture = Ready<Self::Output>;
+///
+/// fn into_future(self) -> Self::IntoFuture {
+/// ready(self.num * self.factor)
+/// }
+/// }
+///
+/// // NOTE: Rust does not yet have an `async fn main` function, that functionality
+/// // currently only exists in the ecosystem.
+/// async fn run() {
+/// let num = Multiply::new(0, 0) // initialize the builder to number: 0, factor: 0
+/// .number(2) // change the number to 2
+/// .factor(2) // change the factor to 2
+/// .await; // convert to future and .await
+///
+/// assert_eq!(num, 4);
+/// }
+/// ```
+///
+/// # Usage in trait bounds
+///
+/// Using `IntoFuture` in trait bounds allows a function to be generic over both
+/// `Future` and `IntoFuture`. This is convenient for users of the function, so
+/// when they are using it they don't have to make an extra call to
+/// `IntoFuture::into_future` to obtain an instance of `Future`:
+///
+/// ```rust
+/// use std::future::IntoFuture;
+///
+/// /// Convert the output of a future to a string.
+/// async fn fut_to_string<Fut>(fut: Fut) -> String
+/// where
+/// Fut: IntoFuture,
+/// Fut::Output: std::fmt::Debug,
+/// {
+/// format!("{:?}", fut.await)
+/// }
+/// ```
+#[stable(feature = "into_future", since = "1.64.0")]
+pub trait IntoFuture {
+ /// The output that the future will produce on completion.
+ #[stable(feature = "into_future", since = "1.64.0")]
+ type Output;
+
+ /// Which kind of future are we turning this into?
+ #[stable(feature = "into_future", since = "1.64.0")]
+ type IntoFuture: Future<Output = Self::Output>;
+
+ /// Creates a future from a value.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```no_run
+ /// use std::future::IntoFuture;
+ ///
+ /// # async fn foo() {
+ /// let v = async { "meow" };
+ /// let mut fut = v.into_future();
+ /// assert_eq!("meow", fut.await);
+ /// # }
+ /// ```
+ #[stable(feature = "into_future", since = "1.64.0")]
+ #[lang = "into_future"]
+ fn into_future(self) -> Self::IntoFuture;
+}
+
+#[stable(feature = "into_future", since = "1.64.0")]
+impl<F: Future> IntoFuture for F {
+ type Output = F::Output;
+ type IntoFuture = F;
+
+ fn into_future(self) -> Self::IntoFuture {
+ self
+ }
+}
diff --git a/library/core/src/future/join.rs b/library/core/src/future/join.rs
new file mode 100644
index 000000000..35f0dea06
--- /dev/null
+++ b/library/core/src/future/join.rs
@@ -0,0 +1,193 @@
+#![allow(unused_imports, unused_macros)] // items are used by the macro
+
+use crate::cell::UnsafeCell;
+use crate::future::{poll_fn, Future};
+use crate::mem;
+use crate::pin::Pin;
+use crate::task::{Context, Poll};
+
+/// Polls multiple futures simultaneously, returning a tuple
+/// of all results once complete.
+///
+/// While `join!(a, b).await` is similar to `(a.await, b.await)`,
+/// `join!` polls both futures concurrently and is therefore more efficient.
+///
+/// # Examples
+///
+/// ```
+/// #![feature(future_join)]
+///
+/// use std::future::join;
+///
+/// async fn one() -> usize { 1 }
+/// async fn two() -> usize { 2 }
+///
+/// # let _ = async {
+/// let x = join!(one(), two()).await;
+/// assert_eq!(x, (1, 2));
+/// # };
+/// ```
+///
+/// `join!` is variadic, so you can pass any number of futures:
+///
+/// ```
+/// #![feature(future_join)]
+///
+/// use std::future::join;
+///
+/// async fn one() -> usize { 1 }
+/// async fn two() -> usize { 2 }
+/// async fn three() -> usize { 3 }
+///
+/// # let _ = async {
+/// let x = join!(one(), two(), three()).await;
+/// assert_eq!(x, (1, 2, 3));
+/// # };
+/// ```
+#[unstable(feature = "future_join", issue = "91642")]
+pub macro join( $($fut:expr),+ $(,)? ) {
+ // Funnel through an internal macro not to leak implementation details.
+ join_internal! {
+ current_position: []
+ futures_and_positions: []
+ munching: [ $($fut)+ ]
+ }
+}
+
+// FIXME(danielhenrymantilla): a private macro should need no stability guarantee.
+#[unstable(feature = "future_join", issue = "91642")]
+/// To be able to *name* the i-th future in the tuple (say we want the .4-th),
+/// the following trick will be used: `let (_, _, _, _, it, ..) = tuple;`
+/// In order to do that, we need to generate a `i`-long repetition of `_`,
+/// for each i-th fut. Hence the recursive muncher approach.
+macro join_internal {
+ // Recursion step: map each future with its "position" (underscore count).
+ (
+ // Accumulate a token for each future that has been expanded: "_ _ _".
+ current_position: [
+ $($underscores:tt)*
+ ]
+ // Accumulate Futures and their positions in the tuple: `_0th () _1st ( _ ) …`.
+ futures_and_positions: [
+ $($acc:tt)*
+ ]
+ // Munch one future.
+ munching: [
+ $current:tt
+ $($rest:tt)*
+ ]
+ ) => (
+ join_internal! {
+ current_position: [
+ $($underscores)*
+ _
+ ]
+ futures_and_positions: [
+ $($acc)*
+ $current ( $($underscores)* )
+ ]
+ munching: [
+ $($rest)*
+ ]
+ }
+ ),
+
+ // End of recursion: generate the output future.
+ (
+ current_position: $_:tt
+ futures_and_positions: [
+ $(
+ $fut_expr:tt ( $($pos:tt)* )
+ )*
+ ]
+ // Nothing left to munch.
+ munching: []
+ ) => (
+ match ( $( MaybeDone::Future($fut_expr), )* ) { futures => async {
+ let mut futures = futures;
+ // SAFETY: this is `pin_mut!`.
+ let mut futures = unsafe { Pin::new_unchecked(&mut futures) };
+ poll_fn(move |cx| {
+ let mut done = true;
+ // For each `fut`, pin-project to it, and poll it.
+ $(
+ // SAFETY: pinning projection
+ let fut = unsafe {
+ futures.as_mut().map_unchecked_mut(|it| {
+ let ( $($pos,)* fut, .. ) = it;
+ fut
+ })
+ };
+ // Despite how tempting it may be to `let () = fut.poll(cx).ready()?;`
+ // doing so would defeat the point of `join!`: to start polling eagerly all
+ // of the futures, to allow parallelizing the waits.
+ done &= fut.poll(cx).is_ready();
+ )*
+ if !done {
+ return Poll::Pending;
+ }
+ // All ready; time to extract all the outputs.
+
+ // SAFETY: `.take_output()` does not break the `Pin` invariants for that `fut`.
+ let futures = unsafe {
+ futures.as_mut().get_unchecked_mut()
+ };
+ Poll::Ready(
+ ($(
+ {
+ let ( $($pos,)* fut, .. ) = &mut *futures;
+ fut.take_output().unwrap()
+ }
+ ),*) // <- no trailing comma since we don't want 1-tuples.
+ )
+ }).await
+ }}
+ ),
+}
+
+/// Future used by `join!` that stores it's output to
+/// be later taken and doesn't panic when polled after ready.
+///
+/// This type is public in a private module for use by the macro.
+#[allow(missing_debug_implementations)]
+#[unstable(feature = "future_join", issue = "91642")]
+pub enum MaybeDone<F: Future> {
+ Future(F),
+ Done(F::Output),
+ Taken,
+}
+
+#[unstable(feature = "future_join", issue = "91642")]
+impl<F: Future> MaybeDone<F> {
+ pub fn take_output(&mut self) -> Option<F::Output> {
+ match *self {
+ MaybeDone::Done(_) => match mem::replace(self, Self::Taken) {
+ MaybeDone::Done(val) => Some(val),
+ _ => unreachable!(),
+ },
+ _ => None,
+ }
+ }
+}
+
+#[unstable(feature = "future_join", issue = "91642")]
+impl<F: Future> Future for MaybeDone<F> {
+ type Output = ();
+
+ fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+ // SAFETY: pinning in structural for `f`
+ unsafe {
+ // Do not mix match ergonomics with unsafe.
+ match *self.as_mut().get_unchecked_mut() {
+ MaybeDone::Future(ref mut f) => {
+ let val = Pin::new_unchecked(f).poll(cx).ready()?;
+ self.set(Self::Done(val));
+ }
+ MaybeDone::Done(_) => {}
+ MaybeDone::Taken => unreachable!(),
+ }
+ }
+
+ Poll::Ready(())
+ }
+}
diff --git a/library/core/src/future/mod.rs b/library/core/src/future/mod.rs
new file mode 100644
index 000000000..6487aa088
--- /dev/null
+++ b/library/core/src/future/mod.rs
@@ -0,0 +1,110 @@
+#![stable(feature = "futures_api", since = "1.36.0")]
+
+//! Asynchronous basic functionality.
+//!
+//! Please see the fundamental [`async`] and [`await`] keywords and the [async book]
+//! for more information on asynchronous programming in Rust.
+//!
+//! [`async`]: ../../std/keyword.async.html
+//! [`await`]: ../../std/keyword.await.html
+//! [async book]: https://rust-lang.github.io/async-book/
+
+use crate::{
+ ops::{Generator, GeneratorState},
+ pin::Pin,
+ ptr::NonNull,
+ task::{Context, Poll},
+};
+
+mod future;
+mod into_future;
+mod join;
+mod pending;
+mod poll_fn;
+mod ready;
+
+#[stable(feature = "futures_api", since = "1.36.0")]
+pub use self::future::Future;
+
+#[unstable(feature = "future_join", issue = "91642")]
+pub use self::join::join;
+
+#[stable(feature = "into_future", since = "1.64.0")]
+pub use into_future::IntoFuture;
+
+#[stable(feature = "future_readiness_fns", since = "1.48.0")]
+pub use pending::{pending, Pending};
+#[stable(feature = "future_readiness_fns", since = "1.48.0")]
+pub use ready::{ready, Ready};
+
+#[stable(feature = "future_poll_fn", since = "1.64.0")]
+pub use poll_fn::{poll_fn, PollFn};
+
+/// This type is needed because:
+///
+/// a) Generators cannot implement `for<'a, 'b> Generator<&'a mut Context<'b>>`, so we need to pass
+/// a raw pointer (see <https://github.com/rust-lang/rust/issues/68923>).
+/// b) Raw pointers and `NonNull` aren't `Send` or `Sync`, so that would make every single future
+/// non-Send/Sync as well, and we don't want that.
+///
+/// It also simplifies the HIR lowering of `.await`.
+#[doc(hidden)]
+#[unstable(feature = "gen_future", issue = "50547")]
+#[derive(Debug, Copy, Clone)]
+pub struct ResumeTy(NonNull<Context<'static>>);
+
+#[unstable(feature = "gen_future", issue = "50547")]
+unsafe impl Send for ResumeTy {}
+
+#[unstable(feature = "gen_future", issue = "50547")]
+unsafe impl Sync for ResumeTy {}
+
+/// Wrap a generator in a future.
+///
+/// This function returns a `GenFuture` underneath, but hides it in `impl Trait` to give
+/// better error messages (`impl Future` rather than `GenFuture<[closure.....]>`).
+// This is `const` to avoid extra errors after we recover from `const async fn`
+#[lang = "from_generator"]
+#[doc(hidden)]
+#[unstable(feature = "gen_future", issue = "50547")]
+#[rustc_const_unstable(feature = "gen_future", issue = "50547")]
+#[inline]
+pub const fn from_generator<T>(gen: T) -> impl Future<Output = T::Return>
+where
+ T: Generator<ResumeTy, Yield = ()>,
+{
+ #[rustc_diagnostic_item = "gen_future"]
+ struct GenFuture<T: Generator<ResumeTy, Yield = ()>>(T);
+
+ // We rely on the fact that async/await futures are immovable in order to create
+ // self-referential borrows in the underlying generator.
+ impl<T: Generator<ResumeTy, Yield = ()>> !Unpin for GenFuture<T> {}
+
+ impl<T: Generator<ResumeTy, Yield = ()>> Future for GenFuture<T> {
+ type Output = T::Return;
+ fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+ // SAFETY: Safe because we're !Unpin + !Drop, and this is just a field projection.
+ let gen = unsafe { Pin::map_unchecked_mut(self, |s| &mut s.0) };
+
+ // Resume the generator, turning the `&mut Context` into a `NonNull` raw pointer. The
+ // `.await` lowering will safely cast that back to a `&mut Context`.
+ match gen.resume(ResumeTy(NonNull::from(cx).cast::<Context<'static>>())) {
+ GeneratorState::Yielded(()) => Poll::Pending,
+ GeneratorState::Complete(x) => Poll::Ready(x),
+ }
+ }
+ }
+
+ GenFuture(gen)
+}
+
+#[lang = "get_context"]
+#[doc(hidden)]
+#[unstable(feature = "gen_future", issue = "50547")]
+#[must_use]
+#[inline]
+pub unsafe fn get_context<'a, 'b>(cx: ResumeTy) -> &'a mut Context<'b> {
+ // SAFETY: the caller must guarantee that `cx.0` is a valid pointer
+ // that fulfills all the requirements for a mutable reference.
+ unsafe { &mut *cx.0.as_ptr().cast() }
+}
diff --git a/library/core/src/future/pending.rs b/library/core/src/future/pending.rs
new file mode 100644
index 000000000..2877e66ec
--- /dev/null
+++ b/library/core/src/future/pending.rs
@@ -0,0 +1,58 @@
+use crate::fmt::{self, Debug};
+use crate::future::Future;
+use crate::marker;
+use crate::pin::Pin;
+use crate::task::{Context, Poll};
+
+/// Creates a future which never resolves, representing a computation that never
+/// finishes.
+///
+/// This `struct` is created by [`pending()`]. See its
+/// documentation for more.
+#[stable(feature = "future_readiness_fns", since = "1.48.0")]
+#[must_use = "futures do nothing unless you `.await` or poll them"]
+pub struct Pending<T> {
+ _data: marker::PhantomData<fn() -> T>,
+}
+
+/// Creates a future which never resolves, representing a computation that never
+/// finishes.
+///
+/// # Examples
+///
+/// ```no_run
+/// use std::future;
+///
+/// # async fn run() {
+/// let future = future::pending();
+/// let () = future.await;
+/// unreachable!();
+/// # }
+/// ```
+#[stable(feature = "future_readiness_fns", since = "1.48.0")]
+pub fn pending<T>() -> Pending<T> {
+ Pending { _data: marker::PhantomData }
+}
+
+#[stable(feature = "future_readiness_fns", since = "1.48.0")]
+impl<T> Future for Pending<T> {
+ type Output = T;
+
+ fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<T> {
+ Poll::Pending
+ }
+}
+
+#[stable(feature = "future_readiness_fns", since = "1.48.0")]
+impl<T> Debug for Pending<T> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("Pending").finish()
+ }
+}
+
+#[stable(feature = "future_readiness_fns", since = "1.48.0")]
+impl<T> Clone for Pending<T> {
+ fn clone(&self) -> Self {
+ pending()
+ }
+}
diff --git a/library/core/src/future/poll_fn.rs b/library/core/src/future/poll_fn.rs
new file mode 100644
index 000000000..db2a52332
--- /dev/null
+++ b/library/core/src/future/poll_fn.rs
@@ -0,0 +1,63 @@
+use crate::fmt;
+use crate::future::Future;
+use crate::pin::Pin;
+use crate::task::{Context, Poll};
+
+/// Creates a future that wraps a function returning [`Poll`].
+///
+/// Polling the future delegates to the wrapped function.
+///
+/// # Examples
+///
+/// ```
+/// # async fn run() {
+/// use core::future::poll_fn;
+/// use std::task::{Context, Poll};
+///
+/// fn read_line(_cx: &mut Context<'_>) -> Poll<String> {
+/// Poll::Ready("Hello, World!".into())
+/// }
+///
+/// let read_future = poll_fn(read_line);
+/// assert_eq!(read_future.await, "Hello, World!".to_owned());
+/// # }
+/// ```
+#[stable(feature = "future_poll_fn", since = "1.64.0")]
+pub fn poll_fn<T, F>(f: F) -> PollFn<F>
+where
+ F: FnMut(&mut Context<'_>) -> Poll<T>,
+{
+ PollFn { f }
+}
+
+/// A Future that wraps a function returning [`Poll`].
+///
+/// This `struct` is created by [`poll_fn()`]. See its
+/// documentation for more.
+#[must_use = "futures do nothing unless you `.await` or poll them"]
+#[stable(feature = "future_poll_fn", since = "1.64.0")]
+pub struct PollFn<F> {
+ f: F,
+}
+
+#[stable(feature = "future_poll_fn", since = "1.64.0")]
+impl<F> Unpin for PollFn<F> {}
+
+#[stable(feature = "future_poll_fn", since = "1.64.0")]
+impl<F> fmt::Debug for PollFn<F> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("PollFn").finish()
+ }
+}
+
+#[stable(feature = "future_poll_fn", since = "1.64.0")]
+impl<T, F> Future for PollFn<F>
+where
+ F: FnMut(&mut Context<'_>) -> Poll<T>,
+{
+ type Output = T;
+
+ fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
+ (&mut self.f)(cx)
+ }
+}
diff --git a/library/core/src/future/ready.rs b/library/core/src/future/ready.rs
new file mode 100644
index 000000000..48f20f90a
--- /dev/null
+++ b/library/core/src/future/ready.rs
@@ -0,0 +1,46 @@
+use crate::future::Future;
+use crate::pin::Pin;
+use crate::task::{Context, Poll};
+
+/// A future that is immediately ready with a value.
+///
+/// This `struct` is created by [`ready()`]. See its
+/// documentation for more.
+#[stable(feature = "future_readiness_fns", since = "1.48.0")]
+#[derive(Debug, Clone)]
+#[must_use = "futures do nothing unless you `.await` or poll them"]
+pub struct Ready<T>(Option<T>);
+
+#[stable(feature = "future_readiness_fns", since = "1.48.0")]
+impl<T> Unpin for Ready<T> {}
+
+#[stable(feature = "future_readiness_fns", since = "1.48.0")]
+impl<T> Future for Ready<T> {
+ type Output = T;
+
+ #[inline]
+ fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<T> {
+ Poll::Ready(self.0.take().expect("`Ready` polled after completion"))
+ }
+}
+
+/// Creates a future that is immediately ready with a value.
+///
+/// Futures created through this function are functionally similar to those
+/// created through `async {}`. The main difference is that futures created
+/// through this function are named and implement `Unpin`.
+///
+/// # Examples
+///
+/// ```
+/// use std::future;
+///
+/// # async fn run() {
+/// let a = future::ready(1);
+/// assert_eq!(a.await, 1);
+/// # }
+/// ```
+#[stable(feature = "future_readiness_fns", since = "1.48.0")]
+pub fn ready<T>(t: T) -> Ready<T> {
+ Ready(Some(t))
+}