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