mod.rs.html -- source
Description: Source to the Rust file `src/libcore/future/mod.rs`.
Keywords: rust, rustlang, rust-lang

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82

    #![stable(feature = "futures_api", since = "1.36.0")]

    //! Asynchronous values.

    #[cfg(not(bootstrap))]
    use crate::{
        ops::{Generator, GeneratorState},
        pin::Pin,
        ptr::NonNull,
        task::{Context, Poll},
    };

    mod future;
    #[stable(feature = "futures_api", since = "1.36.0")]
    pub use self::future::Future;

    /// This type is needed because:
    ///
    /// a) Generators cannot implement `for<'a, 'b> Generator<&'a mut Context<'b>>`, so we need to pass
    ///    a raw pointer (see https://github.com/rust-lang/rust/issues/68923).
    /// b) Raw pointers and `NonNull` aren't `Send` or `Sync`, so that would make every single future
    ///    non-Send/Sync as well, and we don't want that.
    ///
    /// It also simplifies the HIR lowering of `.await`.
    #[doc(hidden)]
    #[unstable(feature = "gen_future", issue = "50547")]
    #[cfg(not(bootstrap))]
    #[derive(Debug, Copy, Clone)]
    pub struct ResumeTy(NonNull<Context<'static>>);

    #[unstable(feature = "gen_future", issue = "50547")]
    #[cfg(not(bootstrap))]
    unsafe impl Send for ResumeTy {}

    #[unstable(feature = "gen_future", issue = "50547")]
    #[cfg(not(bootstrap))]
    unsafe impl Sync for ResumeTy {}

    /// Wrap a generator in a future.
    ///
    /// This function returns a `GenFuture` underneath, but hides it in `impl Trait` to give
    /// better error messages (`impl Future` rather than `GenFuture<[closure.....]>`).
    // This is `const` to avoid extra errors after we recover from `const async fn`
    #[doc(hidden)]
    #[unstable(feature = "gen_future", issue = "50547")]
    #[cfg(not(bootstrap))]
    #[inline]
    pub const fn from_generator<T>(gen: T) -> impl Future<Output = T::Return>
    where
        T: Generator<ResumeTy, Yield = ()>,
    {
        struct GenFuture<T: Generator<ResumeTy, Yield = ()>>(T);

        // We rely on the fact that async/await futures are immovable in order to create
        // self-referential borrows in the underlying generator.
        impl<T: Generator<ResumeTy, Yield = ()>> !Unpin for GenFuture<T> {}

        impl<T: Generator<ResumeTy, Yield = ()>> Future for GenFuture<T> {
            type Output = T::Return;
            fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
                // Safety: Safe because we're !Unpin + !Drop, and this is just a field projection.
                let gen = unsafe { Pin::map_unchecked_mut(self, |s| &mut s.0) };

                // Resume the generator, turning the `&mut Context` into a `NonNull` raw pointer. The
                // `.await` lowering will safely cast that back to a `&mut Context`.
                match gen.resume(ResumeTy(NonNull::from(cx).cast::<Context<'static>>())) {
                    GeneratorState::Yielded(()) => Poll::Pending,
                    GeneratorState::Complete(x) => Poll::Ready(x),
                }
            }
        }

        GenFuture(gen)
    }

    #[doc(hidden)]
    #[unstable(feature = "gen_future", issue = "50547")]
    #[cfg(not(bootstrap))]
    #[inline]
    pub unsafe fn get_context<'a, 'b>(cx: ResumeTy) -> &'a mut Context<'b> {
        &mut *cx.0.as_ptr().cast()
    }