dope-core 0.76.0

Owned native I/O and completion driver for dope
Documentation
//! Reusable slots for externally echoed flight completions.

use std::{
    marker,
    mem::{MaybeUninit, size_of},
    ops, ptr,
};

pub use echo::Echo;
use o3::{
    alloc,
    depot::array::init,
    mem::{self, lease},
};
pub use prepared::Prepared;

use dope_sys::io::reactor::complete::flags::Flow;

mod echo;
mod prepared;
pub mod raw;

const fn is_layout_valid<const INDEX_BITS: u32, const GENERATION_BITS: u32>() -> bool {
    INDEX_BITS != 0
        && INDEX_BITS <= u32::BITS
        && GENERATION_BITS != 0
        && GENERATION_BITS <= u32::BITS
        && INDEX_BITS + GENERATION_BITS <= u64::BITS
}

const fn generation_max<const GENERATION_BITS: u32>() -> u32 {
    if GENERATION_BITS == 0 {
        0
    } else if GENERATION_BITS >= u32::BITS {
        u32::MAX
    } else {
        (1u32 << GENERATION_BITS) - 1
    }
}

const fn index_limit<const INDEX_BITS: u32>() -> usize {
    if INDEX_BITS == 0 {
        0
    } else if INDEX_BITS >= usize::BITS {
        usize::MAX
    } else {
        1usize << INDEX_BITS
    }
}

/// Rust ownership of one externally completing flight.
/// Dropping the lease preserves the slot until its external completion arrives.
#[must_use = "a live flight must reach terminal completion or be detached"]
#[repr(transparent)]
pub struct Lease<'owner, T: Copy, const INDEX_BITS: u32 = 32, const GENERATION_BITS: u32 = 32> {
    live: mem::Lease<raw::Live<'owner, T, INDEX_BITS, GENERATION_BITS, { raw::ATTACHED }>>,
}

impl<'owner, T: Copy, const INDEX_BITS: u32, const GENERATION_BITS: u32>
    Lease<'owner, T, INDEX_BITS, GENERATION_BITS>
{
    pub fn is_pending(&self) -> bool {
        self.live.sink().is_pending()
    }

    pub fn echo(&self) -> Echo<T, INDEX_BITS, GENERATION_BITS> {
        self.live.sink().echo()
    }

    pub fn value(&self) -> T {
        self.live.sink().value()
    }
}

