]> git.lizzy.rs Git - rust.git/blob - src/libstd/future.rs
Rollup merge of #70038 - DutchGhost:const-forget-tests, r=RalfJung
[rust.git] / src / libstd / future.rs
1 //! Asynchronous values.
2
3 #[cfg(bootstrap)]
4 use core::{
5     cell::Cell,
6     marker::Unpin,
7     ops::{Drop, Generator, GeneratorState},
8     pin::Pin,
9     ptr::NonNull,
10     task::{Context, Poll},
11 };
12
13 #[doc(inline)]
14 #[stable(feature = "futures_api", since = "1.36.0")]
15 pub use core::future::*;
16
17 /// Wrap a generator in a future.
18 ///
19 /// This function returns a `GenFuture` underneath, but hides it in `impl Trait` to give
20 /// better error messages (`impl Future` rather than `GenFuture<[closure.....]>`).
21 // This is `const` to avoid extra errors after we recover from `const async fn`
22 #[cfg(bootstrap)]
23 #[doc(hidden)]
24 #[unstable(feature = "gen_future", issue = "50547")]
25 pub const fn from_generator<T: Generator<Yield = ()>>(x: T) -> impl Future<Output = T::Return> {
26     GenFuture(x)
27 }
28
29 /// A wrapper around generators used to implement `Future` for `async`/`await` code.
30 #[cfg(bootstrap)]
31 #[doc(hidden)]
32 #[unstable(feature = "gen_future", issue = "50547")]
33 #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
34 struct GenFuture<T: Generator<Yield = ()>>(T);
35
36 // We rely on the fact that async/await futures are immovable in order to create
37 // self-referential borrows in the underlying generator.
38 #[cfg(bootstrap)]
39 impl<T: Generator<Yield = ()>> !Unpin for GenFuture<T> {}
40
41 #[cfg(bootstrap)]
42 #[doc(hidden)]
43 #[unstable(feature = "gen_future", issue = "50547")]
44 impl<T: Generator<Yield = ()>> Future for GenFuture<T> {
45     type Output = T::Return;
46     fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
47         // Safe because we're !Unpin + !Drop mapping to a ?Unpin value
48         let gen = unsafe { Pin::map_unchecked_mut(self, |s| &mut s.0) };
49         let _guard = unsafe { set_task_context(cx) };
50         match gen.resume(()) {
51             GeneratorState::Yielded(()) => Poll::Pending,
52             GeneratorState::Complete(x) => Poll::Ready(x),
53         }
54     }
55 }
56
57 #[cfg(bootstrap)]
58 thread_local! {
59     static TLS_CX: Cell<Option<NonNull<Context<'static>>>> = Cell::new(None);
60 }
61
62 #[cfg(bootstrap)]
63 struct SetOnDrop(Option<NonNull<Context<'static>>>);
64
65 #[cfg(bootstrap)]
66 impl Drop for SetOnDrop {
67     fn drop(&mut self) {
68         TLS_CX.with(|tls_cx| {
69             tls_cx.set(self.0.take());
70         });
71     }
72 }
73
74 // Safety: the returned guard must drop before `cx` is dropped and before
75 // any previous guard is dropped.
76 #[cfg(bootstrap)]
77 unsafe fn set_task_context(cx: &mut Context<'_>) -> SetOnDrop {
78     // transmute the context's lifetime to 'static so we can store it.
79     let cx = core::mem::transmute::<&mut Context<'_>, &mut Context<'static>>(cx);
80     let old_cx = TLS_CX.with(|tls_cx| tls_cx.replace(Some(NonNull::from(cx))));
81     SetOnDrop(old_cx)
82 }
83
84 #[cfg(bootstrap)]
85 #[doc(hidden)]
86 #[unstable(feature = "gen_future", issue = "50547")]
87 /// Polls a future in the current thread-local task waker.
88 pub fn poll_with_tls_context<F>(f: Pin<&mut F>) -> Poll<F::Output>
89 where
90     F: Future,
91 {
92     let cx_ptr = TLS_CX.with(|tls_cx| {
93         // Clear the entry so that nested `get_task_waker` calls
94         // will fail or set their own value.
95         tls_cx.replace(None)
96     });
97     let _reset = SetOnDrop(cx_ptr);
98
99     let mut cx_ptr = cx_ptr.expect(
100         "TLS Context not set. This is a rustc bug. \
101         Please file an issue on https://github.com/rust-lang/rust.",
102     );
103
104     // Safety: we've ensured exclusive access to the context by
105     // removing the pointer from TLS, only to be replaced once
106     // we're done with it.
107     //
108     // The pointer that was inserted came from an `&mut Context<'_>`,
109     // so it is safe to treat as mutable.
110     unsafe { F::poll(f, cx_ptr.as_mut()) }
111 }