]> git.lizzy.rs Git - rust.git/blob - src/libcore/future/future.rs
ea54b5a66996af925877ea3e810ddc8885ad1981
[rust.git] / src / libcore / future / future.rs
1 #![unstable(feature = "futures_api",
2             reason = "futures in libcore are unstable",
3             issue = "50547")]
4
5 use crate::marker::Unpin;
6 use crate::ops;
7 use crate::pin::Pin;
8 use crate::task::{Context, Poll};
9
10 /// A future represents an asynchronous computation.
11 ///
12 /// A future is a value that may not have finished computing yet. This kind of
13 /// "asynchronous value" makes it possible for a thread to continue doing useful
14 /// work while it waits for the value to become available.
15 ///
16 /// # The `poll` method
17 ///
18 /// The core method of future, `poll`, *attempts* to resolve the future into a
19 /// final value. This method does not block if the value is not ready. Instead,
20 /// the current task is scheduled to be woken up when it's possible to make
21 /// further progress by `poll`ing again. The wake up is performed using
22 /// the `waker` argument of the `poll()` method, which is a handle for waking
23 /// up the current task.
24 ///
25 /// When using a future, you generally won't call `poll` directly, but instead
26 /// `await!` the value.
27 #[doc(spotlight)]
28 #[must_use = "futures do nothing unless polled"]
29 pub trait Future {
30     /// The type of value produced on completion.
31     type Output;
32
33     /// Attempt to resolve the future to a final value, registering
34     /// the current task for wakeup if the value is not yet available.
35     ///
36     /// # Return value
37     ///
38     /// This function returns:
39     ///
40     /// - [`Poll::Pending`] if the future is not ready yet
41     /// - [`Poll::Ready(val)`] with the result `val` of this future if it
42     ///   finished successfully.
43     ///
44     /// Once a future has finished, clients should not `poll` it again.
45     ///
46     /// When a future is not ready yet, `poll` returns `Poll::Pending` and
47     /// stores a clone of the [`Waker`] copied from the current [`Context`].
48     /// This [`Waker`] is then woken once the future can make progress.
49     /// For example, a future waiting for a socket to become
50     /// readable would call `.clone()` on the [`Waker`] and store it.
51     /// When a signal arrives elsewhere indicating that the socket is readable,
52     /// `[Waker::wake]` is called and the socket future's task is awoken.
53     /// Once a task has been woken up, it should attempt to `poll` the future
54     /// again, which may or may not produce a final value.
55     ///
56     /// Note that on multiple calls to `poll`, only the most recent
57     /// [`Waker`] passed to `poll` should be scheduled to receive a
58     /// wakeup.
59     ///
60     /// # Runtime characteristics
61     ///
62     /// Futures alone are *inert*; they must be *actively* `poll`ed to make
63     /// progress, meaning that each time the current task is woken up, it should
64     /// actively re-`poll` pending futures that it still has an interest in.
65     ///
66     /// The `poll` function is not called repeatedly in a tight loop -- instead,
67     /// it should only be called when the future indicates that it is ready to
68     /// make progress (by calling `wake()`). If you're familiar with the
69     /// `poll(2)` or `select(2)` syscalls on Unix it's worth noting that futures
70     /// typically do *not* suffer the same problems of "all wakeups must poll
71     /// all events"; they are more like `epoll(4)`.
72     ///
73     /// An implementation of `poll` should strive to return quickly, and should
74     /// not block. Returning quickly prevents unnecessarily clogging up
75     /// threads or event loops. If it is known ahead of time that a call to
76     /// `poll` may end up taking awhile, the work should be offloaded to a
77     /// thread pool (or something similar) to ensure that `poll` can return
78     /// quickly.
79     ///
80     /// An implementation of `poll` may also never cause memory unsafety.
81     ///
82     /// # Panics
83     ///
84     /// Once a future has completed (returned `Ready` from `poll`),
85     /// then any future calls to `poll` may panic, block forever, or otherwise
86     /// cause any kind of bad behavior except causing memory unsafety.
87     /// The `Future` trait itself provides no guarantees about the behavior
88     /// of `poll` after a future has completed.
89     ///
90     /// [`Poll::Pending`]: ../task/enum.Poll.html#variant.Pending
91     /// [`Poll::Ready(val)`]: ../task/enum.Poll.html#variant.Ready
92     /// [`Context`]: ../task/struct.Context.html
93     /// [`Waker`]: ../task/struct.Waker.html
94     /// [`Waker::wake`]: ../task/struct.Waker.html#method.wake
95     fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
96 }
97
98 impl<F: ?Sized + Future + Unpin> Future for &mut F {
99     type Output = F::Output;
100
101     fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
102         F::poll(Pin::new(&mut **self), cx)
103     }
104 }
105
106 impl<P> Future for Pin<P>
107 where
108     P: Unpin + ops::DerefMut,
109     P::Target: Future,
110 {
111     type Output = <<P as ops::Deref>::Target as Future>::Output;
112
113     fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
114         Pin::get_mut(self).as_mut().poll(cx)
115     }
116 }