dope-core 0.77.0

Owned native I/O and completion driver for dope
Documentation
use std::{cell, mem, num};

use crate::driver::{
    schedule::{
        self,
        ready::{self, DynamicIndex, Readiness},
    },
    settings,
};
use bitmap::Access as _;
use o3::{
    alloc::{self, array},
    depot::{self, index::bitmap},
    mem::quota,
};

const FIRST: DynamicIndex = DynamicIndex::from_code(num::NonZero::<u32>::MIN);
const WORD_BITS: usize = usize::BITS as usize;
const ENTRIES_PER_WORD: usize = WORD_BITS / 2;
const LOW_MASK: usize = usize::MAX / 3;
const SIDE_MASKS: [usize; 2] = [LOW_MASK, LOW_MASK << 1];

/// Ready indices isolated into stable drain batches.
pub(in crate::driver::schedule::ready) struct Set {
    cells: array::raw::Block<cell::Cell<usize>, Extent, State>,
}

struct State {
    mode: cell::Cell<Mode>,
    cursors: [cell::Cell<DynamicIndex>; 2],
}

#[derive(Clone, Copy)]
struct Extent {
    capacity: settings::Ready,
    shape: bitmap::Shape<num::NonZero<u32>>,
}

impl Extent {
    fn base(self) -> usize {
        self.shape.bits()
    }

    fn summary(self) -> usize {
        self.shape.words()
    }
}

// SAFETY: the immutable ready capacity determines one exact length in every copy.
unsafe impl alloc::raw::Extent for Extent {
    fn len(&self) -> usize {
        self.base() + 2 * self.summary()
    }
}

// SAFETY: the immutable ready extent bounds both initialized summary planes.
// Only bitmap operations mutate them; base transitions maintain their exact occupancy.
// The nonempty ready capacity admits every packed word and summary level.
unsafe impl depot::raw::Words for Set {
    type Plane = Side;
    type Size = num::NonZero<u32>;

    fn shape(&self) -> bitmap::Shape<num::NonZero<u32>> {
        self.cells.extent().shape
    }

    fn words(&self, side: Side) -> &[bitmap::Word] {
        let extent = self.cells.extent();
        let end = extent.base() + (side.index() + 1) * extent.summary();
        let cells: &[cell::Cell<usize>] = &self.cells;
        // SAFETY: Extent allocates the complete exact summary after the packed base.
        Self::from_cells(unsafe { cells.get_unchecked(end - extent.summary()..end) })
    }
}

impl Set {
    pub(in crate::driver::schedule::ready) fn try_new(
        capacity: settings::Ready,
    ) -> Result<Self, alloc::Error> {
        let words =
            num::NonZero::<u32>::MIN.saturating_add((capacity.raw() - 1) / ENTRIES_PER_WORD as u32);
        let extent = Extent {
            capacity,
            shape: bitmap::Shape::<num::NonZero<u32>>::new(words),
        };
        let state = State {
            mode: cell::Cell::new(Mode::IdleA),
            cursors: [const { cell::Cell::new(FIRST) }; 2],
        };
        let cells = array::raw::Block::try_new(extent, state)?.repeat_with(cell::Cell::default);
        Ok(Self { cells })
    }

    pub(in crate::driver::schedule::ready) fn has_ready(&self) -> bool {
        !self.is_empty(Side::A) || !self.is_empty(Side::B)
    }

    pub(in crate::driver::schedule::ready) fn start(&self) -> Option<Side> {
        let mode = self.cells.state().mode.get();
        let active = mode.active();
        match mode {
            Mode::DrainingA | Mode::DrainingB => None,
            Mode::PausedA | Mode::PausedB if !self.is_empty(active.other()) => Some(active.other()),
            _ => Some(active),
        }
    }

    pub(in crate::driver::schedule::ready) fn draining(&self, side: Side) {
        self.cells.state().mode.set(match side {
            Side::A => Mode::DrainingA,
            Side::B => Mode::DrainingB,
        });
    }

    pub(in crate::driver::schedule::ready) fn pause(&self, side: Side) {
        let pending = side.other();
        let mode = if !self.is_empty(side) {
            Mode::paused(side)
        } else if self.is_empty(pending) {
            match pending {
                Side::A => Mode::IdleA,
                Side::B => Mode::IdleB,
            }
        } else {
            Mode::paused(pending)
        };
        self.cells.state().mode.set(mode);
    }

    fn row(&self, index: DynamicIndex) -> bitmap::raw::Row<&Set> {
        let position =
            num::NonZero::<u32>::MIN.saturating_add(index.raw() / ENTRIES_PER_WORD as u32);
        // SAFETY: the index belongs to this arena or is an admitted traversal cursor.
        bitmap::raw::Row::from_source(unsafe { depot::raw::Proof::new((self, position)) })
    }

