]> git.lizzy.rs Git - rust.git/blob - library/core/src/future/mod.rs
Some improvements to the async docs
[rust.git] / library / core / src / future / mod.rs
1 #![stable(feature = "futures_api", since = "1.36.0")]
2
3 //! Asynchronous basic functionality.
4 //!
5 //! Please see the fundamental [`async`] and [`await`] keywords and the [async book]
6 //! for more information on asynchronous programming in Rust.
7 //!
8 //! [`async`]: ../../std/keyword.async.html
9 //! [`await`]: ../../std/keyword.await.html
10 //! [async book]: https://rust-lang.github.io/async-book/
11
12 use crate::{
13     ops::{Generator, GeneratorState},
14     pin::Pin,
15     ptr::NonNull,
16     task::{Context, Poll},
17 };
18
19 mod future;
20 mod into_future;
21 mod pending;
22 mod poll_fn;
23 mod ready;
24
25 #[stable(feature = "futures_api", since = "1.36.0")]
26 pub use self::future::Future;
27
28 #[unstable(feature = "into_future", issue = "67644")]
29 pub use into_future::IntoFuture;
30
31 #[stable(feature = "future_readiness_fns", since = "1.48.0")]
32 pub use pending::{pending, Pending};
33 #[stable(feature = "future_readiness_fns", since = "1.48.0")]
34 pub use ready::{ready, Ready};
35
36 #[unstable(feature = "future_poll_fn", issue = "72302")]
37 pub use poll_fn::{poll_fn, PollFn};
38
39 /// This type is needed because:
40 ///
41 /// a) Generators cannot implement `for<'a, 'b> Generator<&'a mut Context<'b>>`, so we need to pass
42 ///    a raw pointer (see <https://github.com/rust-lang/rust/issues/68923>).
43 /// b) Raw pointers and `NonNull` aren't `Send` or `Sync`, so that would make every single future
44 ///    non-Send/Sync as well, and we don't want that.
45 ///
46 /// It also simplifies the HIR lowering of `.await`.
47 #[doc(hidden)]
48 #[unstable(feature = "gen_future", issue = "50547")]
49 #[derive(Debug, Copy, Clone)]
50 pub struct ResumeTy(NonNull<Context<'static>>);
51
52 #[unstable(feature = "gen_future", issue = "50547")]
53 unsafe impl Send for ResumeTy {}
54
55 #[unstable(feature = "gen_future", issue = "50547")]
56 unsafe impl Sync for ResumeTy {}
57
58 /// Wrap a generator in a future.
59 ///
60 /// This function returns a `GenFuture` underneath, but hides it in `impl Trait` to give
61 /// better error messages (`impl Future` rather than `GenFuture<[closure.....]>`).
62 // This is `const` to avoid extra errors after we recover from `const async fn`
63 #[lang = "from_generator"]
64 #[doc(hidden)]
65 #[unstable(feature = "gen_future", issue = "50547")]
66 #[rustc_const_unstable(feature = "gen_future", issue = "50547")]
67 #[inline]
68 pub const fn from_generator<T>(gen: T) -> impl Future<Output = T::Return>
69 where
70     T: Generator<ResumeTy, Yield = ()>,
71 {
72     #[rustc_diagnostic_item = "gen_future"]
73     struct GenFuture<T: Generator<ResumeTy, Yield = ()>>(T);
74
75     // We rely on the fact that async/await futures are immovable in order to create
76     // self-referential borrows in the underlying generator.
77     impl<T: Generator<ResumeTy, Yield = ()>> !Unpin for GenFuture<T> {}
78
79     impl<T: Generator<ResumeTy, Yield = ()>> Future for GenFuture<T> {
80         type Output = T::Return;
81         fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
82             // SAFETY: Safe because we're !Unpin + !Drop, and this is just a field projection.
83             let gen = unsafe { Pin::map_unchecked_mut(self, |s| &mut s.0) };
84
85             // Resume the generator, turning the `&mut Context` into a `NonNull` raw pointer. The
86             // `.await` lowering will safely cast that back to a `&mut Context`.
87             match gen.resume(ResumeTy(NonNull::from(cx).cast::<Context<'static>>())) {
88                 GeneratorState::Yielded(()) => Poll::Pending,
89                 GeneratorState::Complete(x) => Poll::Ready(x),
90             }
91         }
92     }
93
94     GenFuture(gen)
95 }
96
97 #[lang = "get_context"]
98 #[doc(hidden)]
99 #[unstable(feature = "gen_future", issue = "50547")]
100 #[must_use]
101 #[inline]
102 pub unsafe fn get_context<'a, 'b>(cx: ResumeTy) -> &'a mut Context<'b> {
103     // SAFETY: the caller must guarantee that `cx.0` is a valid pointer
104     // that fulfills all the requirements for a mutable reference.
105     unsafe { &mut *cx.0.as_ptr().cast() }
106 }