File: freeze_cycle.rs

package info (click to toggle)
rustc 1.85.0%2Bdfsg3-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, sid, trixie
  • size: 893,396 kB
  • sloc: xml: 158,127; python: 35,830; javascript: 19,497; cpp: 19,002; sh: 17,245; ansic: 13,127; asm: 4,376; makefile: 1,051; perl: 29; lisp: 29; ruby: 19; sql: 11
file content (46 lines) | stat: -rw-r--r-- 1,575 bytes parent folder | download | duplicates (5)
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
//@ check-pass

#![feature(coroutine_trait, negative_impls)]

use std::ops::{Coroutine, CoroutineState};
use std::task::{Poll, Context};
use std::future::{Future};
use std::ptr::NonNull;
use std::pin::Pin;

fn main() {}

#[derive(Debug, Copy, Clone)]
pub struct ResumeTy(NonNull<Context<'static>>);

unsafe impl Send for ResumeTy {}

unsafe impl Sync for ResumeTy {}

pub const fn from_coroutine<T>(gen: T) -> impl Future<Output = T::Return>
where
    T: Coroutine<ResumeTy, Yield = ()>,
{
    struct GenFuture<T: Coroutine<ResumeTy, Yield = ()>>(T);

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

    impl<T: Coroutine<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 coroutine, 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>>())) {
                CoroutineState::Yielded(()) => Poll::Pending,
                CoroutineState::Complete(x) => Poll::Ready(x),
            }
        }
    }

    GenFuture(gen)
}