use crate::{
buffer::{self, segments, storage, write::consume},
depot::{
arena::linked::{self, fifo::ends},
capacity,
},
mem::{self, Rejected},
};
use std::{
convert::Infallible,
mem::{ManuallyDrop, MaybeUninit, replace},
num::NonZero,
ptr,
};
mod chain;
mod links;
mod state;
use chain::{grow_converted, grow_inline, grow_pair, promote_inline};
use links::{admit, append_input, append_links, initial_pair};
use links::{insert_one, move_owner, try_existing};
pub(super) use state::State;
#[derive(Debug)]
#[repr(transparent)]
pub struct Key(usize);
pub(super) enum Occupied {
Single(linked::raw::Index),
Multi(linked::raw::Index),
}
impl Occupied {
pub(super) unsafe fn head<T, L>(&self, root: &super::Header<T, L>) -> linked::raw::Index {
match *self {
Occupied::Single(index) => index,
Occupied::Multi(index) => unsafe { root.rows.value(index) }.links.head_raw(),
}
}
pub(super) fn row(&self) -> Option<linked::raw::Index> {
match *self {
Self::Single(_) => None,
Self::Multi(index) => Some(index),
}
}
pub(super) unsafe fn links<T, L>(
&self,
root: &super::Header<T, L>,
) -> ends::Exclusive<linked::raw::Index> {
match *self {
Self::Single(index) => unsafe { ends::Exclusive::from_ends(index, index) },
Self::Multi(index) => unsafe { ptr::read(&root.rows.value(index).links) },
}
}
}
impl Key {
const MULTI: usize = 1usize << (usize::BITS - 1);
pub const EMPTY: Self = Self(0);
pub const fn is_empty(&self) -> bool {
self.0 == 0
}
pub(super) const fn state(&self) -> Option<Occupied> {
if self.0 == 0 {
return None;
}
Some(unsafe { self.occupied() })
}
pub(super) const unsafe fn occupied(&self) -> Occupied {
let index = unsafe { self.index() };
if self.0 & Self::MULTI == 0 {
Occupied::Single(index)
} else {
Occupied::Multi(index)
}
}
pub(super) fn single(index: linked::raw::Index) -> Self {
let value = index.raw() as usize + 1;
Self(value)
}
pub(super) fn multi(index: linked::raw::Index) -> Self {
let value = index.raw() as usize + 1;
Self(Self::MULTI | value)
}
pub(super) const unsafe fn index(&self) -> linked::raw::Index {
linked::raw::Index::new(((self.0 & !Self::MULTI) - 1) as u32)
}
pub(super) unsafe fn join<'d>(
&mut self,
root: &super::Plain<'d>,
left: Occupied,
right: Occupied,
) -> Result<(), segments::Error> {
unsafe {
let total = root.totals(&left).try_join(root.totals(&right))?;
links::append::<_, _, 0, 0>(root, self, Some(left), right, [], [], total)
}
}
pub unsafe fn try_append<'d, const N: usize, I: Copy>(
&mut self,
root: &super::Plain<'d>,
source: super::Data<'d, I, Infallible>,
) -> Result<(), Rejected<super::Data<'d, I, Infallible>, segments::Error>> {
let target = self;
let mut source = ManuallyDrop::new(source);
match unsafe { links::append_input::<N, I>(root, target, &mut source) } {
Ok(()) => Ok(()),
Err(error) => Err(Rejected::new(ManuallyDrop::into_inner(source), error)),
}
}
pub unsafe fn try_insert<'d>(
&mut self,
pool: &super::Plain<'d>,
owner: super::Run<'d>,
) -> Result<(), Rejected<super::Run<'d>, segments::Error>> {
let key = self;
let mut owner = ManuallyDrop::new(owner);
match unsafe { links::insert_node(pool, key, &mut owner) } {
Ok(()) => Ok(()),
Err(error) => Err(Rejected::new(ManuallyDrop::into_inner(owner), error)),
}
}
pub unsafe fn try_take<'d>(
&mut self,
pool: &super::Plain<'d>,
amount: usize,
) -> Result<Option<super::Data<'d, (), Infallible>>, segments::Error> {
let key = self;
let whole = unsafe { pool.len(key) };
consume::Error::check(amount, whole).map_err(segments::Error::Boundary)?;
let Some(amount) = NonZero::new(amount) else {
return Ok(None);
};
if amount.get() == whole {
let state = match unsafe { key.occupied() } {
Occupied::Single(index) => {
let owner = unsafe { pool.nodes.take::<_, true>(index) };
*key = Key::EMPTY;
super::State::Contiguous { owner, inline: () }
}
Occupied::Multi(_) => {
let root = pool.try_hold().map_err(segments::Error::Retain)?;
let key = replace(key, Key::EMPTY);
super::State::Plain { root, key }
}
};
return Ok(Some(super::Data { state }));
}
let (selected, []) = unsafe { super::Selection::new::<0>(pool, key, amount) };
let cut = selected.boundary.map(super::Boundary::retain).transpose()?;
if selected.prefix.total.nodes.get() == 1 {
let owner = match cut {
Some(split) => split.take(),
None => unsafe { pool.nodes.take::<_, true>(selected.prefix.first) },
};
unsafe { selected.prefix.suffix(pool, key, None) };
return Ok(Some(super::Data {
state: super::State::Contiguous { owner, inline: () },
}));
}
let root = pool.try_hold().map_err(segments::Error::Retain)?;
pool.nodes
.check(capacity::Count::new(u32::from(cut.is_some())))
.map_err(segments::Error::SegmentCapacity)?;
let donor = if selected.prefix.rest.get() == 1 {
unsafe { key.occupied() }.row()
} else {
None
};
if donor.is_none() {
pool.rows
.check(capacity::Count::new(1))
.map_err(segments::Error::ChainCapacity)?;
}
let split = unsafe { super::Split::insert(cut, pool) };
unsafe {
selected.prefix.suffix(pool, key, donor);
}
let key = unsafe { selected.prefix.publish(pool, split, donor) };
Ok(Some(super::Data {
state: super::State::Plain { root, key },
}))
}
pub(super) unsafe fn copy_prefix<'d>(
&mut self,
pool: &super::Plain<'d>,
output: &mut [u8],
whole: usize,
) {
let key = self;
let Some(amount) = NonZero::new(output.len()) else {
return;
};
let original = unsafe { key.occupied() };
if amount.get() == whole {
unsafe { copy_whole(pool, key, original, output.as_mut_ptr()) };
return;
}
match original {
Occupied::Single(index) => {
let owner = unsafe { &mut *pool.nodes.value_ptr(index) };
unsafe {
ptr::copy_nonoverlapping(
owner.as_ref().as_ptr(),
output.as_mut_ptr(),
amount.get(),
);
}
unsafe { storage::raw::consume(owner, amount) };
}
Occupied::Multi(index) => {
let row = unsafe { pool.rows.value(index) };
let first = row.links.head_raw();
let before = row.totals.nodes;
let mut next = first;
let mut last = linked::raw::Index::NONE;
let mut taken = 0;
let mut retained = 0;
let mut left = amount;
let boundary = loop {
let owner = unsafe { pool.nodes.value(next) };
let len = owner.len().get();
let used = left.get().min(len);
unsafe {
ptr::copy_nonoverlapping(
owner.as_ref().as_ptr(),
output.as_mut_ptr().add(amount.get() - left.get()),
used,
);
}
if left.get() < len {
break Some(left);
}
taken += 1;
retained += buffer::Residency::resident(owner);
last = next;
next = unsafe { pool.nodes.next(next) };
match NonZero::new(left.get() - len) {
Some(rest) => left = rest,
None => break None,
}
};
if let Some(boundary) = boundary {
unsafe { storage::raw::consume(&mut *pool.nodes.value_ptr(next), boundary) };
}
let rest = unsafe { NonZero::new_unchecked(before.get() - taken) };
unsafe {
super::Prefix::update(pool, key, next, rest, amount.get(), retained, None)
};
unsafe { super::Prefix::retire(&pool.nodes, first, last, taken) };
}
}
}
pub unsafe fn consume<'d>(
&mut self,
pool: &super::Plain<'d>,
amount: NonZero<usize>,
whole: usize,
) {
let key = self;
match unsafe { key.occupied() } {
Occupied::Single(index) => {
if amount.get() == whole {
unsafe { links::clear::<false, _, _>(pool, index) };
*key = Key::EMPTY;
} else {
unsafe { storage::raw::consume(&mut *pool.nodes.value_ptr(index), amount) };
}
}
Occupied::Multi(index) => {
if amount.get() == whole {
unsafe { links::clear::<true, _, _>(pool, index) };
*key = Key::EMPTY;
} else {
let (selected, []) = unsafe { super::Selection::new::<0>(pool, key, amount) };
unsafe { selected.discard(pool, key) };
}
}
}
}
pub unsafe fn pop<'d>(&mut self, pool: &super::Plain<'d>) -> Option<super::Run<'d>> {
let key = self;
let original = key.state()?;
let head = match original {
Occupied::Single(index) => {
*key = Key::EMPTY;
index
}
Occupied::Multi(index) => {
let row = unsafe { &mut *pool.rows.value_ptr(index) };
let head = row.links.head_raw();
if row.totals.nodes.get() == 2 {
*key = Key::single(row.links.tail_raw());
drop(unsafe { linked::raw::Live::detached(&pool.rows, index) });
} else {
let owner = unsafe { pool.nodes.value(head) };
unsafe {
row.remove_front(
pool.nodes.next(head),
owner.len().get(),
buffer::Residency::resident(owner),
)
};
}
head
}
};
Some(unsafe { pool.nodes.take::<_, true>(head) })
}
pub(super) unsafe fn try_move<'d, const EDGE: usize>(
&mut self,
pool: &super::Plain<'d>,
input: &super::Plain<'d>,
source: &mut Key,
amount: NonZero<usize>,
whole: usize,
slot: [&mut MaybeUninit<mem::raw::Owner<super::Plain<'d>>>; EDGE],
) -> Result<(), segments::Error> {
let target = self;
let left = target.state();
if amount.get() == whole {
let right = unsafe { source.occupied() };
let added = unsafe { input.totals(&right) };
let total = match &left {
None => added,
Some(left) => unsafe { pool.totals(left) }.try_join(added)?,
};
unsafe {
links::append::<_, _, 1, EDGE>(
pool,
target,
left,
right,
[(input, capacity::Count::new(added.nodes.get()))],
slot,
total,
)
}?;
*source = Key::EMPTY;
return Ok(());
}
let (selected, []) = unsafe { super::Selection::new::<0>(input, source, amount) };
let cut = selected.boundary.map(super::Boundary::retain).transpose()?;
let total = match &left {
None => selected.prefix.total,
Some(left) => unsafe { pool.totals(left) }.try_join(selected.prefix.total)?,
};
pool.nodes
.check(capacity::Count::new(selected.prefix.total.nodes.get()))
.map_err(segments::Error::SegmentCapacity)?;
let donor = match left {
Some(Occupied::Multi(index)) => Some(index),
_ => None,
};
if total.nodes.get() > 1 && donor.is_none() {
pool.rows
.check(capacity::Count::new(1))
.map_err(segments::Error::ChainCapacity)?;
}
if const { EDGE != 0 } {
slot[0].write(pool.try_hold().map_err(segments::Error::Retain)?);
}
let split = unsafe { super::Split::insert(cut, pool) };
let moved = unsafe { selected.prefix.transfer(input, source, pool, split) };
unsafe {
links::append_links::<_, _, false>(pool, target, left.as_ref(), moved, total, donor)
};
Ok(())
}
pub unsafe fn clear<T, L>(&self, root: &super::Header<T, L>) {
match self.state() {
None => {}
Some(Occupied::Single(index)) => unsafe { links::clear::<false, _, _>(root, index) },
Some(Occupied::Multi(index)) => unsafe { links::clear::<true, _, _>(root, index) },
}
}
pub unsafe fn into_data<'d>(
self,
root: mem::raw::Owner<super::Plain<'d>>,
) -> super::Data<'d, Infallible, Infallible> {
super::Data {
state: super::State::Plain { root, key: self },
}
}
}
unsafe fn copy_whole<'d>(
root: &super::Plain<'d>,
key: &mut super::Key,
original: super::Occupied,
mut output: *mut u8,
) {
*key = super::Key::EMPTY;
match original {
super::Occupied::Single(index) => {
let owner = unsafe { linked::raw::Live::detached(&root.nodes, index) };
let bytes = owner.get().as_ref();
unsafe { ptr::copy_nonoverlapping(bytes.as_ptr(), output, bytes.len()) };
}
super::Occupied::Multi(index) => {
let row = unsafe { linked::raw::Live::detached(&root.rows, index) };
let nodes = unsafe { linked::raw::Drain::new(&root.nodes, row.get().links.head_raw()) };
for owner in nodes {
let bytes = owner.get().as_ref();
unsafe { ptr::copy_nonoverlapping(bytes.as_ptr(), output, bytes.len()) };
output = unsafe { output.add(bytes.len()) };
}
drop(row);
}
}
}