o3 0.60.0

shared-nothing primitives
Documentation
use std::num::NonZero;

use crate::{
    alloc,
    buffer::{self, resident, segments, storage},
    mem::Rejected,
};

mod chain;
mod detach;
mod hold;
mod normalize;
mod pool;
mod ranges;
mod view;

pub mod raw {
    pub use super::{chain::pop_front, hold::raw::release};
}

pub use normalize::Normalize;
pub use chain::Prefix;
pub use detach::{Detach, DetachError};
pub use crate::buffer::bytes::window::{Copies, CopyError};
pub use ranges::{Header, Iter, Owned};
pub use view::{Contiguous, Cursor, Segments};
pub(in crate::buffer) use ranges::Allocation;

pub type Pool<'d> = pool::Pool<Part<'d>, NonZero<u32>>;
pub type ContiguousPool<'d> = pool::Pool<storage::NonEmpty<resident::Shared<'d>>>;
pub type Prepared<'d> = pool::Partition<
    storage::NonEmpty<resident::Shared<'d>>,
    (),
    ContiguousPool<'d>,
>;
pub type Scoped<'a, 'd> = pool::Partition<
    storage::NonEmpty<resident::Shared<'d>>,
    (),
    &'a pool::Header<storage::NonEmpty<resident::Shared<'d>>>,
>;

#[derive(Debug)]
pub struct Source<'d> {
    state: State<'d>,
}

#[derive(Debug)]
pub struct Sequence<'d> {
    state: SequenceState<'d>,
}

#[derive(Debug)]
enum SequenceState<'d> {
    Empty,
    Contiguous(storage::NonEmpty<resident::Shared<'d>>),
    Prepared(Prepared<'d>),
}

impl<'d> From<Sequence<'d>> for Source<'d> {
    fn from(source: Sequence<'d>) -> Self {
        Self {
            state: match source.state {
                SequenceState::Empty => State::Empty,
                SequenceState::Contiguous(owner) => State::Contiguous(owner),
                SequenceState::Prepared(source) => State::Prepared(source),
            },
        }
    }
}

