o3 0.59.0

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

use crate::{
    buffer,
    buffer::{
        raw::Retain as _,
        segments::{
            self, Chain, Handle as _, Key, Pool,
            assembly::total,
            chain::edit::Promotion,
            handles::{self, Occupied},
        },
        storage,
        write::consume,
    },
    depot::{
        arena::linked::{fifo::ends, slots},
        capacity,
        raw::Proof,
    },
    mem::rc,
};

trait Destination<T: buffer::raw::Segment>: Sized {
    type Output: BorrowMut<Chain<T>>;

    fn try_open(self, pool: &Pool<T>) -> Result<Self::Output, rc::Error>;
    /// # Safety
    /// The key names the complete partition retained by the exclusive source.
    unsafe fn try_whole(
        self,
        source: (Occupied, &mut Chain<T>),
    ) -> Result<Self::Output, segments::Error>;
}

impl<T: buffer::raw::Segment> Destination<T> for () {
    type Output = Chain<T>;

    fn try_open(self, pool: &Pool<T>) -> Result<Self::Output, rc::Error> {
        pool.try_chain()
    }

    unsafe fn try_whole(
        self,
        (_, source): (Occupied, &mut Chain<T>),
    ) -> Result<Self::Output, segments::Error> {
        let empty = self
            .try_open(&source.handle)
            .map_err(segments::Error::Retain)?;
        Ok(mem::replace(source, empty))
    }
}

impl<T: buffer::raw::Segment> Destination<T> for &mut Chain<T> {
    type Output = Self;

    fn try_open(self, _: &Pool<T>) -> Result<Self, rc::Error> {
        Ok(self)
    }

    unsafe fn try_whole(self, source: (Occupied, &mut Chain<T>)) -> Result<Self, segments::Error> {
        let same = self.is_same(source.1);
        unsafe { Chain::join_from(same, (self.key.state(), &mut *self), source) }
            .map_err(|error| error.into_error())?;
        Ok(self)
    }
}

impl<T: buffer::raw::Segment> Chain<T> {
    pub fn try_take(&mut self, amount: usize) -> Result<Self, segments::Error> {
        self.try_transfer(amount, ())
    }

    pub fn try_move_to(&mut self, target: &mut Self, amount: usize) -> Result<(), segments::Error> {
        self.try_transfer(amount, target).map(|_| ())
    }

