Skip to main content

dope_core/executor/task/future/
raw.rs

1use core::{future::Future, marker, mem, pin, ptr, task};
2
3use o3::base::marker::ThreadBound;
4
5use crate::{
6    executor::task::Fiber,
7    executor::task::context::{self, Context},
8};
9
10struct Frame<'call, 'turn, 'd: 'turn, I> {
11    context: &'call mut Context<'turn, 'd>,
12    first: bool,
13    scope: marker::PhantomData<fn(&mut I) -> &mut I>,
14}
15
16const _: () = {
17    assert!(mem::size_of::<Frame<'static, 'static, 'static, ()>>() == 2 * mem::size_of::<usize>());
18};
19
20#[pin_project::pin_project]
21#[repr(transparent)]
22#[doc(hidden)]
23#[must_use = "futures do nothing unless you `.await` or poll them"]
24pub struct Awaitable<'a, 'd, I, F, const REPEAT: bool> {
25    #[pin]
26    fiber: F,
27    marker: marker::PhantomData<&'a mut Brand<'d, I>>,
28}
29
30impl<'d, I, F, const REPEAT: bool> Future for Awaitable<'_, 'd, I, F, REPEAT>
31where
32    F: Fiber<'d>,
33{
34    type Output = F::Output;
35
36    fn poll(
37        self: pin::Pin<&mut Self>,
38        context: &mut task::Context<'_>,
39    ) -> task::Poll<Self::Output> {
40        // SAFETY: the affine brand admits this awaitable only inside its paired
41        // adapter poll, whose waker data is the live frame with the same scope.
42        let frame = unsafe {
43            &mut *context
44                .waker()
45                .data()
46                .cast_mut()
47                .cast::<Frame<'_, '_, 'd, I>>()
48        };
49        let first = mem::replace(&mut frame.first, false);
50        if REPEAT && !first {
51            let context::Continue::Permit(_permit) = frame.context.try_continue() else {
52                return task::Poll::Pending;
53            };
54        }
55        F::poll(context::PollCall {
56            fiber: self.project().fiber,
57            context: &mut *frame.context,
58        })
59    }
60}
61
62pub struct Brand<'d, I> {
63    scope: marker::PhantomData<fn(&'d mut I) -> &'d mut I>,
64    thread: marker::PhantomData<ThreadBound>,
65}
66
67impl<'d, I> Brand<'d, I> {
68    /// # Safety
69    /// This brand must remain affine inside one generated state machine.
70    pub const unsafe fn scope() -> Self {
71        Self {
72            scope: marker::PhantomData,
73            thread: marker::PhantomData,
74        }
75    }
76
77    pub fn awaitable<'a, F, const REPEAT: bool>(
78        fiber: F,
79        _: &'a mut Self,
80    ) -> Awaitable<'a, 'd, I, F, REPEAT> {
81        Awaitable {
82            fiber,
83            marker: marker::PhantomData,
84        }
85    }
86
87    pub fn input<'a, S, A, T, F, M>(_: &'a S, maker: M) -> M
88    where
89        M: FnOnce((A, &'a S, T)) -> F,
90    {
91        maker
92    }
93
94    pub fn call<A, F>(input: A, maker: impl FnOnce(A) -> F) -> F {
95        maker(input)
96    }
97
98    /// # Safety
99    /// `future` must be the generated machine for this scope and must not retain or expose its poll waker.
100    /// It may await only its affine `Brand` or immediately awaited lexical async scopes obeying this rule.
101    pub unsafe fn adapt<F>(future: F) -> FiberAdapter<'d, I, F> {
102        FiberAdapter {
103            future,
104            scope: marker::PhantomData,
105            thread: marker::PhantomData,
106        }
107    }
108}
109
110static BORROWED_VTABLE: task::RawWakerVTable =
111    task::RawWakerVTable::new(clone_inert, noop, noop, noop);
112/// # Safety
113/// `data` borrows one live adapter poll frame; this callback neither owns nor dereferences it.
114/// Cloning preserves the identical `(data, vtable)` pair required for interchangeable wakers.
115unsafe fn clone_inert(data: *const ()) -> task::RawWaker {
116    task::RawWaker::new(data, &BORROWED_VTABLE)
117}
118
119unsafe fn noop(_: *const ()) {}
120
121#[pin_project::pin_project]
122#[repr(transparent)]
123#[doc(hidden)]
124#[must_use = "a fiber does nothing unless it is driven"]
125pub struct FiberAdapter<'d, I, F> {
126    #[pin]
127    future: F,
128    scope: marker::PhantomData<fn(&'d mut I) -> &'d mut I>,
129    thread: marker::PhantomData<ThreadBound>,
130}
131
132impl<'d, I, F> Fiber<'d> for FiberAdapter<'d, I, F>
133where
134    F: Future,
135{
136    type Output = F::Output;
137
138    fn poll(call: context::PollCall<'_, '_, 'd, Self>) -> task::Poll<Self::Output> {
139        use core::task::{RawWaker, Waker};
140
141        let (this, context) = call.into_parts();
142
143        let mut frame = Frame::<I> {
144            context,
145            first: true,
146            scope: marker::PhantomData,
147        };
148        let data = ptr::from_mut(&mut frame).cast_const().cast();
149        let raw = RawWaker::new(data, &BORROWED_VTABLE);
150        let waker = mem::ManuallyDrop::new(unsafe { Waker::from_raw(raw) });
151        let mut cx = task::Context::from_waker(&waker);
152        Future::poll(this.project().future, &mut cx)
153    }
154}