]> git.lizzy.rs Git - rust.git/blob - library/core/src/future/mod.rs
Auto merge of #105698 - joboet:unsupported_threads_once, r=thomcc
[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::ptr::NonNull;
13 use crate::task::Context;
14
15 mod future;
16 mod into_future;
17 mod join;
18 mod pending;
19 mod poll_fn;
20 mod ready;
21
22 #[stable(feature = "futures_api", since = "1.36.0")]
23 pub use self::future::Future;
24
25 #[unstable(feature = "future_join", issue = "91642")]
26 pub use self::join::join;
27
28 #[stable(feature = "into_future", since = "1.64.0")]
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 #[stable(feature = "future_poll_fn", since = "1.64.0")]
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 // FIXME(swatinem): This type can be removed when bumping the bootstrap compiler
48 #[doc(hidden)]
49 #[unstable(feature = "gen_future", issue = "50547")]
50 #[derive(Debug, Copy, Clone)]
51 pub struct ResumeTy(NonNull<Context<'static>>);
52
53 #[unstable(feature = "gen_future", issue = "50547")]
54 unsafe impl Send for ResumeTy {}
55
56 #[unstable(feature = "gen_future", issue = "50547")]
57 unsafe impl Sync for ResumeTy {}
58
59 /// Wrap a generator in a future.
60 ///
61 /// This function returns a `GenFuture` underneath, but hides it in `impl Trait` to give
62 /// better error messages (`impl Future` rather than `GenFuture<[closure.....]>`).
63 // This is `const` to avoid extra errors after we recover from `const async fn`
64 // FIXME(swatinem): This fn can be removed when bumping the bootstrap compiler
65 #[cfg_attr(bootstrap, lang = "from_generator")]
66 #[doc(hidden)]
67 #[unstable(feature = "gen_future", issue = "50547")]
68 #[rustc_const_unstable(feature = "gen_future", issue = "50547")]
69 #[inline]
70 pub const fn from_generator<T>(gen: T) -> impl Future<Output = T::Return>
71 where
72     T: crate::ops::Generator<ResumeTy, Yield = ()>,
73 {
74     use crate::{
75         ops::{Generator, GeneratorState},
76         pin::Pin,
77         task::Poll,
78     };
79
80     #[rustc_diagnostic_item = "gen_future"]
81     struct GenFuture<T: Generator<ResumeTy, Yield = ()>>(T);
82
83     // We rely on the fact that async/await futures are immovable in order to create
84     // self-referential borrows in the underlying generator.
85     impl<T: Generator<ResumeTy, Yield = ()>> !Unpin for GenFuture<T> {}
86
87     impl<T: Generator<ResumeTy, Yield = ()>> Future for GenFuture<T> {
88         type Output = T::Return;
89         #[track_caller]
90         fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
91             // SAFETY: Safe because we're !Unpin + !Drop, and this is just a field projection.
92             let gen = unsafe { Pin::map_unchecked_mut(self, |s| &mut s.0) };
93
94             // Resume the generator, turning the `&mut Context` into a `NonNull` raw pointer. The
95             // `.await` lowering will safely cast that back to a `&mut Context`.
96             match gen.resume(ResumeTy(NonNull::from(cx).cast::<Context<'static>>())) {
97                 GeneratorState::Yielded(()) => Poll::Pending,
98                 GeneratorState::Complete(x) => Poll::Ready(x),
99             }
100         }
101     }
102
103     GenFuture(gen)
104 }
105
106 // FIXME(swatinem): This fn can be removed when bumping the bootstrap compiler
107 #[cfg_attr(bootstrap, lang = "get_context")]
108 #[doc(hidden)]
109 #[unstable(feature = "gen_future", issue = "50547")]
110 #[must_use]
111 #[inline]
112 pub unsafe fn get_context<'a, 'b>(cx: ResumeTy) -> &'a mut Context<'b> {
113     // SAFETY: the caller must guarantee that `cx.0` is a valid pointer
114     // that fulfills all the requirements for a mutable reference.
115     unsafe { &mut *cx.0.as_ptr().cast() }
116 }
117
118 // FIXME(swatinem): This fn is currently needed to work around shortcomings
119 // in type and lifetime inference.
120 // See the comment at the bottom of `LoweringContext::make_async_expr` and
121 // <https://github.com/rust-lang/rust/issues/104826>.
122 #[cfg_attr(not(bootstrap), lang = "identity_future")]
123 #[doc(hidden)]
124 #[unstable(feature = "gen_future", issue = "50547")]
125 #[inline]
126 pub const fn identity_future<O, Fut: Future<Output = O>>(f: Fut) -> Fut {
127     f
128 }