future.rs - source
Description: Source of the Rust file `library/core/src/future/future.rs`.

#
core/future/
future.rs

    1#![stable(feature = "futures_api", since = "1.36.0")]
    2
    3use crate::ops;
    4use crate::pin::Pin;
    5use crate::task::{Context, Poll};
    6
    7/// A future represents an asynchronous computation, commonly obtained by use of
    8/// [`async`].
    9///
    10/// A future is a value that might not have finished computing yet. This kind of
    11/// "asynchronous value" makes it possible for a thread to continue doing useful
    12/// work while it waits for the value to become available.
    13///
    14/// # The `poll` method
    15///
    16/// The core method of future, `poll`, *attempts* to resolve the future into a
    17/// final value. This method does not block if the value is not ready. Instead,
    18/// the current task is scheduled to be woken up when it's possible to make
    19/// further progress by `poll`ing again. The `context` passed to the `poll`
    20/// method can provide a [`Waker`], which is a handle for waking up the current
    21/// task.
    22///
    23/// When using a future, you generally won't call `poll` directly, but instead
    24/// `.await` the value.
    25///
    26/// [`async`]: ../../std/keyword.async.html
    27/// [`Waker`]: crate::task::Waker
    28#[doc(notable_trait)]
    29#[doc(search_unbox)]
    30#[must_use = "futures do nothing unless you `.await` or poll them"]
    31#[stable(feature = "futures_api", since = "1.36.0")]
    32#[lang = "future_trait"]
    33#[diagnostic::on_unimplemented(
    34    label = "`{Self}` is not a future",
    35    message = "`{Self}` is not a future"
    36)]
    37pub trait Future {
    38    /// The type of value produced on completion.
    39    #[stable(feature = "futures_api", since = "1.36.0")]
    40    #[lang = "future_output"]
    41    type Output;
    42
    43    /// Attempts to resolve the future to a final value, registering
    44    /// the current task for wakeup if the value is not yet available.
    45    ///
    46    /// # Return value
    47    ///
    48    /// This function returns:
    49    ///
    50    /// - [`Poll::Pending`] if the future is not ready yet
    51    /// - [`Poll::Ready(val)`] with the result `val` of this future if it
    52    ///   finished successfully.
    53    ///
    54    /// Once a future has finished, clients should not `poll` it again.
    55    ///
    56    /// When a future is not ready yet, `poll` returns `Poll::Pending` and
    57    /// stores a clone of the [`Waker`] copied from the current [`Context`].
    58    /// This [`Waker`] is then woken once the future can make progress.
    59    /// For example, a future waiting for a socket to become
    60    /// readable would call `.clone()` on the [`Waker`] and store it.
    61    /// When a signal arrives elsewhere indicating that the socket is readable,
    62    /// [`Waker::wake`] is called and the socket future's task is awoken.
    63    /// Once a task has been woken up, it should attempt to `poll` the future
    64    /// again, which may or may not produce a final value.
    65    ///
    66    /// Note that on multiple calls to `poll`, only the [`Waker`] from the
    67    /// [`Context`] passed to the most recent call should be scheduled to
    68    /// receive a wakeup.
    69    ///
    70    /// # Runtime characteristics
    71    ///
    72    /// Futures alone are *inert*; they must be *actively* `poll`ed for the
    73    /// underlying computation to make progress, meaning that each time the
    74    /// current task is woken up, it should actively re-`poll` pending futures
    75    /// that it still has an interest in.
    76    ///
    77    /// Having said that, some Futures may represent a value that is being
    78    /// computed in a different task. In this case, the future's underlying
    79    /// computation is simply acting as a conduit for a value being computed
    80    /// by that other task, which will proceed independently of the Future.
    81    /// Futures of this kind are typically obtained when spawning a new task into an
    82    /// async runtime.
    83    ///
    84    /// The `poll` function should not be called repeatedly in a tight loop --
    85    /// instead, it should only be called when the future indicates that it is
    86    /// ready to make progress (by calling `wake()`). If you're familiar with the
    87    /// `poll(2)` or `select(2)` syscalls on Unix it's worth noting that futures
    88    /// typically do *not* suffer the same problems of "all wakeups must poll
    89    /// all events"; they are more like `epoll(4)`.
    90    ///
    91    /// An implementation of `poll` should strive to return quickly, and should
    92    /// not block. Returning quickly prevents unnecessarily clogging up
    93    /// threads or event loops. If it is known ahead of time that a call to
    94    /// `poll` may end up taking a while, the work should be offloaded to a
    95    /// thread pool (or something similar) to ensure that `poll` can return
    96    /// quickly.
    97    ///
    98    /// # Panics
    99    ///
    100    /// Once a future has completed (returned `Ready` from `poll`), calling its
    101    /// `poll` method again may panic, block forever, or cause other kinds of
    102    /// problems; the `Future` trait places no requirements on the effects of
    103    /// such a call. However, as the `poll` method is not marked `unsafe`,
    104    /// Rust's usual rules apply: calls must never cause undefined behavior
    105    /// (memory corruption, incorrect use of `unsafe` functions, or the like),
    106    /// regardless of the future's state.
    107    ///
    108    /// [`Poll::Ready(val)`]: Poll::Ready
    109    /// [`Waker`]: crate::task::Waker
    110    /// [`Waker::wake`]: crate::task::Waker::wake
    111    #[lang = "poll"]
    112    #[stable(feature = "futures_api", since = "1.36.0")]
    113    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
    114}
    115
    116#[stable(feature = "futures_api", since = "1.36.0")]
    117impl<F: ?Sized + Future + Unpin> Future for &mut F {
    118    type Output = F::Output;
    119
    120    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
    121        F::poll(Pin::new(&mut **self), cx)
    122    }
    123}
    124
    125#[stable(feature = "futures_api", since = "1.36.0")]
    126impl<P> Future for Pin<P>
    127where
    128    P: ops::DerefMut<Target: Future>,
    129{
    130    type Output = <<P as ops::Deref>::Target as Future>::Output;
    131
    132    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
    133        <P::Target as Future>::poll(self.as_deref_mut(), cx)
    134    }
    135}