o3 0.59.0

shared-nothing primitives
Documentation
use std::{mem, num::NonZero};

use segments::{assembly, assembly::total};

use crate::{
    buffer,
    buffer::{
        segments,
        segments::{
            Chain, Key, Pool, Totals,
            chain::edit::{Cause, Multi},
            handles,
            handles::{Descriptor, Occupied},
        },
    },
    depot::{
        arena::linked::{fifo::ends, slots},
        capacity,
    },
};

pub(in crate::buffer::segments::chain) enum Promotion<'a> {
    Vacant(slots::Vacant<Descriptor, &'a slots::Store<Descriptor>>),
    Occupied(slots::Live<Descriptor, &'a slots::Store<Descriptor>>),
}

impl Key {
    /// # Safety
    /// The key and prior describe the same unchanged target in this pool. The nonempty moved
    /// partition is disjoint; promotion owns a descriptor exactly when the combined key needs one.
    #[inline(always)]
    pub(in crate::buffer::segments::chain) unsafe fn append<T>(
        &mut self,
        handle: &impl segments::Handle<T>,
        prior: Option<Occupied>,
        promotion: Option<Promotion<'_>>,
        mut moved: ends::Exclusive<slots::Index>,
        totals: Totals,
    ) {
        let nodes = handles::nodes(handle);
        if let Some(Occupied::Multi(index)) = prior {
            let desc = unsafe { &mut *handles::descriptors(handle).value_ptr(index) };
            unsafe { desc.links.append_chain(nodes, moved) };
            desc.totals = totals;
        } else {
            if let Some(Occupied::Single(index)) = prior {
                // SAFETY: the moved run is already nonempty; its tail remains the outer tail.
                unsafe { moved.link_front(nodes, index) };
            }
            if let Some(promotion) = promotion {
                let desc = Descriptor {
                    links: moved,
                    totals,
                };
                let index = match promotion {
                    Promotion::Vacant(slot) => unsafe { slot.insert(desc).into_index() },
                    Promotion::Occupied(slot) => {
                        // SAFETY: the donated initialized slot owns no remaining source nodes.
                        let (store, index) = unsafe { slot.into_raw_parts() };
                        unsafe { *store.value_ptr(index) = desc };
                        index
                    }
                };
                *self = Key::multi(index);
            } else {
                *self = Key::single(moved.head_raw());
            }
        }
    }
}

impl<'a, T, K: From<Occupied>> From<Multi<'a, T, Pool<T>>> for (K, &'a mut Chain<T>) {
    fn from(edit: Multi<'a, T, Pool<T>>) -> Self {
        (Occupied::Multi(edit.index).into(), edit.sequence)
    }
}

pub(in crate::buffer::segments) enum Rejected {
    Total(total::Error),
    Capacity(segments::Count, Totals, Cause),
}

impl<T: buffer::raw::Segment> Chain<T> {
    /// Joins two chains from this exact pool without touching payload owners.
    pub fn try_append(&mut self, source: &mut Self) -> Result<(), segments::Error> {
        if !self.is_same(source) {
            return Err(segments::Error::DifferentPool);
        }
        if let Some(from) = source.key.state() {
            // SAFETY: these disjoint chains own the decoded keys in the same pool.
            unsafe { Self::join::<true>((self.key.state(), self), (from, source)) }
                .map_err(Rejected::into_error)?;
        }
        Ok(())
    }

    /// Moves every incoming owner into this pool, preserving the source on rejection.
    pub fn try_extend(
        &mut self,
        mut source: segments::Many<T>,
    ) -> Result<(), crate::mem::Rejected<segments::Many<T>, segments::Error>> {
        let same = self.is_same(source.as_chain());
        // SAFETY: the exclusive Many edit retains its descriptor and both pools are unchanged.
        unsafe { Self::join_from(same, (self.key.state(), self), source.edit()) }
            .map_err(|error| crate::mem::Rejected::new(source, error.into_error()))
    }

    /// # Safety
    /// Both keys belong to their exclusive chains and `same` is their pool identity.
    pub(in crate::buffer::segments::chain) unsafe fn join_from<'a>(
        same: bool,
        target: impl Into<(Option<Occupied>, &'a mut Self)>,
        source: impl Into<(Occupied, &'a mut Self)>,
    ) -> Result<(), Rejected>
    where
        T: 'a,
    {
        if same {
            unsafe { Self::join::<true>(target, source) }
        } else {
            unsafe { Self::join::<false>(target, source) }
        }
    }

    /// # Safety
    /// Each owner retains its supplied key. SAME is their pool identity.
    unsafe fn join<'a, const SAME: bool>(
        target: impl Into<(Option<Occupied>, &'a mut Self)>,
        source: impl Into<(Occupied, &'a mut Self)>,
    ) -> Result<(), Rejected>
    where
        T: 'a,
    {
        let (prior, target) = target.into();
        let (from, source) = source.into();
        if SAME && prior.is_none() {
            mem::swap(&mut target.key, &mut source.key);
            return Ok(());
        }
        let (current, len, resident) = unsafe { target.totals_at(prior.as_ref()) };
        let (added, bytes, retained) = unsafe { source.totals_at(Some(&from)) };
        let count = if SAME {
            current.into_raw().wrapping_add(added.into_raw())
        } else {
            total::Error::count(current, added)
                .map_err(Rejected::Total)?
                .into_raw()
        };
        let len = total::Error::logical(len, bytes).map_err(Rejected::Total)?;
        let resident = total::Error::resident(resident, retained).map_err(Rejected::Total)?;
        // SAFETY: the source is nonempty. Same-store partitions are disjoint and fit
        // physical node capacity, so their sum cannot wrap; cross-store sums are checked.
        let sum = Totals {
            count: unsafe { NonZero::new_unchecked(count) },
            len,
            resident,
        };
        let nodes = handles::nodes(&target.handle);
        let descs = handles::descriptors(&target.handle);
        if SAME && let (Some(Occupied::Single(left)), Occupied::Multi(right)) = (&prior, &from) {
            // SAFETY: this descriptor stays in its original slot and gains the disjoint singleton.
            let desc = unsafe { &mut *descs.value_ptr(*right) };
            unsafe { desc.links.link_front(nodes, *left) };
            desc.totals = sum;
            target.key = mem::replace(&mut source.key, Key::EMPTY);
            return Ok(());
        }
        let reserve = if SAME {
            None
        } else {
            Some(
                slots::Reserve::try_new(nodes, capacity::Count::new(added.into_raw()))
                    .map_err(|shortage| Rejected::Capacity(current, sum, Cause::Nodes(shortage)))?,
            )
        };
        let promotion = if sum.count.get() > 1 && !matches!(prior, Some(Occupied::Multi(_))) {
            let Some(slot) = descs.vacant() else {
                return Err(Rejected::Capacity(
                    current,
                    sum,
                    Cause::Descriptors(capacity::Shortage::ONE),
                ));
            };
            Some(Promotion::Vacant(slot))
        } else {
            None
        };
        let input = match from {
            // SAFETY: the exclusive source owns this singleton or the descriptor's whole partition.
            Occupied::Single(index) => unsafe { ends::Exclusive::from_ends(index, index) },
            Occupied::Multi(index) => {
                unsafe { handles::descriptors(&source.handle).take::<_, true>(index) }.links
            }
        };
        let moved = match reserve {
            // SAFETY: the distinct target has admitted the entire nonempty source.
            Some(reserve) => unsafe { reserve.move_from(handles::nodes(&source.handle), input) },
            None => input,
        };
        // SAFETY: the linked or moved partition and any promotion now belong to this target.
        unsafe {
            target
                .key
                .append(&target.handle, prior, promotion, moved, sum)
        };
        source.key = Key::EMPTY;
        Ok(())
    }
}

impl<T: buffer::raw::Segment> TryFrom<(Self, Self)> for segments::Many<T> {
    type Error = crate::mem::Rejected<(Self, Self), assembly::Error>;

    fn try_from((mut first, mut second): (Self, Self)) -> Result<Self, Self::Error> {
        let same = first.as_chain().is_same(second.as_chain());
        // SAFETY: the two exclusive edits retain the compared pools and their live descriptors.
        match unsafe { Chain::<T>::join_from(same, first.edit(), second.edit()) } {
            Ok(()) => Ok(first),
            Err(Rejected::Total(cause)) => Err(crate::mem::Rejected::new(
                (first, second),
                assembly::Error::Total(cause),
            )),
            Err(Rejected::Capacity(current, sum, cause)) => {
                match segments::Exact::try_reserve(current, sum) {
                    // SAFETY: capacity rejection leaves both admitted source chains untouched.
                    Ok(exact) => Ok(unsafe { exact.join(first, second) }),
                    Err(error) => Err(crate::mem::Rejected::new(
                        (first, second),
                        cause.allocation(error),
                    )),
                }
            }
        }
    }
}

impl Rejected {
    pub(in crate::buffer::segments) fn into_error(self) -> segments::Error {
        match self {
            Self::Total(cause) => cause.into(),
            Self::Capacity(_, _, cause) => cause.into_error(),
        }
    }
}