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 {
#[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 {
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) => {
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> {
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() {
unsafe { Self::join::<true>((self.key.state(), self), (from, source)) }
.map_err(Rejected::into_error)?;
}
Ok(())
}
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());
unsafe { Self::join_from(same, (self.key.state(), self), source.edit()) }
.map_err(|error| crate::mem::Rejected::new(source, error.into_error()))
}
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) }
}
}
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)?;
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) {
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 {
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 {
Some(reserve) => unsafe { reserve.move_from(handles::nodes(&source.handle), input) },
None => input,
};
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());
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) {
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(),
}
}
}