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.....]>`).
20 #[unstable(feature = "gen_future", issue = "50547")]
21 pub fn from_generator<T: Generator<Yield = ()>>(x: T) -> impl Future<Output = T::Return> {
25 /// A wrapper around generators used to implement `Future` for `async`/`await` code.
27 #[unstable(feature = "gen_future", issue = "50547")]
28 #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
29 #[cfg_attr(not(test), rustc_diagnostic_item = "gen_future")]
30 struct GenFuture<T: Generator<Yield = ()>>(T);
32 // We rely on the fact that async/await futures are immovable in order to create
33 // self-referential borrows in the underlying generator.
34 impl<T: Generator<Yield = ()>> !Unpin for GenFuture<T> {}
37 #[unstable(feature = "gen_future", issue = "50547")]
38 impl<T: Generator<Yield = ()>> Future for GenFuture<T> {
39 type Output = T::Return;
40 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
41 // Safe because we're !Unpin + !Drop mapping to a ?Unpin value
42 let gen = unsafe { Pin::map_unchecked_mut(self, |s| &mut s.0) };
43 set_task_context(cx, || match gen.resume() {
44 GeneratorState::Yielded(()) => Poll::Pending,
45 GeneratorState::Complete(x) => Poll::Ready(x),
51 static TLS_CX: Cell<Option<NonNull<Context<'static>>>> = Cell::new(None);
54 struct SetOnDrop(Option<NonNull<Context<'static>>>);
56 impl Drop for SetOnDrop {
58 TLS_CX.with(|tls_cx| {
59 tls_cx.set(self.0.take());
65 #[unstable(feature = "gen_future", issue = "50547")]
66 /// Sets the thread-local task context used by async/await futures.
67 pub fn set_task_context<F, R>(cx: &mut Context<'_>, f: F) -> R
71 // transmute the context's lifetime to 'static so we can store it.
73 core::mem::transmute::<&mut Context<'_>, &mut Context<'static>>(cx)
75 let old_cx = TLS_CX.with(|tls_cx| {
76 tls_cx.replace(Some(NonNull::from(cx)))
78 let _reset = SetOnDrop(old_cx);
83 #[unstable(feature = "gen_future", issue = "50547")]
84 /// Retrieves the thread-local task context used by async/await futures.
86 /// This function acquires exclusive access to the task context.
88 /// Panics if no context has been set or if the context has already been
89 /// retrieved by a surrounding call to get_task_context.
90 pub fn get_task_context<F, R>(f: F) -> R
92 F: FnOnce(&mut Context<'_>) -> R
94 let cx_ptr = TLS_CX.with(|tls_cx| {
95 // Clear the entry so that nested `get_task_waker` calls
96 // will fail or set their own value.
99 let _reset = SetOnDrop(cx_ptr);
101 let mut cx_ptr = cx_ptr.expect(
102 "TLS Context not set. This is a rustc bug. \
103 Please file an issue on https://github.com/rust-lang/rust.");
105 // Safety: we've ensured exclusive access to the context by
106 // removing the pointer from TLS, only to be replaced once
107 // we're done with it.
109 // The pointer that was inserted came from an `&mut Context<'_>`,
110 // so it is safe to treat as mutable.
111 unsafe { f(cx_ptr.as_mut()) }
115 #[unstable(feature = "gen_future", issue = "50547")]
116 /// Polls a future in the current thread-local task waker.
117 pub fn poll_with_tls_context<F>(f: Pin<&mut F>) -> Poll<F::Output>
121 get_task_context(|cx| F::poll(f, cx))