1 //! Asynchronous values.
7 ops::{Drop, Generator, GeneratorState},
10 task::{Context, Poll},
14 #[stable(feature = "futures_api", since = "1.36.0")]
15 pub use core::future::*;
17 /// Wrap a generator in a future.
19 /// This function returns a `GenFuture` underneath, but hides it in `impl Trait` to give
20 /// better error messages (`impl Future` rather than `GenFuture<[closure.....]>`).
21 // This is `const` to avoid extra errors after we recover from `const async fn`
24 #[unstable(feature = "gen_future", issue = "50547")]
25 pub const fn from_generator<T: Generator<Yield = ()>>(x: T) -> impl Future<Output = T::Return> {
29 /// A wrapper around generators used to implement `Future` for `async`/`await` code.
32 #[unstable(feature = "gen_future", issue = "50547")]
33 #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
34 struct GenFuture<T: Generator<Yield = ()>>(T);
36 // We rely on the fact that async/await futures are immovable in order to create
37 // self-referential borrows in the underlying generator.
39 impl<T: Generator<Yield = ()>> !Unpin for GenFuture<T> {}
43 #[unstable(feature = "gen_future", issue = "50547")]
44 impl<T: Generator<Yield = ()>> Future for GenFuture<T> {
45 type Output = T::Return;
46 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
47 // Safe because we're !Unpin + !Drop mapping to a ?Unpin value
48 let gen = unsafe { Pin::map_unchecked_mut(self, |s| &mut s.0) };
49 let _guard = unsafe { set_task_context(cx) };
50 match gen.resume(()) {
51 GeneratorState::Yielded(()) => Poll::Pending,
52 GeneratorState::Complete(x) => Poll::Ready(x),
59 static TLS_CX: Cell<Option<NonNull<Context<'static>>>> = Cell::new(None);
63 struct SetOnDrop(Option<NonNull<Context<'static>>>);
66 impl Drop for SetOnDrop {
68 TLS_CX.with(|tls_cx| {
69 tls_cx.set(self.0.take());
74 // Safety: the returned guard must drop before `cx` is dropped and before
75 // any previous guard is dropped.
77 unsafe fn set_task_context(cx: &mut Context<'_>) -> SetOnDrop {
78 // transmute the context's lifetime to 'static so we can store it.
79 let cx = core::mem::transmute::<&mut Context<'_>, &mut Context<'static>>(cx);
80 let old_cx = TLS_CX.with(|tls_cx| tls_cx.replace(Some(NonNull::from(cx))));
86 #[unstable(feature = "gen_future", issue = "50547")]
87 /// Polls a future in the current thread-local task waker.
88 pub fn poll_with_tls_context<F>(f: Pin<&mut F>) -> Poll<F::Output>
92 let cx_ptr = TLS_CX.with(|tls_cx| {
93 // Clear the entry so that nested `get_task_waker` calls
94 // will fail or set their own value.
97 let _reset = SetOnDrop(cx_ptr);
99 let mut cx_ptr = cx_ptr.expect(
100 "TLS Context not set. This is a rustc bug. \
101 Please file an issue on https://github.com/rust-lang/rust.",
104 // Safety: we've ensured exclusive access to the context by
105 // removing the pointer from TLS, only to be replaced once
106 // we're done with it.
108 // The pointer that was inserted came from an `&mut Context<'_>`,
109 // so it is safe to treat as mutable.
110 unsafe { F::poll(f, cx_ptr.as_mut()) }