dope-core 0.76.0

Owned native I/O and completion driver for dope
Documentation
use std::mem;

use dope_sys::io::reactor::event::kind::Connect;
use dope_sys::memory::buffer::Access as _;
use dope_sys::{
    engine, engine::admit, io::reactor::Full, kernel, memory, table::permit::Queue as _,
};

use crate::{
    Backend, Engine,
    driver::{
        Local,
        receive::Proof,
        result,
        retained::flight,
        route::{indices, kind},
    },
    io::{fd::handles, socket::install::slot},
};

mod context;
pub(in crate::driver) mod drain;
pub(crate) mod host;
mod receive;
pub use context::Context;
pub use receive::Receive;

/// Exclusive native authority borrowed from one driver-local scope.
///
/// Its parts can only enter native code through the same `Local` root.
#[repr(transparent)]
pub(crate) struct Loan<'a, 'd> {
    local: &'a mut Local<'d>,
}

impl<'a, 'd> Loan<'a, 'd> {
    pub(in crate::driver) fn new(local: &'a mut Local<'d>) -> Self {
        Self { local }
    }

    pub(crate) fn try_admit(
        self,
    ) -> Result<<Engine as admit::Admit<host::Host<Backend>>>::Admission<'a>, Full> {
        match admit::Admit::<host::Host<Backend>>::try_admit(&mut *self.local.backend) {
            Ok(native) => Ok(native),
            Err(full) => {
                self.local.retry = true;
                Err(full)
            }
        }
    }

    pub(crate) fn try_cancel<C: kind::Class>(
        self,
        flight: &mut flight::Flight<'d, C>,
    ) -> admit::Cancellation<host::Host<Backend>> {
        let echo = flight.key();
        let pending = flight.is_pending();
        match C::KIND {
            kind::Kind::Accept => self.cancel::<0>(echo, pending, None),
            kind::Kind::Recv => self.cancel::<1>(echo, pending, None),
            kind::Kind::Send | kind::Kind::Connect => self.cancel::<2>(echo, pending, None),
            kind::Kind::Unspecified
            | kind::Kind::Socket
            | kind::Kind::Shutdown
            | kind::Kind::Open
            | kind::Kind::OneShot
            | kind::Kind::TaskQueue
            | kind::Kind::Tuning
            | kind::Kind::Write
            | kind::Kind::Read
            | kind::Kind::Sync => self.cancel::<3>(echo, pending, None),
        }
    }

    pub(crate) fn try_stop_at(
        self,
        flight: &mut flight::Flight<'d, Connect>,
        fd: &handles::Descriptor<'d>,
    ) -> admit::Cancellation<host::Host<Backend>> {
        self.cancel::<2>(flight.key(), flight.is_pending(), Some(fd.slot()))
    }

    fn cancel<const FAMILY: u8>(
        self,
        echo: flight::Echo,
        pending: bool,
        slot: Option<handles::PhysicalSlot>,
    ) -> admit::Cancellation<host::Host<Backend>> {
        let result = admit::Backend::try_cancel::<FAMILY>(
            &mut *self.local.backend,
            echo,
            pending,
            slot.as_ref(),
        );
        if matches!(result, Err(admit::Error::Full(_))) {
            self.local.retry = true;
        }
        result
    }

    pub(crate) fn reclaim(&mut self, limit: usize) {
        let driver = self.local.driver;
        let owners = driver.owners();
        let mut count = 0;
        while count < limit {
            let Some(token) = owners.pop_returned() else {
                break;
            };
            // SAFETY: Local pairs this backend with its branded receive owners.
            // pop_returned transfers the unique slot after its last projection.
            unsafe { memory::raw::Release::release(&mut *self.local.backend, token) };
            count += 1;
        }
        if count != 0
            && let Ok(permit) = crate::Permits::try_acquire()
        {
            Proof::release(&permit, driver.exhausted(), driver);
        }
    }

    pub(crate) fn install<H, E>(
        self,
        hold: slot::Reserved<'d>,
        handle: H,
    ) -> Result<handles::Descriptor<'d>, result::Kernel>
    where
        Engine: engine::Install<handles::OwnedSlot, H, Error = E>,
        E: Into<<crate::Backend as kernel::Source>::Failure<indices::SlotIndex>>,
    {
        let state = &mut *self.local.backend;
        let slot = handles::OwnedSlot::from(hold.slot());
        if let Err(error) = engine::Install::install(state, slot, handle) {
            drop(hold);
            let cause: <crate::Backend as kernel::Source>::Failure<indices::SlotIndex> =
                error.into();
            return Err(result::Kernel::native(cause));
        }
        let (driver, slot) = hold.commit();
        Ok(handles::Descriptor::from_slot(slot, driver))
    }
}

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

impl AsMut<Engine> for Loan<'_, '_> {
    fn as_mut(&mut self) -> &mut Engine {
        self.local.backend
    }
}