o3 0.61.0

shared-nothing primitives
Documentation
//! Allocation-owner retention projected onto accounting authorities.

use std::{num::NonZero, ptr};

pub use crate::buffer::storage::regions::retained::Retained;
pub use charge::Charge;
pub use error::Error;

use crate::buffer::{self, resident, storage};

mod charge;
mod error;
pub mod evidence;
pub mod limits;
pub mod ranges;
pub mod raw;

pub(in crate::buffer) trait Selection {
    const RESIDENT: bool;

    fn copy(logical: usize) -> Self;
    fn share(logical: usize, resident: usize) -> Self;
}

impl Selection for bool {
    const RESIDENT: bool = false;

    fn copy(_: usize) -> Self {
        false
    }

    fn share(_: usize, _: usize) -> Self {
        true
    }
}

impl Selection for (bool, usize) {
    const RESIDENT: bool = true;

    fn copy(logical: usize) -> Self {
        (false, logical)
    }

    fn share(logical: usize, resident: usize) -> Self {
        (true, logical.max(resident))
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Policy {
    min: usize,
    factor: usize,
}

impl Policy {
    pub const fn new(min: usize, factor: usize) -> Self {
        Self { min, factor }
    }

    pub const fn compact() -> Self {
        Self::new(usize::MAX, 0)
    }

    /// Prefers every shareable owner. Pair this policy with a hard resident budget.
    pub const fn share() -> Self {
        Self::new(0, usize::MAX)
    }

    pub fn choose(self, logical: usize, resident: &(impl buffer::Residency + ?Sized)) -> bool {
        match NonZero::new(logical) {
            Some(logical) => self.select(logical, resident),
            None => false,
        }
    }

    pub fn choose_nonzero(
        self,
        logical: NonZero<usize>,
        resident: &(impl buffer::Residency + ?Sized),
    ) -> bool {
        self.select(logical, resident)
    }

    /// Selects retention and its resident ceiling for a nonempty input.
    pub fn choose_with_ceiling(
        self,
        logical: NonZero<usize>,
        resident: &(impl buffer::Residency + ?Sized),
    ) -> (bool, usize) {
        self.select(logical, resident)
    }

    pub(in crate::buffer) fn select<S: Selection>(
        self,
        logical: NonZero<usize>,
        resident: &(impl buffer::Residency + ?Sized),
    ) -> S {
        let logical = logical.get();
        if logical < self.min || self.factor == 0 {
            return S::copy(logical);
        }
        let limit = logical.saturating_mul(self.factor);
        if limit == usize::MAX {
            let resident = if S::RESIDENT { resident.resident() } else { 0 };
            return S::share(logical, resident);
        }
        let resident = resident.resident();
        if resident <= limit {
            S::share(logical, resident)
        } else {
            S::copy(logical)
        }
    }

    pub const fn try_limit(self, logical: usize) -> Result<limits::Bound, limits::Error> {
        if logical < self.min || self.factor == 0 {
            return Ok(limits::Bound::new(logical));
        }
        match logical.checked_mul(self.factor) {
            Some(resident) => Ok(limits::Bound::new(resident)),
            None => Err(limits::Error::Scale {
                logical,
                factor: self.factor,
            }),
        }
    }
}

const _: () = assert!(core::mem::size_of::<Policy>() == 2 * core::mem::size_of::<usize>());

/// Exact component and operands that overflowed while combining charges.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Overflow {
    Logical { left: usize, right: usize },
    Resident { left: usize, right: usize },
    Owners { left: usize, right: usize },
}

const _: () = assert!(core::mem::size_of::<Overflow>() == 3 * core::mem::size_of::<usize>());

/// Copy authority for one retained-owner family.
#[derive(Debug)]
pub struct Retention<C: buffer::raw::Segment> {
    authority: C::Retention,
}

impl<C: buffer::raw::Segment> Default for Retention<C> {
    fn default() -> Self {
        Self {
            authority: C::Retention::default(),
        }
    }
}

impl<C: buffer::raw::Segment> Retention<C> {
    /// Copies bytes into this owner family, preserving its allocation authority.
    /// Empty input needs neither an authority nor an allocation.
    pub fn try_copy(&self, bytes: &[u8]) -> Result<C, CopyError> {
        let Some(source) = buffer::raw::Slices::try_new([bytes]).transpose() else {
            return Ok(C::EMPTY);
        };
        Ok(C::try_copy(source, &self.authority)?.into_storage())
    }

    pub(in crate::buffer) fn try_item(
        &self,
        source: buffer::raw::Slices<'_, 1>,
    ) -> Result<storage::NonEmpty<C>, CopyError> {
        C::try_copy(Ok(source), &self.authority)
    }
}

impl<'d> Retention<resident::Shared<'d>> {
    /// Binds once to an exact resident domain. Rebinding that same domain is inert.
    #[inline]
    pub fn try_bind(&mut self, budget: resident::Budget<'d>) -> Result<(), resident::BindError> {
        let bound = self.authority.get_or_insert(budget);
        if ptr::eq(bound.core(), budget.core()) {
            Ok(())
        } else {
            Err(resident::BindError::Foreign)
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CopyError {
    Storage(storage::AllocError),
    Resident(resident::AllocError),
    Authority(resident::BindError),
}

const _: () = {
    assert!(size_of::<Retention<storage::Shared>>() == 0);
    assert!(size_of::<Retention<resident::Shared<'static>>>() == size_of::<usize>());
};