futures_core/future/mod.rs
1//! Futures.
2
3use Poll;
4use task;
5
6mod option;
7pub use self::option::FutureOption;
8#[path = "result.rs"]
9mod result_;
10pub use self::result_::{result, ok, err, FutureResult};
11#[cfg(feature = "either")]
12mod either;
13
14/// A future represents an asychronous computation that may fail.
15///
16/// A future is like a `Result` value that may not have finished computing
17/// yet. This kind of "asynchronous value" makes it possible for a thread to
18/// continue doing useful work while it waits for the value to become available.
19///
20/// The ergonomics and implementation of the `Future` trait are very similar to
21/// the `Iterator` trait in that there is just one method you need to
22/// implement, but you get a whole lot of others for free as a result. These
23/// other methods allow you to chain together large computations based on
24/// futures, which will automatically handle asynchrony for you.
25///
26/// # The `poll` method
27///
28/// The core method of future, `poll`, *attempts* to resolve the future into a
29/// final value. This method does not block if the value is not ready. Instead,
30/// the current task is scheduled to be woken up when it's possible to make
31/// further progress by `poll`ing again. The wake up is performed using
32/// `cx.waker()`, a handle for waking up the current task.
33///
34/// When using a future, you generally won't call `poll` directly, but instead
35/// use combinators to build up asynchronous computations. A complete
36/// computation can then be spawned onto an
37/// [executor](../futures_core/executor/trait.Executor.html) as a new, independent
38/// task that will automatically be `poll`ed to completion.
39///
40/// # Combinators
41///
42/// Like iterators, futures provide a large number of combinators to work with
43/// futures to express computations in a much more natural method than
44/// scheduling a number of callbacks. As with iterators, the combinators are
45/// zero-cost: they compile away. You can find the combinators in the
46/// [future-util](https://docs.rs/futures-util) crate.
47pub trait Future {
48 /// A successful value
49 type Item;
50
51 /// An error
52 type Error;
53
54 /// Attempt to resolve the future to a final value, registering
55 /// the current task for wakeup if the value is not yet available.
56 ///
57 /// # Return value
58 ///
59 /// This function returns:
60 ///
61 /// - `Ok(Async::Pending)` if the future is not ready yet
62 /// - `Ok(Async::Ready(val))` with the result `val` of this future if it finished
63 /// successfully.
64 /// - `Err(err)` if the future is finished but resolved to an error `err`.
65 ///
66 /// Once a future has finished, clients should not `poll` it again.
67 ///
68 /// When a future is not ready yet, `poll` returns
69 /// [`Async::Pending`](::Async). The future will *also* register the
70 /// interest of the current task in the value being produced. For example,
71 /// if the future represents the availability of data on a socket, then the
72 /// task is recorded so that when data arrives, it is woken up (via
73 /// [`cx.waker()`](::task::Context::waker). Once a task has been woken up,
74 /// it should attempt to `poll` the future again, which may or may not
75 /// produce a final value.
76 ///
77 /// Note that if `Pending` is returned it only means that the *current* task
78 /// (represented by the argument `cx`) will receive a notification. Tasks
79 /// from previous calls to `poll` will *not* receive notifications.
80 ///
81 /// # Runtime characteristics
82 ///
83 /// Futures alone are *inert*; they must be *actively* `poll`ed to make
84 /// progress, meaning that each time the current task is woken up, it should
85 /// actively re-`poll` pending futures that it still has an interest in.
86 /// Usually this is done by building up a large computation as a single
87 /// future (using combinators), then spawning that future as a *task* onto
88 /// an [executor](../futures_core/executor/trait.Executor.html). Executors
89 /// ensure that each task is `poll`ed every time a future internal to that
90 /// task is ready to make progress.
91 ///
92 /// The `poll` function is not called repeatedly in a tight loop for
93 /// futures, but only whenever the future itself is ready, as signaled via
94 /// [`cx.waker()`](::task::Context::waker). If you're familiar with the
95 /// `poll(2)` or `select(2)` syscalls on Unix it's worth noting that futures
96 /// typically do *not* suffer the same problems of "all wakeups must poll
97 /// all events"; they are more like `epoll(4)`.
98 ///
99 /// An implementation of `poll` should strive to return quickly, and must
100 /// *never* block. Returning quickly prevents unnecessarily clogging up
101 /// threads or event loops. If it is known ahead of time that a call to
102 /// `poll` may end up taking awhile, the work should be offloaded to a
103 /// thread pool (or something similar) to ensure that `poll` can return
104 /// quickly.
105 ///
106 /// # Errors
107 ///
108 /// This future may have failed to finish the computation, in which case
109 /// the `Err` variant will be returned with an appropriate payload of an
110 /// error.
111 ///
112 /// # Panics
113 ///
114 /// Once a future has completed (returned `Ready` or `Err` from `poll`),
115 /// then any future calls to `poll` may panic, block forever, or otherwise
116 /// cause bad behavior. The `Future` trait itself provides no guarantees
117 /// about the behavior of `poll` after a future has completed.
118 ///
119 /// Callers who may call `poll` too many times may want to consider using
120 /// the `fuse` adaptor which defines the behavior of `poll`, but comes with
121 /// a little bit of extra cost.
122 fn poll(&mut self, cx: &mut task::Context) -> Poll<Self::Item, Self::Error>;
123}
124
125impl<'a, F: ?Sized + Future> Future for &'a mut F {
126 type Item = F::Item;
127 type Error = F::Error;
128
129 fn poll(&mut self, cx: &mut task::Context) -> Poll<Self::Item, Self::Error> {
130 (**self).poll(cx)
131 }
132}
133
134if_std! {
135 impl<F: ?Sized + Future> Future for ::std::boxed::Box<F> {
136 type Item = F::Item;
137 type Error = F::Error;
138
139 fn poll(&mut self, cx: &mut task::Context) -> Poll<Self::Item, Self::Error> {
140 (**self).poll(cx)
141 }
142 }
143
144 #[cfg(feature = "nightly")]
145 impl<F: ?Sized + Future> Future for ::std::boxed::PinBox<F> {
146 type Item = F::Item;
147 type Error = F::Error;
148
149 fn poll(&mut self, cx: &mut task::Context) -> Poll<Self::Item, Self::Error> {
150 unsafe { ::core::mem::PinMut::get_mut_unchecked(self.as_pin_mut()).poll(cx) }
151 }
152 }
153
154 impl<F: Future> Future for ::std::panic::AssertUnwindSafe<F> {
155 type Item = F::Item;
156 type Error = F::Error;
157
158 fn poll(&mut self, cx: &mut task::Context) -> Poll<F::Item, F::Error> {
159 self.0.poll(cx)
160 }
161 }
162}
163
164/// Types that can be converted into a future.
165///
166/// This trait is very similar to the `IntoIterator` trait.
167pub trait IntoFuture {
168 /// The future that this type can be converted into.
169 type Future: Future<Item=Self::Item, Error=Self::Error>;
170
171 /// The item that the future may resolve with.
172 type Item;
173 /// The error that the future may resolve with.
174 type Error;
175
176 /// Consumes this object and produces a future.
177 fn into_future(self) -> Self::Future;
178}
179
180impl<F> IntoFuture for F where F: Future {
181 type Future = Self;
182 type Item = <Self as Future>::Item;
183 type Error = <Self as Future>::Error;
184 fn into_future(self) -> Self { self }
185}