#[derive(Debug)]
enum State<'d> {
    Empty,
    Contiguous(storage::NonEmpty<resident::Shared<'d>>),
    Ranges(ranges::Owned<'d>),
    Prepared(Prepared<'d>),
    Node(chain::Chain<'d, false>),
    Mixed(chain::Chain<'d>),
}

#[derive(Debug)]
pub enum Part<'d> {
    Contiguous(storage::NonEmpty<resident::Shared<'d>>),
    Ranges(ranges::Owned<'d>),
}

impl<'d> From<storage::NonEmpty<resident::Shared<'d>>> for Part<'d> {
    fn from(owner: storage::NonEmpty<resident::Shared<'d>>) -> Self {
        Self::Contiguous(owner)
    }
}

impl<'d> Part<'d> {
    fn try_clone(&self) -> Result<Self, crate::mem::rc::Error> {
        Ok(match self {
            Self::Contiguous(owner) => Self::Contiguous(owner.try_clone()?),
            Self::Ranges(owner) => Self::Ranges(owner.try_clone()?),
        })
    }

    fn count(&self) -> NonZero<u32> {
        match self {
            Self::Contiguous(_) => NonZero::<u32>::MIN,
            Self::Ranges(owner) => owner.count(),
        }
    }

    fn len(&self) -> usize {
        match self {
            Self::Contiguous(owner) => owner.len().get(),
            Self::Ranges(owner) => owner.len(),
        }
    }

    fn resident(&self) -> usize {
        match self {
            Self::Contiguous(owner) => buffer::Residency::resident(owner),
            Self::Ranges(owner) => owner.resident(),
        }
    }

    fn first(&self) -> &[u8] {
        match self {
            Self::Contiguous(owner) => owner.as_ref(),
            Self::Ranges(owner) => owner.first(),
        }
    }
}

impl<'d> Source<'d> {
    pub const EMPTY: Self = Self { state: State::Empty };

    pub const fn new() -> Self {
        Self::EMPTY
    }

    fn totals(&self) -> Option<chain::Totals<NonZero<u32>>> {
        let (count, len, resident) = match &self.state {
            State::Empty => return None,
            State::Contiguous(owner) => (
                NonZero::<u32>::MIN,
                owner.len().get(),
                buffer::Residency::resident(owner),
            ),
            State::Ranges(owner) => (owner.count(), owner.len(), owner.resident()),
            State::Prepared(source) => {
                let totals = source.totals()?;
                return Some(chain::Totals {
                    nodes: totals.nodes,
                    logical: totals.nodes,
                    len: totals.len,
                    resident: totals.resident,
                });
            }
            State::Node(chain) => return Some(chain.totals()),
            State::Mixed(chain) => return Some(chain.totals()),
        };
        Some(chain::Totals { logical: count, nodes: NonZero::<u32>::MIN, len, resident })
    }

    pub fn len(&self) -> usize {
        match &self.state {
            State::Empty => 0,
            State::Contiguous(owner) => owner.len().get(),
            State::Ranges(owner) => owner.len(),
            State::Prepared(source) => source.len(),
            State::Node(chain) => chain.totals().len,
            State::Mixed(chain) => chain.totals().len,
        }
    }

    pub fn is_empty(&self) -> bool {
        matches!(self.state, State::Empty)
    }

    pub fn count(&self) -> segments::Count {
        let count = match &self.state {
            State::Empty => return segments::Count::EMPTY,
            State::Contiguous(_) => return segments::Count::ONE,
            State::Ranges(owner) => owner.count(),
            State::Prepared(source) => return source.count(),
            State::Node(chain) => chain.totals().logical,
            State::Mixed(chain) => chain.totals().logical,
        };
        segments::Count::new(count.get())
    }

    pub fn part_count(&self) -> segments::Count {
        match &self.state {
            State::Empty => segments::Count::EMPTY,
            State::Mixed(chain) => segments::Count::new(chain.totals().nodes.get()),
            State::Prepared(source) => source.count(),
            State::Contiguous(_) | State::Ranges(_) | State::Node(_) => segments::Count::ONE,
        }
    }

    pub fn front(&self) -> Option<&[u8]> {
        Some(match &self.state {
            State::Empty => return None,
            State::Contiguous(owner) => owner.as_ref(),
            State::Ranges(owner) => owner.first(),
            State::Prepared(source) => return source.front().map(AsRef::as_ref),
            State::Node(chain) => chain.front().first(),
            State::Mixed(chain) => chain.front().first(),
        })
    }

    pub fn pop_part<const KEEP_SOURCE: bool>(&mut self) -> Option<Part<'d>> {
        chain::Chain::pop_part::<KEEP_SOURCE>(self)
    }

    pub fn contiguous(&self) -> Option<&[u8]> {
        match &self.state {
            State::Empty => Some(&[]),
            State::Contiguous(owner) => Some(owner.as_ref()),
            State::Ranges(owner) => owner.contiguous(),
            State::Prepared(source) => source.contiguous(),
            State::Node(chain) => match chain.front() {
                Part::Contiguous(owner) => Some(owner.as_ref()),
                Part::Ranges(owner) => owner.contiguous(),
            },
            State::Mixed(_) => None,
        }
    }

    pub fn try_append(
        &mut self,
        source: Self,
    ) -> Result<(), Rejected<Self, segments::assembly::Error>> {
        chain::Chain::try_extend(self, source)
    }

    pub fn try_join(&mut self, source: &mut Self) -> Result<(), segments::Error> {
        chain::Chain::try_join(self, source)
    }

    pub fn try_take<const KEEP_SOURCE: bool>(&mut self, amount: usize) -> Result<Self, segments::Error> {
        chain::Chain::try_take::<KEEP_SOURCE>(self, amount)
    }

    pub fn prefix<const N: usize>(&mut self, amount: usize) -> Result<Prefix<'_, 'd, N>, buffer::write::consume::Error> {
        Prefix::new(self, amount)
    }

    pub fn try_consume<const KEEP_SOURCE: bool>(&mut self, amount: usize) -> Result<(), buffer::write::consume::Error> {
        Prefix::<0>::new(self, amount)?.discard::<KEEP_SOURCE>();
        Ok(())
    }

    pub fn try_clone(&self) -> Result<Self, buffer::hold::ranges::retain::Error> {
        use buffer::hold::ranges::retain::Error;
        Ok(Self {
            state: match &self.state {
                State::Empty => State::Empty,
                State::Contiguous(owner) => {
                    State::Contiguous(owner.try_clone().map_err(Error::Retain)?)
                }
                State::Ranges(owner) => {
                    State::Ranges(owner.try_clone().map_err(Error::Retain)?)
                }
                State::Prepared(source) => State::Prepared(source.try_clone()?),
                State::Node(chain) => State::Node(chain.try_clone()?),
                State::Mixed(chain) => State::Mixed(chain.try_clone()?),
            },
        })
    }

    /// # Safety
    /// The ranges were admitted against this unchanged owner. Their count and
    /// complete byte sum are exact, and every member is nonempty.
    pub(in crate::buffer) unsafe fn from_ranges<N: buffer::raw::Length>(
        mut source: resident::Shared<'d>,
        ranges: &[(N, N)],
        count: segments::Count,
        len: usize,
    ) -> Result<Self, Rejected<resident::Shared<'d>, alloc::Error>> {
        match count.kind() {
            segments::Kind::Empty => Ok(Self::EMPTY),
            segments::Kind::One => {
                // SAFETY: the exact admitted count retains this sole nonempty range.
                let &(start, end) = unsafe { &*ranges.as_ptr() };
                unsafe { source.restrict(start.into_usize()..end.into_usize()) };
                Ok(Self {
                    // SAFETY: the admitted range remains nonempty in its original owner.
                    state: State::Contiguous(unsafe { storage::NonEmpty::assume(source) }),
                })
            }
            segments::Kind::Many(count) => {
                let owner = unsafe { ranges::Owned::try_new(source, ranges, count.nonzero(), len) }?;
                Ok(Self { state: State::Ranges(owner) })
            }
        }
    }

    pub(in crate::buffer) fn allocate_ranges(
        count: NonZero<u32>,
    ) -> Result<Allocation<'d>, alloc::Error> {
        ranges::Owned::allocate(count)
    }

    /// # Safety
    /// The allocation and ranges retain this exact count and source origin.
    pub(in crate::buffer) unsafe fn from_allocated_ranges<N: buffer::raw::Length>(
        allocation: Allocation<'d>,
        source: resident::Shared<'d>,
        ranges: &[(N, N)],
        count: NonZero<u32>,
        len: usize,
    ) -> Self {
        Self {
            state: State::Ranges(unsafe {
                ranges::Owned::initialize(allocation, source, ranges, count, len)
            }),
        }
    }
}

impl Default for Source<'_> {
    fn default() -> Self {
        Self::EMPTY
    }
}

impl<'d> From<resident::Shared<'d>> for Source<'d> {
    fn from(owner: resident::Shared<'d>) -> Self {
        match storage::NonEmpty::try_new(owner) {
            Ok(owner) => owner.into(),
            Err(_) => Self::EMPTY,
        }
    }
}

impl<'d> From<storage::NonEmpty<resident::Shared<'d>>> for Source<'d> {
    fn from(owner: storage::NonEmpty<resident::Shared<'d>>) -> Self {
        Self { state: State::Contiguous(owner) }
    }
}

impl<'d> From<Part<'d>> for Source<'d> {
    fn from(part: Part<'d>) -> Self {
        Self {
            state: match part {
                Part::Contiguous(owner) => State::Contiguous(owner),
                Part::Ranges(owner) => State::Ranges(owner),
            },
        }
    }
}

impl<'d> From<Prepared<'d>> for Source<'d> {
    fn from(source: Prepared<'d>) -> Self {
        if source.is_empty() {
            Self::EMPTY
        } else {
            Self { state: State::Prepared(source) }
        }
    }
}

impl buffer::Residency for Source<'_> {
    fn resident(&self) -> usize {
        self.totals().map_or(0, |totals| totals.resident)
    }
}