]> git.lizzy.rs Git - rust.git/blob - library/core/src/future/future.rs
Auto merge of #94144 - est31:let_else_trait_selection, r=cjgillot
[rust.git] / library / core / src / future / future.rs
1 #![stable(feature = "futures_api", since = "1.36.0")]
2
3 use crate::marker::Unpin;
4 use crate::ops;
5 use crate::pin::Pin;
6 use crate::task::{Context, Poll};
7
8 /// A future represents an asynchronous computation obtained by use of [`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 #[must_use = "futures do nothing unless you `.await` or poll them"]
30 #[stable(feature = "futures_api", since = "1.36.0")]
31 #[lang = "future_trait"]
32 #[rustc_on_unimplemented(
33     label = "`{Self}` is not a future",
34     message = "`{Self}` is not a future",
35     note = "{Self} must be a future or must implement `IntoFuture` to be awaited"
36 )]
37 pub trait Future {
38     /// The type of value produced on completion.
39     #[stable(feature = "futures_api", since = "1.36.0")]
40     type Output;
41
42     /// Attempt to resolve the future to a final value, registering
43     /// the current task for wakeup if the value is not yet available.
44     ///
45     /// # Return value
46     ///
47     /// This function returns:
48     ///
49     /// - [`Poll::Pending`] if the future is not ready yet
50     /// - [`Poll::Ready(val)`] with the result `val` of this future if it
51     ///   finished successfully.
52     ///
53     /// Once a future has finished, clients should not `poll` it again.
54     ///
55     /// When a future is not ready yet, `poll` returns `Poll::Pending` and
56     /// stores a clone of the [`Waker`] copied from the current [`Context`].
57     /// This [`Waker`] is then woken once the future can make progress.
58     /// For example, a future waiting for a socket to become
59     /// readable would call `.clone()` on the [`Waker`] and store it.
60     /// When a signal arrives elsewhere indicating that the socket is readable,
61     /// [`Waker::wake`] is called and the socket future's task is awoken.
62     /// Once a task has been woken up, it should attempt to `poll` the future
63     /// again, which may or may not produce a final value.
64     ///
65     /// Note that on multiple calls to `poll`, only the [`Waker`] from the
66     /// [`Context`] passed to the most recent call should be scheduled to
67     /// receive a wakeup.
68     ///
69     /// # Runtime characteristics
70     ///
71     /// Futures alone are *inert*; they must be *actively* `poll`ed to make
72     /// progress, meaning that each time the current task is woken up, it should
73     /// actively re-`poll` pending futures that it still has an interest in.
74     ///
75     /// The `poll` function is not called repeatedly in a tight loop -- instead,
76     /// it should only be called when the future indicates that it is ready to
77     /// make progress (by calling `wake()`). If you're familiar with the
78     /// `poll(2)` or `select(2)` syscalls on Unix it's worth noting that futures
79     /// typically do *not* suffer the same problems of "all wakeups must poll
80     /// all events"; they are more like `epoll(4)`.
81     ///
82     /// An implementation of `poll` should strive to return quickly, and should
83     /// not block. Returning quickly prevents unnecessarily clogging up
84     /// threads or event loops. If it is known ahead of time that a call to
85     /// `poll` may end up taking awhile, the work should be offloaded to a
86     /// thread pool (or something similar) to ensure that `poll` can return
87     /// quickly.
88     ///
89     /// # Panics
90     ///
91     /// Once a future has completed (returned `Ready` from `poll`), calling its
92     /// `poll` method again may panic, block forever, or cause other kinds of
93     /// problems; the `Future` trait places no requirements on the effects of
94     /// such a call. However, as the `poll` method is not marked `unsafe`,
95     /// Rust's usual rules apply: calls must never cause undefined behavior
96     /// (memory corruption, incorrect use of `unsafe` functions, or the like),
97     /// regardless of the future's state.
98     ///
99     /// [`Poll::Ready(val)`]: Poll::Ready
100     /// [`Waker`]: crate::task::Waker
101     /// [`Waker::wake`]: crate::task::Waker::wake
102     #[lang = "poll"]
103     #[stable(feature = "futures_api", since = "1.36.0")]
104     fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
105 }
106
107 #[stable(feature = "futures_api", since = "1.36.0")]
108 impl<F: ?Sized + Future + Unpin> Future for &mut F {
109     type Output = F::Output;
110
111     fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
112         F::poll(Pin::new(&mut **self), cx)
113     }
114 }
115
116 #[stable(feature = "futures_api", since = "1.36.0")]
117 impl<P> Future for Pin<P>
118 where
119     P: ops::DerefMut<Target: Future>,
120 {
121     type Output = <<P as ops::Deref>::Target as Future>::Output;
122
123     fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
124         <P::Target as Future>::poll(self.as_deref_mut(), cx)
125     }
126 }