use crate::{
buffer::{self, hold::Charge, segments, storage},
depot::{arena::linked, capacity},
};
use std::{
convert::Infallible,
mem::{ManuallyDrop, MaybeUninit},
num::NonZero,
ptr,
};
mod prefix;
pub(super) use prefix::{Boundary, Prefix, Selection, Split};
pub struct Cut<'a, 'd, const N: usize> {
source: &'a mut super::Data<'d, (), Infallible>,
charge: [Charge; N],
detail: Detail<'d>,
}
union Detail<'d> {
contiguous: NonZero<usize>,
plain: ManuallyDrop<prefix::Selection<'d>>,
}
impl<const N: usize> Cut<'_, '_, N> {
pub fn charges(&self) -> [Charge; N] {
self.charge
}
pub fn resident(&self) -> usize {
if const { N == 1 } {
return self.charge[0].resident_bytes;
}
match &self.source.state {
super::State::Contiguous { owner, .. } => buffer::Residency::resident(owner),
super::State::Plain { .. } => unsafe { self.detail.plain.prefix.total.resident },
super::State::Ranges { ranges, .. } | super::State::Ranged { ranges, .. } => {
match *ranges {}
}
}
}
pub fn split(&self) -> [Charge; N] {
let mut output = [Charge::default(); N];
if N == 1 {
let resident = match &self.source.state {
super::State::Contiguous { .. } => self.charge[0].resident_bytes,
super::State::Plain { .. } => unsafe { self.detail.plain.prefix.edge_mem },
super::State::Ranges { ranges, .. } | super::State::Ranged { ranges, .. } => {
match *ranges {}
}
};
for item in &mut output {
*item = Charge::from_split(resident);
}
}
output
}
pub fn released(&self) -> [Charge; N] {
let mut output = self.charge;
for (charge, split) in output.iter_mut().zip(self.split()) {
charge.resident_bytes -= split.resident_bytes;
charge.owners -= split.owners;
}
output
}
}
impl<'d, const N: usize> AsRef<super::Data<'d, (), Infallible>> for Cut<'_, 'd, N> {
fn as_ref(&self) -> &super::Data<'d, (), Infallible> {
self.source
}
}
impl<'d, const N: usize> Cut<'_, 'd, N> {
pub fn write(
self,
output: &mut MaybeUninit<super::Data<'d, (), Infallible>>,
) -> Result<(), segments::Error> {
let Self {
source,
detail,
charge: _,
} = self;
let place = ptr::addr_of_mut!(source.state);
let output = unsafe { ptr::addr_of_mut!((*output.as_mut_ptr()).state) };
match &mut source.state {
super::State::Contiguous { owner, .. } => {
let amount = unsafe { detail.contiguous };
let edge = buffer::raw::Retain::try_retain(owner.as_inner().owner())
.map_err(segments::Error::Retain)?;
let owner = unsafe { storage::raw::split(owner, amount, edge) };
unsafe { ptr::write(output, super::State::Contiguous { owner, inline: () }) };
Ok(())
}
super::State::Plain { root, key } => {
let selected = unsafe { ManuallyDrop::into_inner(detail.plain) };
let pointer = ptr::from_ref(root.get());
let input = unsafe { &*pointer };
let cut = selected
.boundary
.map(prefix::Boundary::retain)
.transpose()?;
if selected.prefix.total.nodes.get() == 1 {
let owner = match cut {
Some(split) => split.take(),
None => unsafe { input.nodes.take::<_, true>(selected.prefix.first) },
};
unsafe { selected.prefix.suffix(input, key, None) };
if selected.prefix.rest.get() == 1 {
let rest = unsafe { input.nodes.take::<_, true>(selected.prefix.next) };
let original = unsafe { ptr::read(root) };
unsafe {
ptr::write(
place,
super::State::Contiguous {
owner: rest,
inline: (),
},
)
};
drop(original);
}
unsafe { ptr::write(output, super::State::Contiguous { owner, inline: () }) };
return Ok(());
}
if selected.prefix.rest.get() == 1 {
let row = unsafe { key.index() };
let split = cut.map(prefix::Split::take);
let (rest, vacancy) =
unsafe { linked::raw::Live::detached(&input.nodes, selected.prefix.next) }
.take();
let original = unsafe { ptr::read(root) };
unsafe {
ptr::write(
place,
super::State::Contiguous {
owner: rest,
inline: (),
},
)
};
let split = match split {
Some(owner) => unsafe { vacancy.insert(owner).into_index() },
None => {
drop(vacancy);
linked::raw::Index::NONE
}
};
let key = unsafe { selected.prefix.publish(input, split, Some(row)) };
unsafe {
ptr::write(
output,
super::State::Plain {
root: original,
key,
},
)
};
return Ok(());
}
let retained = input.try_hold().map_err(segments::Error::Retain)?;
input
.nodes
.check(capacity::Count::new(u32::from(cut.is_some())))
.map_err(segments::Error::SegmentCapacity)?;
input
.rows
.check(capacity::Count::new(1))
.map_err(segments::Error::ChainCapacity)?;
let split = unsafe { prefix::Split::insert(cut, input) };
unsafe { selected.prefix.suffix(input, key, None) };
let key = unsafe { selected.prefix.publish(input, split, None) };
unsafe {
ptr::write(
output,
super::State::Plain {
root: retained,
key,
},
)
};
Ok(())
}
super::State::Ranges { ranges, .. } | super::State::Ranged { ranges, .. } => {
match *ranges {}
}
}
}
}
impl<const N: usize> Cut<'_, '_, N> {
pub fn discard(self) {
let Self {
source,
detail,
charge: _,
} = self;
let output = ptr::addr_of_mut!(source.state);
match &mut source.state {
super::State::Contiguous { owner, .. } => unsafe {
storage::raw::consume(owner, detail.contiguous)
},
super::State::Plain { root, key } => {
let selected = unsafe { ManuallyDrop::into_inner(detail.plain) };
if let Some(boundary) = selected.boundary {
unsafe { boundary.discard() };
}
let input = unsafe { &*ptr::from_ref(root.get()) };
unsafe { selected.prefix.suffix(input, key, None) };
if selected.prefix.rest.get() == 1 {
let owner = unsafe { input.nodes.take::<_, true>(selected.prefix.next) };
let original = unsafe { ptr::read(root) };
unsafe { ptr::write(output, super::State::Contiguous { owner, inline: () }) };
unsafe {
Prefix::retire(
&input.nodes,
selected.prefix.first,
selected.prefix.last,
selected.prefix.taken,
)
};
drop(original);
} else {
unsafe {
Prefix::retire(
&input.nodes,
selected.prefix.first,
selected.prefix.last,
selected.prefix.taken,
)
};
}
}
super::State::Ranges { ranges, .. } | super::State::Ranged { ranges, .. } => {
match *ranges {}
}
}
}
}
impl<'a, 'd, const N: usize> Cut<'a, 'd, N> {
pub(super) unsafe fn new(
source: &'a mut super::Data<'d, (), Infallible>,
amount: NonZero<usize>,
) -> Self {
let mut charge = [Charge::default(); N];
let detail = match &mut source.state {
super::State::Contiguous { owner, .. } => {
if N == 1 {
charge.fill(Charge::from_owner(
amount.get(),
buffer::Residency::resident(owner),
));
}
Detail { contiguous: amount }
}
super::State::Plain { root, key } => {
let (selected, value) = unsafe { Selection::new::<N>(root.get(), key, amount) };
charge = value;
Detail {
plain: ManuallyDrop::new(selected),
}
}
super::State::Ranges { ranges, .. } | super::State::Ranged { ranges, .. } => {
match *ranges {}
}
};
Cut {
source,
charge,
detail,
}
}
}