    /// Publishes one insertion or removal on the caller's exact side.
    /// Only that side can change occupancy; the other plane remains unchanged.
    fn publish<const SET: bool>(
        word: &cell::Cell<usize>,
        row: bitmap::raw::Row<&Set>,
        side: Side,
        before: usize,
        after: usize,
    ) {
        word.set(after);
        let stable = if SET { before } else { after };
        if stable & SIDE_MASKS[side.index()] == 0 {
            row.update::<SET>(side);
        }
    }

    pub(in crate::driver::schedule::ready) fn insert(&self, index: DynamicIndex) {
        let side = self.cells.state().mode.get().active();
        let row = self.row(index);
        let shift = (index.get() % ENTRIES_PER_WORD) * 2;
        let word = self.word(row);
        let current = word.get();
        if current & (3usize << shift) != 0 {
            return;
        }
        Self::publish::<true>(
            word,
            row,
            side,
            current,
            current | (1usize << (shift + side.index())),
        );
    }

    /// Removes the sole side encoded by an insertion into an empty packed position.
    pub(in crate::driver::schedule::ready) fn remove(&self, index: DynamicIndex) -> Readiness {
        let row = self.row(index);
        let shift = (index.get() % ENTRIES_PER_WORD) * 2;
        let word = self.word(row);
        let current = word.get();
        let bits = current & (3usize << shift);
        if bits == 0 {
            return Readiness::Idle;
        }
        let side = if bits & LOW_MASK != 0 {
            Side::A
        } else {
            Side::B
        };
        Self::publish::<false>(word, row, side, current, current & !bits);
        Readiness::Ready
    }

    pub(in crate::driver::schedule::ready) fn next(
        &self,
        side: Side,
        budget: &mut quota::Lease<'_, schedule::Domain<'_, ready::Lane>>,
    ) -> Option<DynamicIndex> {
        let permit = budget.take()?;
        let start = self.cursor(side).get();
        let index = match self.take(side, start) {
            None if start.get() != 0 => self.take(side, FIRST),
            item => item,
        }?;
        permit.commit();
        Some(index)
    }

    fn word(&self, row: bitmap::raw::Row<&Self>) -> &cell::Cell<usize> {
        let cells: &[cell::Cell<usize>] = &self.cells;
        // SAFETY: the row came from this set and its packed base precedes both summaries.
        unsafe { cells.get_unchecked(row.index()) }
    }

    fn cursor(&self, side: Side) -> &cell::Cell<DynamicIndex> {
        &self.cells.state().cursors[side.index()]
    }

    fn take(&self, side: Side, start: DynamicIndex) -> Option<DynamicIndex> {
        let shift = (start.get() % ENTRIES_PER_WORD) * 2 + side.index();
        let first = self.row(start);
        let word = self.word(first);
        let current = word.get();
        let selected = current & SIDE_MASKS[side.index()] & (usize::MAX << shift);
        let (row, word, current, bits) = match num::NonZero::<usize>::new(selected) {
            Some(bits) => (first, word, current, bits),
            None => {
                let row = bitmap::Access::find(self, side, first.index() + 1)?;
                let word = self.word(row);
                let current = word.get();
                // SAFETY: the found row proves this exact packed word holds a set
                // bit for `side`, so its side mask is nonzero.
                let bits =
                    unsafe { num::NonZero::new_unchecked(current & SIDE_MASKS[side.index()]) };
                (row, word, current, bits)
            }
        };
        let bit = bits.trailing_zeros() as usize;
        Self::publish::<false>(word, row, side, current, current & !(1usize << bit));
        let index = row.index() * ENTRIES_PER_WORD + bit / 2;
        // SAFETY: only an admitted index may set this bit. Its one-based code is at most capacity.
        let code = unsafe { num::NonZero::<u32>::new_unchecked(index as u32 + 1) };
        self.cursor(side)
            .set(if code.get() < self.cells.extent().capacity.raw() {
                DynamicIndex(code.saturating_add(1))
            } else {
                FIRST
            });
        Some(DynamicIndex(code))
    }
}

const _: () = {
    assert!(WORD_BITS == 64);
    assert!(!mem::needs_drop::<cell::Cell<usize>>());
    assert!(mem::size_of::<Set>() == 4 * mem::size_of::<usize>());
    assert!(mem::size_of::<Mode>() == 1);
};

#[derive(Clone, Copy, Eq, PartialEq)]
#[repr(u8)]
pub(in crate::driver::schedule::ready) enum Side {
    A,
    B,
}

#[derive(Clone, Copy, Eq, PartialEq)]
#[repr(u8)]
enum Mode {
    IdleA,
    IdleB,
    DrainingB,
    DrainingA,
    PausedB,
    PausedA,
}

impl Side {
    const fn index(self) -> usize {
        match self {
            Self::A => 0,
            Self::B => 1,
        }
    }

    const fn other(self) -> Self {
        match self {
            Self::A => Self::B,
            Self::B => Self::A,
        }
    }
}

impl Mode {
    const fn active(self) -> Side {
        if self as u8 & 1 == 0 {
            Side::A
        } else {
            Side::B
        }
    }

    const fn paused(side: Side) -> Self {
        match side {
            Side::A => Self::PausedA,
            Side::B => Self::PausedB,
        }
    }
}