use std::{
borrow::{Borrow, BorrowMut},
mem,
num::NonZero,
};
use crate::{
buffer,
buffer::{
raw::Retain as _,
segments::{
self, Chain, Handle as _, Key, Pool,
assembly::total,
chain::edit::Promotion,
handles::{self, Occupied},
},
storage,
write::consume,
},
depot::{
arena::linked::{fifo::ends, slots},
capacity,
raw::Proof,
},
mem::rc,
};
trait Destination<T: buffer::raw::Segment>: Sized {
type Output: BorrowMut<Chain<T>>;
fn try_open(self, pool: &Pool<T>) -> Result<Self::Output, rc::Error>;
unsafe fn try_whole(
self,
source: (Occupied, &mut Chain<T>),
) -> Result<Self::Output, segments::Error>;
}
impl<T: buffer::raw::Segment> Destination<T> for () {
type Output = Chain<T>;
fn try_open(self, pool: &Pool<T>) -> Result<Self::Output, rc::Error> {
pool.try_chain()
}
unsafe fn try_whole(
self,
(_, source): (Occupied, &mut Chain<T>),
) -> Result<Self::Output, segments::Error> {
let empty = self
.try_open(&source.handle)
.map_err(segments::Error::Retain)?;
Ok(mem::replace(source, empty))
}
}
impl<T: buffer::raw::Segment> Destination<T> for &mut Chain<T> {
type Output = Self;
fn try_open(self, _: &Pool<T>) -> Result<Self, rc::Error> {
Ok(self)
}
unsafe fn try_whole(self, source: (Occupied, &mut Chain<T>)) -> Result<Self, segments::Error> {
let same = self.is_same(source.1);
unsafe { Chain::join_from(same, (self.key.state(), &mut *self), source) }
.map_err(|error| error.into_error())?;
Ok(self)
}
}
impl<T: buffer::raw::Segment> Chain<T> {
pub fn try_take(&mut self, amount: usize) -> Result<Self, segments::Error> {
self.try_transfer(amount, ())
}
pub fn try_move_to(&mut self, target: &mut Self, amount: usize) -> Result<(), segments::Error> {
self.try_transfer(amount, target).map(|_| ())
}
fn try_transfer<D: Destination<T>>(
&mut self,
amount: usize,
destination: D,
) -> Result<D::Output, segments::Error> {
let Some(amount) = NonZero::new(amount) else {
return destination
.try_open(&self.handle)
.map_err(segments::Error::Retain);
};
let Some(source_key) = self.key.state() else {
return Err(segments::Error::Boundary(consume::Error::new(amount, 0)));
};
let state = unsafe { self.occupied_at(&source_key) };
let room = state.len();
match amount.get().cmp(&room) {
std::cmp::Ordering::Equal => {
return unsafe { destination.try_whole((source_key, self)) };
}
std::cmp::Ordering::Greater => {
return Err(segments::Error::Boundary(consume::Error::new(amount, room)));
}
std::cmp::Ordering::Less => {}
}
let total = state.count();
let first = state.head();
let input = handles::nodes(&self.handle);
let mut index_after = first;
let mut last = slots::Index::NONE;
let mut full = segments::Count::EMPTY;
let mut full_resident = 0usize;
let mut rest = amount;
let (frontier, backing, added_resident) = loop {
let owner = unsafe { &mut *input.value_ptr(index_after) };
let len = owner.len();
let measured = full_resident.wrapping_add(buffer::Residency::resident(owner));
if rest < len {
let region: &storage::Shared<T::Backing> = Borrow::borrow(owner.get_ref());
let backing = region
.owner()
.try_retain()
.map_err(segments::Error::Retain)?;
break (owner, Some(backing), measured);
}
full = segments::Count::new(full.into_raw().wrapping_add(1));
full_resident = measured;
last = index_after;
index_after = unsafe { input.next(index_after) };
let Some(next) = NonZero::new(rest.get() - len.get()) else {
break (owner, None, measured);
};
rest = next;
};
let mut destination = destination
.try_open(&self.handle)
.map_err(segments::Error::Retain)?;
{
let target = destination.borrow_mut();
let split_count = u32::from(backing.is_some());
let prior = target.key.state();
let (current, len, resident) = unsafe { target.totals_at(prior.as_ref()) };
let added = segments::Count::new(full.into_raw().wrapping_add(split_count));
let count = total::Error::count(current, added)?;
let len = total::Error::logical(len, amount.get())?;
let resident = total::Error::resident(resident, added_resident)?;
let same = self.handle.is_same(&target.handle);
let output = handles::nodes(&target.handle);
let needed = if same { split_count } else { added.into_raw() };
let mut reserve = slots::Reserve::try_new(output, capacity::Count::new(needed))
.map_err(segments::Error::SegmentCapacity)?;
let source_table = handles::descriptors(&self.handle);
let target_table = handles::descriptors(&target.handle);
let mut source_descriptor = match source_key {
Occupied::Multi(index) => Some(index),
Occupied::Single(_) => None,
};
let remains = segments::Count::new(total.into_raw() - full.into_raw());
let promotion = if count.is_many() && !matches!(prior, Some(Occupied::Multi(_))) {
let donor = if same && remains == segments::Count::ONE {
source_descriptor.take()
} else {
None
};
Some(match donor {
Some(index) => {
self.key = Key::single(index_after);
Promotion::Occupied(unsafe { source_table.detached(index) })
}
None => Promotion::Vacant(
target_table
.vacant()
.ok_or(segments::Error::ChainCapacity(capacity::Shortage::ONE))?,
),
})
} else {
None
};
if let Some(index) = source_descriptor {
if let segments::Kind::Many(count) = remains.kind() {
let desc = unsafe { &mut *source_table.value_ptr(index) };
if !full.is_empty() {
desc.links = unsafe {
ends::Exclusive::from_ends(index_after, desc.links.tail_raw())
};
desc.totals.count = count.nonzero();
desc.totals.resident -= full_resident;
}
desc.totals.len -= amount.get();
} else {
self.key = Key::single(index_after);
drop(unsafe { source_table.detached(index) });
}
}
let split = match backing {
Some(backing) => {
let prefix = unsafe { frontier.split_retained(rest, backing) };
let live = slots::Reserve::claim(unsafe { Proof::new(&mut reserve) }, prefix);
unsafe { live.into_index() }
}
None => slots::Index::NONE,
};
let moved = if full.is_empty() {
unsafe { ends::Exclusive::from_ends(split, split) }
} else if same {
unsafe { input.set_next(last, split) };
let tail = if split == slots::Index::NONE {
last
} else {
split
};
unsafe { ends::Exclusive::from_ends(first, tail) }
} else {
unsafe { reserve.move_through(input, first, last, split) }
};
let count = unsafe { NonZero::new_unchecked(count.into_raw()) };
let totals = segments::Totals {
count,
len,
resident,
};
unsafe {
target
.key
.append(&target.handle, prior, promotion, moved, totals)
};
}
Ok(destination)
}
}