const _: () = {
    assert!(size_of::<Complete<'static, ()>>() == size_of::<usize>());
    assert!(size_of::<Option<Complete<'static, ()>>>() == size_of::<usize>());
    assert!(size_of::<Reserved<'static, ()>>() == size_of::<usize>());
    assert!(size_of::<Option<Reserved<'static, ()>>>() == size_of::<usize>());
    assert!(size_of::<Lease<'static, ()>>() == size_of::<usize>());
    assert!(size_of::<Option<Lease<'static, ()>>>() == size_of::<usize>());
    assert!(size_of::<Vacant<'static, 'static, ()>>() == 2 * size_of::<usize>());
    assert!(size_of::<Option<Vacant<'static, 'static, ()>>>() == 2 * size_of::<usize>());
};

/// One matched external completion tied to its owning arena.
#[must_use = "a bound completion must be applied"]
#[repr(transparent)]
pub struct Complete<'owner, T: Copy, const INDEX_BITS: u32 = 32, const GENERATION_BITS: u32 = 32> {
    bound:
        mem::Lease<raw::Live<'owner, T, INDEX_BITS, GENERATION_BITS, { raw::BOUND }>, lease::Open>,
}

impl<'owner, T: Copy, const INDEX_BITS: u32, const GENERATION_BITS: u32>
    Complete<'owner, T, INDEX_BITS, GENERATION_BITS>
{
    pub(in crate::driver::retained::flight::storage) fn new(
        bound: raw::Live<'owner, T, INDEX_BITS, GENERATION_BITS, { raw::BOUND }>,
    ) -> Self {
        Self {
            bound: mem::Lease::open(bound, ()),
        }
    }

    pub fn echo(&self) -> Echo<T, INDEX_BITS, GENERATION_BITS> {
        self.bound.sink().echo()
    }

    pub fn value(&self) -> T {
        self.bound.sink().value()
    }

    pub fn complete(self) -> T {
        let value = self.value();
        self.finish();
        value
    }

    /// Releases only this completion loan until the operation's last packet.
    pub fn settle(self, flow: Flow) -> T {
        match flow {
            Flow::Last => self.complete(),
            Flow::More => self.value(),
        }
    }

    pub(crate) fn terminal(&self) {
        self.bound.sink().terminal();
    }

    pub(in crate::driver::retained::flight) fn attachment(
        &self,
        slots: &raw::Slots<'_, T, INDEX_BITS, GENERATION_BITS>,
    ) -> Option<bool> {
        self.bound.sink().attachment(slots)
    }

    pub(in crate::driver::retained::flight) fn into_pointer(
        self,
    ) -> ptr::NonNull<raw::Entry<T, INDEX_BITS, GENERATION_BITS>> {
        let (bound, ()) = self.bound.into_parts();
        bound.into_pointer()
    }

    pub fn finish(self) {
        let (bound, ()) = self.bound.into_parts();
        bound.finish();
    }
}

/// A flight slot that rolls back unless committed.
#[must_use = "a reserved flight must be committed or released"]
#[repr(transparent)]
pub struct Reserved<'owner, T: Copy, const INDEX_BITS: u32 = 32, const GENERATION_BITS: u32 = 32> {
    live: mem::Lease<raw::Live<'owner, T, INDEX_BITS, GENERATION_BITS>, lease::Open>,
}

impl<'owner, T: Copy, const INDEX_BITS: u32, const GENERATION_BITS: u32>
    Reserved<'owner, T, INDEX_BITS, GENERATION_BITS>
{
    pub fn echo(&self) -> Echo<T, INDEX_BITS, GENERATION_BITS> {
        self.live.sink().echo()
    }

    pub fn commit(self) -> Lease<'owner, T, INDEX_BITS, GENERATION_BITS> {
        let (live, ()) = self.live.into_parts();
        Lease {
            live: mem::Lease::new(live.submit(), ()),
        }
    }
}

/// Exclusive vacant entry returned to its group when dropped.
///
/// The group remains borrowed even when the vacancy is only implicitly dropped.
#[must_use = "a vacancy must be reserved or released"]
#[repr(transparent)]
pub struct Vacant<
    'slot,
    'owner,
    T: Copy,
    const INDEX_BITS: u32 = 32,
    const GENERATION_BITS: u32 = 32,
> {
    vacant: mem::Lease<raw::Vacant<'slot, 'owner, T, INDEX_BITS, GENERATION_BITS>, lease::Open>,
}

impl<'owner, T: Copy, const INDEX_BITS: u32, const GENERATION_BITS: u32>
    Vacant<'_, 'owner, T, INDEX_BITS, GENERATION_BITS>
{
    pub fn reserve(self, value: T) -> Reserved<'owner, T, INDEX_BITS, GENERATION_BITS> {
        let (vacant, ()) = self.vacant.into_parts();
        Reserved {
            live: mem::Lease::open(vacant.occupy(value), ()),
        }
    }
}

/// Reusable externally completed flights with packed index/generation echoes.
pub struct Flights<T: Copy, const INDEX_BITS: u32 = 32, const GENERATION_BITS: u32 = 32> {
    groups: raw::Pool<T, INDEX_BITS, GENERATION_BITS>,
}

impl<T: Copy, const INDEX_BITS: u32, const GENERATION_BITS: u32>
    Flights<T, INDEX_BITS, GENERATION_BITS>
{
    pub const fn new() -> Self {
        Self {
            groups: raw::Pool::new(),
        }
    }

    /// Exclusively owns preparation while completed groups borrow this arena.
    pub fn builder(&mut self) -> raw::Builder<'_, T, INDEX_BITS, GENERATION_BITS> {
        raw::Builder { arena: self }
    }

    pub fn drain(&self) -> Drain<'_, T, INDEX_BITS, GENERATION_BITS> {
        Drain { arena: self }
    }

    pub(in crate::driver::retained::flight) fn is_pending(&self) -> bool {
        self.groups.is_pending()
    }

    pub(in crate::driver::retained::flight) fn finish(&self) {
        self.groups.finish();
    }
}