    fn try_transfer<D: Destination<T>>(
        &mut self,
        amount: usize,
        destination: D,
    ) -> Result<D::Output, segments::Error> {
        let Some(amount) = NonZero::new(amount) else {
            return destination
                .try_open(&self.handle)
                .map_err(segments::Error::Retain);
        };
        let Some(source_key) = self.key.state() else {
            return Err(segments::Error::Boundary(consume::Error::new(amount, 0)));
        };
        // SAFETY: the untouched source owns the partition named by this key.
        let state = unsafe { self.occupied_at(&source_key) };
        let room = state.len();
        match amount.get().cmp(&room) {
            // SAFETY: this source still owns exactly the partition examined above.
            std::cmp::Ordering::Equal => {
                return unsafe { destination.try_whole((source_key, self)) };
            }
            std::cmp::Ordering::Greater => {
                return Err(segments::Error::Boundary(consume::Error::new(amount, room)));
            }
            std::cmp::Ordering::Less => {}
        }
        let total = state.count();
        let first = state.head();
        let input = handles::nodes(&self.handle);
        let mut index_after = first;
        let mut last = slots::Index::NONE;
        let mut full = segments::Count::EMPTY;
        let mut full_resident = 0usize;
        let mut rest = amount;
        let (frontier, backing, added_resident) = loop {
            // SAFETY: positive admitted bytes remain in the source's exclusive partition.
            let owner = unsafe { &mut *input.value_ptr(index_after) };
            let len = owner.len();
            let measured = full_resident.wrapping_add(buffer::Residency::resident(owner));
            if rest < len {
                let region: &storage::Shared<T::Backing> = Borrow::borrow(owner.get_ref());
                let backing = region
                    .owner()
                    .try_retain()
                    .map_err(segments::Error::Retain)?;
                break (owner, Some(backing), measured);
            }
            full = segments::Count::new(full.into_raw().wrapping_add(1));
            full_resident = measured;
            last = index_after;
            // SAFETY: this node belongs to the unchanged source and a nonempty suffix follows.
            index_after = unsafe { input.next(index_after) };
            let Some(next) = NonZero::new(rest.get() - len.get()) else {
                break (owner, None, measured);
            };
            rest = next;
        };
        let mut destination = destination
            .try_open(&self.handle)
            .map_err(segments::Error::Retain)?;
        {
            let target = destination.borrow_mut();
            let split_count = u32::from(backing.is_some());
            let prior = target.key.state();
            // SAFETY: prior was decoded from this exclusively borrowed target.
            let (current, len, resident) = unsafe { target.totals_at(prior.as_ref()) };
            let added = segments::Count::new(full.into_raw().wrapping_add(split_count));
            let count = total::Error::count(current, added)?;
            let len = total::Error::logical(len, amount.get())?;
            let resident = total::Error::resident(resident, added_resident)?;
            let same = self.handle.is_same(&target.handle);
            let output = handles::nodes(&target.handle);
            let needed = if same { split_count } else { added.into_raw() };
            let mut reserve = slots::Reserve::try_new(output, capacity::Count::new(needed))
                .map_err(segments::Error::SegmentCapacity)?;
            let source_table = handles::descriptors(&self.handle);
            let target_table = handles::descriptors(&target.handle);
            let mut source_descriptor = match source_key {
                Occupied::Multi(index) => Some(index),
                Occupied::Single(_) => None,
            };
            let remains = segments::Count::new(total.into_raw() - full.into_raw());
            let promotion = if count.is_many() && !matches!(prior, Some(Occupied::Multi(_))) {
                let donor = if same && remains == segments::Count::ONE {
                    source_descriptor.take()
                } else {
                    None
                };
                Some(match donor {
                    Some(index) => {
                        self.key = Key::single(index_after);
                        // SAFETY: the source now owns its suffix directly. Its live descriptor is free to transfer.
                        Promotion::Occupied(unsafe { source_table.detached(index) })
                    }
                    None => Promotion::Vacant(
                        target_table
                            .vacant()
                            .ok_or(segments::Error::ChainCapacity(capacity::Shortage::ONE))?,
                    ),
                })
            } else {
                None
            };

            if let Some(index) = source_descriptor {
                if let segments::Kind::Many(count) = remains.kind() {
                    let desc = unsafe { &mut *source_table.value_ptr(index) };
                    if !full.is_empty() {
                        // SAFETY: this same nonempty suffix retains the original tail.
                        desc.links = unsafe {
                            ends::Exclusive::from_ends(index_after, desc.links.tail_raw())
                        };
                        desc.totals.count = count.nonzero();
                        desc.totals.resident -= full_resident;
                    }
                    desc.totals.len -= amount.get();
                } else {
                    self.key = Key::single(index_after);
                    // SAFETY: this original descriptor has transferred its live nodes and sole return right.
                    drop(unsafe { source_table.detached(index) });
                }
            }
            let split = match backing {
                Some(backing) => {
                    // SAFETY: only rest < len retained this edge, from this unchanged exclusive node.
                    let prefix = unsafe { frontier.split_retained(rest, backing) };
                    // SAFETY: both pool cases debited one node for this retained prefix.
                    let live = slots::Reserve::claim(unsafe { Proof::new(&mut reserve) }, prefix);
                    unsafe { live.into_index() }
                }
                None => slots::Index::NONE,
            };
            let moved = if full.is_empty() {
                // SAFETY: the positive amount consisted solely of this admitted split node.
                unsafe { ends::Exclusive::from_ends(split, split) }
            } else if same {
                // SAFETY: the measured whole run and optional new singleton belong to this store.
                unsafe { input.set_next(last, split) };
                let tail = if split == slots::Index::NONE {
                    last
                } else {
                    split
                };
                unsafe { ends::Exclusive::from_ends(first, tail) }
            } else {
                // SAFETY: the suffix has its own key and the remaining debit exactly covers the whole run.
                unsafe { reserve.move_through(input, first, last, split) }
            };

            // SAFETY: at least one measured node was added and the total was checked.
            let count = unsafe { NonZero::new_unchecked(count.into_raw()) };
            let totals = segments::Totals {
                count,
                len,
                resident,
            };
            // SAFETY: the completed admissions retain this target, its promotion, and the moved nodes.
            unsafe {
                target
                    .key
                    .append(&target.handle, prior, promotion, moved, totals)
            };
        }
        Ok(destination)
    }
}