use crate::{
buffer,
buffer::{
segments,
segments::{Exact, Many, assembly, chain::edit, handles},
storage::NonEmpty,
},
depot::arena::linked::fifo::ends,
};
impl<T: buffer::raw::Segment> Many<T> {
#[inline(always)]
pub(in crate::buffer::segments::chain) fn try_insert<const FRONT: bool>(
self,
item: NonEmpty<T>,
) -> Result<Self, crate::mem::Rejected<(Self, NonEmpty<T>), assembly::Error>> {
let mut chain = self;
let (current, growth) = 'full: {
let multi = chain.edit();
let nodes = handles::nodes(&multi.sequence.handle);
let desc = unsafe {
&mut *handles::descriptors(&multi.sequence.handle).value_ptr(multi.index)
};
let totals = &desc.totals;
let current = segments::Count::new(totals.count.get());
let growth =
match segments::Totals::try_new(current, totals.len, totals.resident, &item) {
Ok(growth) => growth,
Err(error) => {
return Err(crate::mem::Rejected::new(
(chain, item),
assembly::Error::Total(error),
));
}
};
let Some(node) = nodes.vacant() else {
break 'full (current, growth);
};
let index = unsafe { node.insert(item).into_index() };
if FRONT {
unsafe { desc.links.link_front(nodes, index) };
} else {
let tail = unsafe { ends::Exclusive::from_ends(index, index) };
unsafe { desc.links.append_chain(nodes, tail) };
}
desc.totals = growth;
return Ok(chain);
};
match Exact::try_reserve(current, growth) {
Ok(exact) => Ok(unsafe {
if FRONT {
exact.join(item, chain)
} else {
exact.join(chain, item)
}
}),
Err(error) => Err(crate::mem::Rejected::new(
(chain, item),
edit::Cause::ONE_NODE.allocation(error),
)),
}
}
}