o3 0.62.0

shared-nothing primitives
Documentation
//! Allocation accounting tied to a stable generative lifetime root.

use std::{
    convert::Infallible,
    mem::{ManuallyDrop, MaybeUninit},
    num,
    ops::ControlFlow,
    ptr::NonNull,
};

use crate::{
    base::cell::region,
    buffer::{
        bytes::bounded,
        pool,
        storage::{self, alloc},
        write::consume,
    },
    mem::{credit, rc},
};

pub use exact::Exact;
pub use state::State;
pub(in crate::buffer) use state::{Backing, Kind};

pub mod bound;
pub mod staging;
pub mod write;

mod exact;
mod state;

/// One stable resident-accounting counter reused across generative regions.
#[derive(Debug)]
pub struct Domain {
    capacity: usize,
    resident: crate::mem::raw::Account<true>,
}

impl Default for Domain {
    fn default() -> Self {
        Self::new()
    }
}

impl Domain {
    pub const fn new() -> Self {
        Self {
            capacity: 0,
            resident: crate::mem::raw::Account::new(0),
        }
    }
}

const _: () = assert!(size_of::<Domain>() == size_of::<usize>() * 2);

/// A one-word authorization naming one exact stable accounting counter.
/// Credits measure retained payload capacity, excluding allocator metadata and padding.
/// Retaining a pool slot can reserve credits without allocating another backing.
#[derive(Clone, Copy, Debug)]
pub struct Budget<'d> {
    core: (&'d Domain, region::Identity<'d>),
}

pub(in crate::buffer) trait Admission {
    type Declined;

    fn check(&self, _: Budget<'_>, _: usize) -> ControlFlow<Self::Declined> {
        ControlFlow::Continue(())
    }
}

impl Admission for () {
    type Declined = Infallible;
}

pub(in crate::buffer) struct Cap(pub(in crate::buffer) usize);

impl Admission for Cap {
    type Declined = ();

    fn check(&self, budget: Budget<'_>, extra: usize) -> ControlFlow<()> {
        let used = budget.resident();
        if used > self.0 || extra > self.0 - used {
            ControlFlow::Break(())
        } else {
            ControlFlow::Continue(())
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BindError {
    Unbound,
    Foreign,
}

impl Domain {
    /// Activates an empty counter for the exact region carried by `proof`.
    pub fn try_budget<'d>(
        &'d mut self,
        capacity: usize,
        proof: region::Identity<'d>,
    ) -> Result<Budget<'d>, Reuse> {
        if let Some(retained) = num::NonZero::new(self.resident.get()) {
            return Err(Reuse {
                retained,
                previous: self.capacity,
                requested: capacity,
            });
        }
        self.capacity = capacity;
        Ok(Budget {
            core: (self, proof),
        })
    }
}

impl<'d> Budget<'d> {
    pub(in crate::buffer) const fn core(self) -> &'d Domain {
        self.core.0
    }

    pub fn capacity(self) -> usize {
        self.core().capacity
    }

    pub fn resident(self) -> usize {
        self.core().resident.get()
    }

    pub fn try_copy(
        &self,
        source: &impl bounded::Source,
    ) -> Result<storage::Shared<State<'d>>, alloc::Error<credit::Error>> {
        let mut owner = MaybeUninit::<storage::Shared<State<'d>>>::uninit();
        storage::Owned::try_copy(source, self, &mut owner)?;
        // SAFETY: the original copy initializer wrote this exact output after successful admission.
        Ok(unsafe { owner.assume_init() })
    }

    pub const fn charge(self) -> Charge<'d> {
        Charge {
            budget: self,
            capacity: 0,
        }
    }

    pub fn try_charge(self, capacity: usize) -> Result<Charge<'d>, credit::Error> {
        if let Some(amount) = num::NonZero::new(capacity) {
            self.core()
                .resident
                .try_acquire(amount, self.core().capacity)?;
        }
        Ok(Charge {
            budget: self,
            capacity,
        })
    }

    /// # Safety
    /// Transfer exactly this counter's previously acquired credit once.
    pub(in crate::buffer) unsafe fn release(self, capacity: usize) {
        self.core().resident.refund(capacity);
    }
}

