o3 0.62.0

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

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

pub use charge::Charge;
pub use error::Error;
pub(in crate::buffer) use owner::Backing;
pub use owner::Owner;

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

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

#[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 can_share(
        self,
        logical: impl TryInto<NonZero<usize>>,
        resident: &(impl buffer::Residency + ?Sized),
    ) -> bool {
        let Ok(logical) = logical.try_into() else {
            return false;
        };
        match self.limit(logical) {
            Some(limit) => limit.get() == usize::MAX || resident.resident() <= limit.get(),
            None => false,
        }
    }

    /// Selects retention and its resident ceiling for a nonempty input.
    pub fn ceiling(
        self,
        logical: NonZero<usize>,
        resident: &(impl buffer::Residency + ?Sized),
    ) -> (bool, usize) {
        let Some(limit) = self.limit(logical) else {
            return (false, logical.get());
        };
        let resident = resident.resident();
        if limit.get() == usize::MAX || resident <= limit.get() {
            (true, logical.get().max(resident))
        } else {
            (false, logical.get())
        }
    }

    fn limit(self, logical: NonZero<usize>) -> Option<NonZero<usize>> {
        if logical.get() < self.min {
            return None;
        }
        Some(logical.saturating_mul(NonZero::new(self.factor)?))
    }

    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<storage::Shared<resident::State<'d>>> {
    /// Binds once to an exact resident domain. Rebinding that same domain is inert.
    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<storage::Shared<resident::State<'static>>>>() == size_of::<usize>()
    );
};