use std::{mem, num, ops, ptr};
use storage::alloc;
use crate::buffer::{raw, raw::Policy as _, resident, storage};
#[repr(transparent)]
#[derive(Debug)]
pub(in crate::buffer) struct Heap<P: raw::Policy = ()> {
pointer: ptr::NonNull<raw::Header<P>>,
}
impl<P: raw::Policy> Heap<P> {
#[inline]
pub(in crate::buffer) fn try_new(
seed: P,
capacity: num::NonZero<u32>,
) -> Result<Self, alloc::Error<P::Failure>> {
let debit = raw::Debit::try_new(seed, capacity).map_err(alloc::Error::Budget)?;
Self::try_charged(debit).map_err(alloc::Error::Allocation)
}
#[inline]
pub(in crate::buffer) fn try_charged(
debit: raw::Debit<P>,
) -> Result<Self, crate::alloc::Exhausted> {
let pointer = unsafe { raw::Header::try_new(*debit.item(), debit)? };
Ok(Self { pointer })
}
fn header(&self) -> &raw::Header<P> {
unsafe { self.pointer.as_ref() }
}
pub(in crate::buffer) fn capacity(&self) -> num::NonZero<u32> {
self.header().capacity()
}
pub(in crate::buffer) fn seed(&self) -> P {
self.header().policy
}
pub(in crate::buffer) fn try_reserve(
&mut self,
target: num::NonZero<u32>,
) -> Result<(), alloc::Error<P::Failure>> {
let Some(amount) = num::NonZero::new(target.get().saturating_sub(self.capacity().get()))
else {
return Ok(());
};
unsafe { self.try_grow(target, amount, 0..0, &[][..]) }
}
pub(in crate::buffer) unsafe fn try_grow<I: raw::SliceExt + ?Sized>(
&mut self,
target: num::NonZero<u32>,
amount: num::NonZero<u32>,
live: ops::Range<u32>,
src: &I,
) -> Result<(), alloc::Error<P::Failure>> {
use raw::SliceExt as _;
let debit = raw::Debit::try_new(self.seed(), amount).map_err(alloc::Error::Budget)?;
if live.start == 0 {
unsafe { self.resize(target) }.map_err(alloc::Error::Allocation)?;
debit.commit();
unsafe { src.copy_to(self.as_mut_ptr().cast::<u8>().add(live.end as usize)) };
} else {
let next =
unsafe { raw::Header::try_new(target, debit) }.map_err(alloc::Error::Allocation)?;
let len = (live.end - live.start) as usize;
let bytes = unsafe { raw::range(self.as_ptr().cast(), live.start as usize, len) };
let current = self.capacity();
unsafe {
(bytes, src).copy_to(raw::Header::data(next).as_ptr());
raw::Header::free(mem::replace(&mut self.pointer, next), current);
}
}
Ok(())
}
unsafe fn resize(&mut self, target: num::NonZero<u32>) -> Result<(), crate::alloc::Exhausted> {
let old = raw::Header::<P>::layout(self.capacity());
let new = raw::Header::<P>::layout(target);
unsafe {
self.pointer = crate::alloc::raw::resize(old, self.pointer.cast(), new)?.cast();
self.pointer.as_mut().set_capacity(target);
}
Ok(())
}
pub(in crate::buffer) fn as_ptr(&self) -> *const mem::MaybeUninit<u8> {
raw::Header::data(self.pointer).cast().as_ptr()
}
pub(in crate::buffer) fn as_mut_ptr(&mut self) -> *mut mem::MaybeUninit<u8> {
raw::Header::data(self.pointer).cast().as_ptr()
}
pub(in crate::buffer) fn into_shared(self) -> raw::Rc<P> {
let this = mem::ManuallyDrop::new(self);
unsafe { raw::Rc::from_raw(this.pointer) }
}
}
impl<P: raw::Policy> Drop for Heap<P> {
fn drop(&mut self) {
unsafe { raw::Header::destroy(self.pointer) };
}
}
const _: () = assert!(size_of::<Heap<()>>() == size_of::<ptr::NonNull<()>>());
const _: () = assert!(size_of::<Option<Heap<()>>>() == size_of::<ptr::NonNull<()>>());
impl<'d> Heap<resident::Budget<'d>> {
pub(in crate::buffer) fn try_compact(
&mut self,
capacity: num::NonZero<u32>,
) -> Result<(), crate::alloc::Exhausted> {
let current = self.capacity();
if capacity == current {
return Ok(());
}
unsafe {
self.resize(capacity)?;
self.seed().refund(crate::mem::raw::Counter::nonzero(
current.get() - capacity.get(),
));
}
Ok(())
}
}