const _: () = assert!(size_of::<Budget<'static>>() == size_of::<usize>());
const _: () = assert!(size_of::<Option<Budget<'static>>>() == size_of::<Budget<'static>>());

/// One exact resident debit. The lifetime cannot be detached by safe code.
pub struct Charge<'d> {
    budget: Budget<'d>,
    capacity: usize,
}

impl<'d> Charge<'d> {
    pub const fn capacity(&self) -> usize {
        self.capacity
    }

    /// Transfers part of this debit without changing the domain's resident total.
    /// An oversized request leaves this charge unchanged.
    pub fn try_split(&mut self, capacity: usize) -> Result<Self, credit::Error> {
        let Some(left) = self.capacity.checked_sub(capacity) else {
            return Err(credit::Error::new(
                num::NonZero::<usize>::MIN.saturating_add(capacity - 1),
                self.capacity,
            ));
        };
        self.capacity = left;
        Ok(Self {
            budget: self.budget,
            capacity,
        })
    }

    pub fn try_resize(&mut self, capacity: usize) -> Result<(), credit::Error> {
        let core = self.budget.core();
        if let Some(amount) = num::NonZero::new(capacity.saturating_sub(self.capacity)) {
            core.resident.try_acquire(amount, core.capacity)?;
            self.capacity = capacity;
        } else {
            self.truncate(capacity);
        }
        Ok(())
    }

    pub(in crate::buffer) fn truncate(&mut self, capacity: usize) {
        let capacity = capacity.min(self.capacity);
        // SAFETY: this charge transfers only its released debit.
        unsafe { self.budget.release(self.capacity - capacity) };
        self.capacity = capacity;
    }
}

impl Drop for Charge<'_> {
    fn drop(&mut self) {
        // SAFETY: dropping this charge transfers its complete remaining debit.
        unsafe { self.budget.release(self.capacity) };
    }
}

impl<'d> From<Charge<'d>> for Budget<'d> {
    fn from(charge: Charge<'d>) -> Self {
        ManuallyDrop::new(charge).budget
    }
}

const _: () = assert!(size_of::<Charge<'static>>() == size_of::<usize>() * 2);
const _: () = assert!(size_of::<Option<Charge<'static>>>() == size_of::<Charge<'static>>());

impl<'d> crate::buffer::raw::Policy for Budget<'d> {
    type Failure = credit::Error;
    type Debit = Charge<'d>;

    fn available(self) -> usize {
        self.capacity() - self.resident()
    }

    fn try_acquire(self, amount: num::NonZero<u32>) -> Result<Self::Debit, Self::Failure> {
        let core = self.core();
        let amount = num::NonZero::<usize>::MIN.saturating_add(amount.get() as usize - 1);
        core.resident.try_acquire(amount, core.capacity)?;
        Ok(Charge {
            budget: self,
            capacity: amount.get(),
        })
    }

    unsafe fn deallocate(self, pointer: NonNull<u8>, capacity: num::NonZero<u32>) {
        // SAFETY: terminal ownership transfers this policy's exact debit and allocation once.
        unsafe {
            Budget::release(self, capacity.get() as usize);
            crate::buffer::raw::Header::<Self>::free(pointer.cast(), capacity);
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AllocError {
    Capacity(consume::Error),
    Budget(credit::Error),
    Retain(rc::Error),
    Layout(pool::LayoutError),
    Exhausted(crate::alloc::Exhausted),
}

impl From<storage::AllocError<credit::Error>> for AllocError {
    fn from(error: storage::AllocError<credit::Error>) -> Self {
        match error {
            storage::AllocError::Capacity(error) => Self::Capacity(error),
            storage::AllocError::Exhausted(error) => Self::Exhausted(error),
            storage::AllocError::Budget(error) => Self::Budget(error),
        }
    }
}

impl From<alloc::Error<credit::Error>> for AllocError {
    fn from(error: alloc::Error<credit::Error>) -> Self {
        match error {
            alloc::Error::Budget(error) => Self::Budget(error),
            alloc::Error::Allocation(error) => Self::Exhausted(error),
        }
    }
}

/// A preceding generation still owns resident credit.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Reuse {
    pub retained: num::NonZero<usize>,
    pub previous: usize,
    pub requested: usize,
}

const _: () = assert!(size_of::<Reuse>() == size_of::<usize>() * 3);