/// Borrowed authority to apply external completion echoes.
#[repr(transparent)]
pub struct Drain<'arena, T: Copy, const INDEX_BITS: u32 = 32, const GENERATION_BITS: u32 = 32> {
    arena: &'arena Flights<T, INDEX_BITS, GENERATION_BITS>,
}

impl<'arena, T: Copy, const INDEX_BITS: u32, const GENERATION_BITS: u32>
    Drain<'arena, T, INDEX_BITS, GENERATION_BITS>
{
    pub fn bind(
        &self,
        echo: Echo<T, INDEX_BITS, GENERATION_BITS>,
    ) -> Option<Complete<'arena, T, INDEX_BITS, GENERATION_BITS>> {
        self.arena.groups.bind(echo).map(Complete::new)
    }
}

enum Preparation<'owner, T: Copy, const INDEX_BITS: u32, const GENERATION_BITS: u32> {
    Reuse(raw::Slots<'owner, T, INDEX_BITS, GENERATION_BITS>),
    New(raw::Allocation<T, INDEX_BITS, GENERATION_BITS>),
}

impl<T: Copy, const INDEX_BITS: u32, const GENERATION_BITS: u32> Default
    for Flights<T, INDEX_BITS, GENERATION_BITS>
{
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Copy, const INDEX_BITS: u32, const GENERATION_BITS: u32>
    Flights<T, INDEX_BITS, GENERATION_BITS>
{
    /// # Safety
    /// The exact arena stays alive and immovable for `'owner`; the caller
    /// exclusively owns preparation for `'a` until it is committed or dropped.
    pub(in crate::driver::retained::flight) unsafe fn try_batch<
        'a,
        'owner,
        const GROUPS: usize,
        B,
    >(
        &'owner self,
        caps: [usize; GROUPS],
    ) -> Result<Prepared<'a, 'owner, T, INDEX_BITS, GENERATION_BITS, GROUPS, B>, alloc::Error> {
        const { assert!(GROUPS > 0) };
        if !is_layout_valid::<INDEX_BITS, GENERATION_BITS>() {
            return Err(alloc::Error::Overflow);
        }
        let mut end = self.groups.len();
        let mut rest = caps
            .iter()
            .try_fold(0usize, |total, capacity| total.checked_add(*capacity));
        let mut entries = MaybeUninit::uninit();
        let mut guard = init::Guard::<_, GROUPS, false>::new(&mut entries);
        let states = loop {
            let vacant = match guard.next() {
                ops::ControlFlow::Break(states) => break states.into_array(),
                ops::ControlFlow::Continue(vacant) => vacant,
            };
            let capacity = *vacant.get(&caps);
            let last = vacant.as_slice().len() + 1 == GROUPS;
            rest = rest.map(|rest| rest - capacity);
            let state = if last {
                self.groups.prepare::<B>(&mut end, capacity, rest)?
            } else {
                self.groups.prepare::<()>(&mut end, capacity, rest)?
            };
            guard = vacant.insert(state);
        };
        let dir = self.groups.try_plan(end)?;
        Ok(Prepared {
            arena: self,
            preparation: marker::PhantomData,
            states,
            directory: dir,
        })
    }
}