1 // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Asynchronous values.
14 use core::marker::Unpin;
16 use core::option::Option;
17 use core::ptr::NonNull;
18 use core::task::{LocalWaker, Poll};
19 use core::ops::{Drop, Generator, GeneratorState};
22 pub use core::future::*;
24 /// Wrap a future in a generator.
26 /// This function returns a `GenFuture` underneath, but hides it in `impl Trait` to give
27 /// better error messages (`impl Future` rather than `GenFuture<[closure.....]>`).
28 #[unstable(feature = "gen_future", issue = "50547")]
29 pub fn from_generator<T: Generator<Yield = ()>>(x: T) -> impl Future<Output = T::Return> {
33 /// A wrapper around generators used to implement `Future` for `async`/`await` code.
34 #[unstable(feature = "gen_future", issue = "50547")]
35 #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
36 struct GenFuture<T: Generator<Yield = ()>>(T);
38 // We rely on the fact that async/await futures are immovable in order to create
39 // self-referential borrows in the underlying generator.
40 impl<T: Generator<Yield = ()>> !Unpin for GenFuture<T> {}
42 #[unstable(feature = "gen_future", issue = "50547")]
43 impl<T: Generator<Yield = ()>> Future for GenFuture<T> {
44 type Output = T::Return;
45 fn poll(self: Pin<&mut Self>, lw: &LocalWaker) -> Poll<Self::Output> {
46 set_task_waker(lw, || match unsafe { Pin::get_mut_unchecked(self).0.resume() } {
47 GeneratorState::Yielded(()) => Poll::Pending,
48 GeneratorState::Complete(x) => Poll::Ready(x),
54 static TLS_WAKER: Cell<Option<NonNull<LocalWaker>>> = Cell::new(None);
57 struct SetOnDrop(Option<NonNull<LocalWaker>>);
59 impl Drop for SetOnDrop {
61 TLS_WAKER.with(|tls_waker| {
62 tls_waker.set(self.0.take());
67 #[unstable(feature = "gen_future", issue = "50547")]
68 /// Sets the thread-local task context used by async/await futures.
69 pub fn set_task_waker<F, R>(lw: &LocalWaker, f: F) -> R
73 let old_waker = TLS_WAKER.with(|tls_waker| {
74 tls_waker.replace(Some(NonNull::from(lw)))
76 let _reset_waker = SetOnDrop(old_waker);
80 #[unstable(feature = "gen_future", issue = "50547")]
81 /// Retrieves the thread-local task waker used by async/await futures.
83 /// This function acquires exclusive access to the task waker.
85 /// Panics if no waker has been set or if the waker has already been
86 /// retrieved by a surrounding call to get_task_waker.
87 pub fn get_task_waker<F, R>(f: F) -> R
89 F: FnOnce(&LocalWaker) -> R
91 let waker_ptr = TLS_WAKER.with(|tls_waker| {
92 // Clear the entry so that nested `get_task_waker` calls
93 // will fail or set their own value.
94 tls_waker.replace(None)
96 let _reset_waker = SetOnDrop(waker_ptr);
98 let waker_ptr = waker_ptr.expect(
99 "TLS LocalWaker not set. This is a rustc bug. \
100 Please file an issue on https://github.com/rust-lang/rust.");
101 unsafe { f(waker_ptr.as_ref()) }
104 #[unstable(feature = "gen_future", issue = "50547")]
105 /// Polls a future in the current thread-local task waker.
106 pub fn poll_with_tls_waker<F>(f: Pin<&mut F>) -> Poll<F::Output>
110 get_task_waker(|lw| F::poll(f, lw))