1 #![stable(feature = "futures_api", since = "1.36.0")]
3 //! Asynchronous values.
7 ops::{Generator, GeneratorState},
10 task::{Context, Poll},
14 #[stable(feature = "futures_api", since = "1.36.0")]
15 pub use self::future::Future;
17 /// This type is needed because:
19 /// a) Generators cannot implement `for<'a, 'b> Generator<&'a mut Context<'b>>`, so we need to pass
21 /// b) Raw pointers and `NonNull` aren't `Send` or `Sync`, so that would make every single future
22 /// non-Send/Sync as well, and we don't want that.
24 /// It also simplifies the HIR lowering of `.await`.
26 #[unstable(feature = "gen_future", issue = "50547")]
27 #[cfg(not(bootstrap))]
28 #[derive(Debug, Copy, Clone)]
29 pub struct ResumeTy(pub NonNull<Context<'static>>);
31 #[unstable(feature = "gen_future", issue = "50547")]
32 #[cfg(not(bootstrap))]
33 unsafe impl Send for ResumeTy {}
35 #[unstable(feature = "gen_future", issue = "50547")]
36 #[cfg(not(bootstrap))]
37 unsafe impl Sync for ResumeTy {}
39 /// Wrap a generator in a future.
41 /// This function returns a `GenFuture` underneath, but hides it in `impl Trait` to give
42 /// better error messages (`impl Future` rather than `GenFuture<[closure.....]>`).
43 // This is `const` to avoid extra errors after we recover from `const async fn`
45 #[unstable(feature = "gen_future", issue = "50547")]
46 #[cfg(not(bootstrap))]
48 pub const fn from_generator<T>(gen: T) -> impl Future<Output = T::Return>
50 T: Generator<ResumeTy, Yield = ()>
52 #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
53 struct GenFuture<T: Generator<ResumeTy, Yield = ()>>(T);
55 // We rely on the fact that async/await futures are immovable in order to create
56 // self-referential borrows in the underlying generator.
57 impl<T: Generator<ResumeTy, Yield = ()>> !Unpin for GenFuture<T> {}
59 impl<T: Generator<ResumeTy, Yield = ()>> Future for GenFuture<T> {
60 type Output = T::Return;
61 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
62 // Safety: Safe because we're !Unpin + !Drop mapping to a ?Unpin value
63 let gen = unsafe { Pin::map_unchecked_mut(self, |s| &mut s.0) };
65 // Resume the generator, turning the `&mut Context` into a `NonNull` raw pointer. The
66 // `.await` lowering will safely cast that back to a `&mut Context`.
67 match gen.resume(ResumeTy(NonNull::from(cx).cast::<Context<'static>>())) {
68 GeneratorState::Yielded(()) => Poll::Pending,
69 GeneratorState::Complete(x) => Poll::Ready(x),
78 #[unstable(feature = "gen_future", issue = "50547")]
79 #[cfg(not(bootstrap))]
81 pub unsafe fn poll_with_context<F>(f: Pin<&mut F>, mut cx: ResumeTy) -> Poll<F::Output>
85 F::poll(f, cx.0.as_mut())