dope-core 0.77.0

Owned native I/O and completion driver for dope
Documentation
use core::{future::Future, marker, mem, pin, ptr, task};

use o3::base::marker::ThreadBound;

use crate::{
    executor::task::Fiber,
    executor::task::context::{self, Context},
};

struct Frame<'call, 'turn, 'd: 'turn, I> {
    context: &'call mut Context<'turn, 'd>,
    first: bool,
    scope: marker::PhantomData<fn(&mut I) -> &mut I>,
}

const _: () = {
    assert!(mem::size_of::<Frame<'static, 'static, 'static, ()>>() == 2 * mem::size_of::<usize>());
};

#[pin_project::pin_project]
#[repr(transparent)]
#[doc(hidden)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Awaitable<'a, 'd, I, F, const REPEAT: bool> {
    #[pin]
    fiber: F,
    marker: marker::PhantomData<&'a mut Brand<'d, I>>,
}

impl<'d, I, F, const REPEAT: bool> Future for Awaitable<'_, 'd, I, F, REPEAT>
where
    F: Fiber<'d>,
{
    type Output = F::Output;

    fn poll(
        self: pin::Pin<&mut Self>,
        context: &mut task::Context<'_>,
    ) -> task::Poll<Self::Output> {
        // SAFETY: the affine brand admits this awaitable only inside its paired
        // adapter poll, whose waker data is the live frame with the same scope.
        let frame = unsafe {
            &mut *context
                .waker()
                .data()
                .cast_mut()
                .cast::<Frame<'_, '_, 'd, I>>()
        };
        let first = mem::replace(&mut frame.first, false);
        if REPEAT && !first {
            let context::Continue::Permit(_permit) = frame.context.try_continue() else {
                return task::Poll::Pending;
            };
        }
        F::poll(context::PollCall {
            fiber: self.project().fiber,
            context: &mut *frame.context,
        })
    }
}

pub struct Brand<'d, I> {
    scope: marker::PhantomData<fn(&'d mut I) -> &'d mut I>,
    thread: marker::PhantomData<ThreadBound>,
}

impl<'d, I> Brand<'d, I> {
    /// # Safety
    /// This brand must remain affine inside one generated state machine.
    pub const unsafe fn scope() -> Self {
        Self {
            scope: marker::PhantomData,
            thread: marker::PhantomData,
        }
    }

    pub fn awaitable<'a, F, const REPEAT: bool>(
        fiber: F,
        _: &'a mut Self,
    ) -> Awaitable<'a, 'd, I, F, REPEAT> {
        Awaitable {
            fiber,
            marker: marker::PhantomData,
        }
    }

    pub fn input<'a, S, A, T, F, M>(_: &'a S, maker: M) -> M
    where
        M: FnOnce((A, &'a S, T)) -> F,
    {
        maker
    }

    pub fn call<A, F>(input: A, maker: impl FnOnce(A) -> F) -> F {
        maker(input)
    }

    /// # Safety
    /// `future` must be the generated machine for this scope and must not retain or expose its poll waker.
    /// It may await only its affine `Brand` or immediately awaited lexical async scopes obeying this rule.
    pub unsafe fn adapt<F>(future: F) -> FiberAdapter<'d, I, F> {
        FiberAdapter {
            future,
            scope: marker::PhantomData,
            thread: marker::PhantomData,
        }
    }
}

static BORROWED_VTABLE: task::RawWakerVTable =
    task::RawWakerVTable::new(clone_inert, noop, noop, noop);
/// # Safety
/// `data` borrows one live adapter poll frame; this callback neither owns nor dereferences it.
/// Cloning preserves the identical `(data, vtable)` pair required for interchangeable wakers.
unsafe fn clone_inert(data: *const ()) -> task::RawWaker {
    task::RawWaker::new(data, &BORROWED_VTABLE)
}

unsafe fn noop(_: *const ()) {}

#[pin_project::pin_project]
#[repr(transparent)]
#[doc(hidden)]
#[must_use = "a fiber does nothing unless it is driven"]
pub struct FiberAdapter<'d, I, F> {
    #[pin]
    future: F,
    scope: marker::PhantomData<fn(&'d mut I) -> &'d mut I>,
    thread: marker::PhantomData<ThreadBound>,
}

impl<'d, I, F> Fiber<'d> for FiberAdapter<'d, I, F>
where
    F: Future,
{
    type Output = F::Output;

    fn poll(call: context::PollCall<'_, '_, 'd, Self>) -> task::Poll<Self::Output> {
        use core::task::{RawWaker, Waker};

        let (this, context) = call.into_parts();

        let mut frame = Frame::<I> {
            context,
            first: true,
            scope: marker::PhantomData,
        };
        let data = ptr::from_mut(&mut frame).cast_const().cast();
        let raw = RawWaker::new(data, &BORROWED_VTABLE);
        let waker = mem::ManuallyDrop::new(unsafe { Waker::from_raw(raw) });
        let mut cx = task::Context::from_waker(&waker);
        Future::poll(this.project().future, &mut cx)
    }
}