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