]> git.lizzy.rs Git - rust.git/blob - src/libstd/future.rs
Rollup merge of #58440 - gnzlbg:v6, r=japaric
[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::{Waker, Poll};
9 use core::ops::{Drop, Generator, GeneratorState};
10
11 #[doc(inline)]
12 pub use core::future::*;
13
14 /// Wrap a generator in a future.
15 ///
16 /// This function returns a `GenFuture` underneath, but hides it in `impl Trait` to give
17 /// better error messages (`impl Future` rather than `GenFuture<[closure.....]>`).
18 #[unstable(feature = "gen_future", issue = "50547")]
19 pub fn from_generator<T: Generator<Yield = ()>>(x: T) -> impl Future<Output = T::Return> {
20     GenFuture(x)
21 }
22
23 /// A wrapper around generators used to implement `Future` for `async`/`await` code.
24 #[unstable(feature = "gen_future", issue = "50547")]
25 #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
26 struct GenFuture<T: Generator<Yield = ()>>(T);
27
28 // We rely on the fact that async/await futures are immovable in order to create
29 // self-referential borrows in the underlying generator.
30 impl<T: Generator<Yield = ()>> !Unpin for GenFuture<T> {}
31
32 #[unstable(feature = "gen_future", issue = "50547")]
33 impl<T: Generator<Yield = ()>> Future for GenFuture<T> {
34     type Output = T::Return;
35     fn poll(self: Pin<&mut Self>, waker: &Waker) -> Poll<Self::Output> {
36         // Safe because we're !Unpin + !Drop mapping to a ?Unpin value
37         let gen = unsafe { Pin::map_unchecked_mut(self, |s| &mut s.0) };
38         set_task_waker(waker, || match gen.resume() {
39             GeneratorState::Yielded(()) => Poll::Pending,
40             GeneratorState::Complete(x) => Poll::Ready(x),
41         })
42     }
43 }
44
45 thread_local! {
46     static TLS_WAKER: Cell<Option<NonNull<Waker>>> = Cell::new(None);
47 }
48
49 struct SetOnDrop(Option<NonNull<Waker>>);
50
51 impl Drop for SetOnDrop {
52     fn drop(&mut self) {
53         TLS_WAKER.with(|tls_waker| {
54             tls_waker.set(self.0.take());
55         });
56     }
57 }
58
59 #[unstable(feature = "gen_future", issue = "50547")]
60 /// Sets the thread-local task context used by async/await futures.
61 pub fn set_task_waker<F, R>(waker: &Waker, f: F) -> R
62 where
63     F: FnOnce() -> R
64 {
65     let old_waker = TLS_WAKER.with(|tls_waker| {
66         tls_waker.replace(Some(NonNull::from(waker)))
67     });
68     let _reset_waker = SetOnDrop(old_waker);
69     f()
70 }
71
72 #[unstable(feature = "gen_future", issue = "50547")]
73 /// Retrieves the thread-local task waker used by async/await futures.
74 ///
75 /// This function acquires exclusive access to the task waker.
76 ///
77 /// Panics if no waker has been set or if the waker has already been
78 /// retrieved by a surrounding call to get_task_waker.
79 pub fn get_task_waker<F, R>(f: F) -> R
80 where
81     F: FnOnce(&Waker) -> R
82 {
83     let waker_ptr = TLS_WAKER.with(|tls_waker| {
84         // Clear the entry so that nested `get_task_waker` calls
85         // will fail or set their own value.
86         tls_waker.replace(None)
87     });
88     let _reset_waker = SetOnDrop(waker_ptr);
89
90     let waker_ptr = waker_ptr.expect(
91         "TLS Waker not set. This is a rustc bug. \
92         Please file an issue on https://github.com/rust-lang/rust.");
93     unsafe { f(waker_ptr.as_ref()) }
94 }
95
96 #[unstable(feature = "gen_future", issue = "50547")]
97 /// Polls a future in the current thread-local task waker.
98 pub fn poll_with_tls_waker<F>(f: Pin<&mut F>) -> Poll<F::Output>
99 where
100     F: Future
101 {
102     get_task_waker(|waker| F::poll(f, waker))
103 }