dope-core 0.77.0

Owned native I/O and completion driver for dope
Documentation
use core::{cell, mem, pin, task::Poll};

use o3::base::cell::region;

use crate::{
    driver::{
        self,
        schedule::{
            app,
            ready::{self, wake::Waker},
        },
    },
    executor::task,
};
pub mod raw;
pub mod wake;

mod pollcall;

pub use pollcall::PollCall;

#[derive(Clone, Copy, Eq, PartialEq)]
pub enum Requeue {
    Idle,
    Requested,
}

const _: () = {
    assert!(mem::size_of::<Requeue>() == mem::size_of::<bool>());
    assert!(mem::align_of::<Requeue>() == mem::align_of::<bool>());
};

/// Result of reserving one additional application credit.
#[must_use = "a continuation either carries a permit or reports exhaustion"]
pub enum Continue<'poll, 'd> {
    Permit(app::Permit<'poll, 'd>),
    Exhausted,
}

const _: () = {
    assert!(mem::size_of::<Continue<'static, 'static>>() == mem::size_of::<u8>());
};

/// Result of polling one child with the current application budget.
#[must_use = "a poll either carries its result or reports exhaustion"]
pub enum PollResult<T> {
    Polled(Poll<T>),
    Exhausted,
}

const _: () = {
    assert!(mem::size_of::<PollResult<()>>() == mem::size_of::<Option<Poll<()>>>());
};

pub struct Context<'poll, 'd: 'poll> {
    wake: wake::Waker<'d>,
    root: wake::RootWaker<'d>,
    work: app::Work<'poll, 'd>,
    driver: &'poll mut driver::Local<'d>,
    requeue: cell::Cell<Requeue>,
}

impl<'poll, 'd> Context<'poll, 'd> {
    pub(crate) fn from_waker(
        wake: wake::Waker<'d>,
        root: wake::RootWaker<'d>,
        work: app::Work<'poll, 'd>,
        driver: &'poll mut driver::Local<'d>,
    ) -> Self {
        Self {
            wake,
            root,
            work,
            driver,
            requeue: cell::Cell::new(Requeue::Idle),
        }
    }

    /// Creates one poll context for the supplied root and work.
    pub fn new(
        target: ready::Target<'d>,
        work: app::Work<'poll, 'd>,
        driver: &'poll mut driver::Local<'d>,
    ) -> Self {
        let root = wake::RootWaker::from(target);
        Self::from_waker(root.into(), root, work, driver)
    }

    pub fn admitted<'call, 'turn>(
        &'call mut self,
        _permit: app::Permit<'turn, 'd>,
    ) -> raw::Admission<'call, 'poll, 'd>
    where
        'turn: 'poll,
    {
        raw::Admission { context: self }
    }

    pub const fn waker(&self) -> wake::Waker<'d> {
        self.wake
    }

    /// Returns the exact driver-owned root carried through this poll tree.
    /// It can own a persistent scheduler whose members outlive child adapters.
    pub fn root_waker(&self) -> wake::RootWaker<'d> {
        self.root
    }

    /// Returns a persistent wake capability for this poll target.
    pub fn completion(&self) -> Waker<'d> {
        self.wake.completion()
    }

    pub fn work(&self) -> app::Work<'poll, 'd> {
        self.work
    }

    pub fn driver(&mut self) -> &mut driver::Local<'d> {
        self.driver
    }

    /// Polls a live child with one credit, or returns `Pending` after completion.
    /// Exhaustion reactivates the current wake target and returns `Pending`.
    pub fn poll<'call, F>(
        &'call mut self,
        fiber: pin::Pin<&'call mut task::Task<F>>,
    ) -> Poll<F::Output>
    where
        F: task::Fiber<'d>,
    {
        match self.try_poll(fiber) {
            PollResult::Polled(poll) => poll,
            PollResult::Exhausted => Poll::Pending,
        }
    }

    /// Polls a live child with one credit; `Exhausted` reactivates its wake target.
    /// A completed task returns `Polled(Pending)` without consuming credit.
    pub fn try_poll<'call, F>(
        &'call mut self,
        fiber: pin::Pin<&'call mut task::Task<F>>,
    ) -> PollResult<F::Output>
    where
        F: task::Fiber<'d>,
    {
        let mut state = fiber.project().state;
        let Some(fiber) = state.as_mut().as_pin_mut() else {
            return PollResult::Polled(Poll::Pending);
        };
        let Continue::Permit(_permit) = self.try_continue() else {
            return PollResult::Exhausted;
        };
        let result = F::poll(PollCall {
            fiber,
            context: self,
        });
        if result.is_ready() {
            state.set(None);
        }
        PollResult::Polled(result)
    }

    /// Reserves one additional application credit for continued inline work.
    /// Exhaustion requeues the current fiber before returning `Exhausted`.
    pub fn try_continue(&self) -> Continue<'poll, 'd> {
        match self.work.permit() {
            Some(permit) => Continue::Permit(permit),
            None => {
                self.requeue();
                Continue::Exhausted
            }
        }
    }

    pub(crate) fn child<'call>(&'call mut self, wake: wake::Waker<'d>) -> Context<'call, 'd> {
        Context::from_waker(wake, self.root, self.work, &mut *self.driver)
    }

    pub fn region_token(&mut self) -> &mut region::Token<region::Identity<'d>> {
        self.driver.region_token()
    }

    pub fn wake(&self) {
        self.wake.wake();
    }

    /// Requests exact requeue after the current fiber borrow ends. A storage
    /// boundary may consume this bit for an inline requeue; otherwise the
    /// lexical scope wakes the target when the context drops.
    pub(crate) fn requeue(&self) {
        self.requeue.set(Requeue::Requested);
    }

    pub fn into_requeue(self) -> Requeue {
        self.requeue.replace(Requeue::Idle)
    }
}

impl Drop for Context<'_, '_> {
    fn drop(&mut self) {
        if self.requeue.get() == Requeue::Requested {
            self.wake.wake();
        }
    }
}