1 //! Asynchronous values.
4 use core::marker::Unpin;
6 use core::option::Option;
7 use core::ptr::NonNull;
8 use core::task::{Context, Poll};
9 use core::ops::{Drop, Generator, GeneratorState};
12 #[stable(feature = "futures_api", since = "1.36.0")]
13 pub use core::future::*;
15 /// Wrap a generator in a future.
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> {
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);
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> {}
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),
47 static TLS_CX: Cell<Option<NonNull<Context<'static>>>> = Cell::new(None);
50 struct SetOnDrop(Option<NonNull<Context<'static>>>);
52 impl Drop for SetOnDrop {
54 TLS_CX.with(|tls_cx| {
55 tls_cx.set(self.0.take());
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
66 // transmute the context's lifetime to 'static so we can store it.
68 core::mem::transmute::<&mut Context<'_>, &mut Context<'static>>(cx)
70 let old_cx = TLS_CX.with(|tls_cx| {
71 tls_cx.replace(Some(NonNull::from(cx)))
73 let _reset = SetOnDrop(old_cx);
77 #[unstable(feature = "gen_future", issue = "50547")]
78 /// Retrieves the thread-local task context used by async/await futures.
80 /// This function acquires exclusive access to the task context.
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
86 F: FnOnce(&mut Context<'_>) -> R
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.
93 let _reset = SetOnDrop(cx_ptr);
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.");
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.
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()) }
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>
114 get_task_context(|cx| F::poll(f, cx))