use std::{cell, mem, ptr};
use pool::state;
use crate::{
buffer,
buffer::{
pool,
pool::owners,
resident::{self, staging},
storage,
},
};
#[repr(C, align(8))]
pub(in crate::buffer) struct Accounts<'d> {
root: mem::ManuallyDrop<resident::Charge<'d>>,
head: cell::Cell<u32>,
fresh: cell::Cell<u32>,
}
impl<'d> Accounts<'d> {
pub(in crate::buffer) fn try_grow<I: buffer::raw::Transfer>(
reserve: staging::Reserve<
(&mut pool::Span<owners::Resident<'d>>, &mut u32),
&owners::Measured<I>,
>,
) -> Result<bool, resident::AllocError> {
let ((span, head), capacity, input) = reserve.into_parts();
let core = span.slots;
let header = core.header();
let previous = header.capacity();
if capacity <= previous
|| header.slots() != 1
|| !header.is_detached()
|| !crate::mem::raw::Edge::is_unique(span.slots.slot(span.key))
{
return Ok(false);
}
let shape =
owners::Shape::<owners::Resident<'d>>::try_new(pool::NonEmpty::new(capacity).into())
.map_err(resident::AllocError::Layout)?;
let accounts = unsafe { core.accounts().as_mut() };
accounts
.root
.try_resize(capacity.get() as usize)
.map_err(resident::AllocError::Budget)?;
let block = match owners::raw::Block::<owners::Resident<'d>, state::Uninit>::allocate(shape)
{
Ok(block) => block,
Err(error) => {
accounts.root.truncate(previous.get() as usize);
return Err(resident::AllocError::Exhausted(error));
}
};
let root = unsafe { mem::ManuallyDrop::take(&mut accounts.root) };
let next = unsafe { block.account(root, 1) };
let seed = unsafe { owners::raw::Seed::from_ptr(next) };
let bytes = unsafe { span.as_slice().get_unchecked(*head as usize..) };
let next = seed
.into_span()
.copy_in((bytes, input.input()), bytes.len() + input.len());
unsafe {
core.deallocate();
ptr::write(span, next);
}
*head = 0;
Ok(true)
}
pub(in crate::buffer::pool::owners) fn new(root: resident::Charge<'d>, limit: u32) -> Self {
Self {
root: mem::ManuallyDrop::new(root),
head: cell::Cell::new(limit.wrapping_sub(1)),
fresh: cell::Cell::new(limit),
}
}
pub(in crate::buffer) unsafe fn release<S>(core: owners::raw::Ptr<owners::Resident<'d>, S>) {
unsafe {
mem::ManuallyDrop::drop(&mut core.accounts().as_mut().root);
core.deallocate();
}
}
unsafe fn entry(table: ptr::NonNull<Self>, index: u32) -> ptr::NonNull<Account<'d>> {
unsafe { table.add(1).cast::<Account<'d>>().add(index as usize) }
}
}
#[repr(C, align(8))]
#[derive(Debug)]
pub(in crate::buffer) struct Account<'d> {
prefix: storage::raw::Prefix,
slot: ptr::NonNull<owners::raw::Slot<owners::Resident<'d>>>,
budget: resident::Budget<'d>,
}
impl<'d> Account<'d> {
pub(in crate::buffer) fn try_bind<M, A: resident::Admission>(
span: &pool::Span<owners::Resident<'d>, M>,
budget: &resident::Budget<'d>,
admit: A,
) -> Result<Option<crate::mem::raw::Owner<Self>>, resident::AllocError> {
use crate::mem::raw::{Edge, Owner};
let table = span.slots.accounts();
let slot = span.slots.ptr(span.key);
let link = unsafe { &slot.as_ref().backing.account };
let index = link.get();
if index != super::END {
let entry = unsafe { Accounts::entry(table, index) };
let account = unsafe { entry.as_ref() };
if !ptr::eq(budget.core(), account.budget.core()) || admit.check(*budget, 0).is_break()
{
return Ok(None);
}
unsafe {
Edge::try_retain(account).map_err(resident::AllocError::Retain)?;
return Ok(Some(Owner::from_raw(entry)));
}
}
let accounts = unsafe { table.as_ref() };
let index = accounts.head.get();
if index == super::END {
return Ok(None);
}
let capacity = span.capacity().get();
if admit.check(*budget, capacity as usize).is_break() {
return Ok(None);
}
let charge = budget
.try_charge(capacity as usize)
.map_err(resident::AllocError::Budget)?;
unsafe {
let entry = Accounts::entry(table, index);
let next = if index < accounts.fresh.get() {
accounts.fresh.set(index);
index.wrapping_sub(1)
} else {
entry.cast::<u32>().read()
};
accounts.head.set(next);
entry.write(Self {
prefix: storage::raw::Prefix::one(capacity),
slot,
budget: charge.into(),
});
Edge::start_pair(slot.as_ref());
link.set(index);
Ok(Some(Owner::from_raw(entry)))
}
}
pub(in crate::buffer) fn bytes(&self) -> usize {
self.prefix.word() as usize
}
}
unsafe impl crate::mem::raw::Edge for Account<'_> {
fn count(&self) -> &crate::mem::raw::Count {
crate::mem::raw::Edge::count(&self.prefix)
}
}
unsafe impl<'d> crate::mem::raw::Target for Account<'d> {
unsafe fn destroy(entry: ptr::NonNull<Self>) {
unsafe {
let account = entry.as_ref();
let slot = account.slot;
let (core, key) = owners::raw::Slot::locate(slot);
account.budget.release(account.bytes());
let index = slot.as_ref().backing.account.replace(super::END);
let table = core.accounts().as_ref();
entry.cast::<u32>().write(table.head.get());
table.head.set(index);
owners::raw::Slot::release(slot, core, key);
}
}
}
const _: () = {
assert!(size_of::<Accounts<'static>>() == 24);
assert!(size_of::<Account<'static>>() == 24);
assert!(size_of::<crate::mem::raw::Owner<Account<'_>>>() == size_of::<usize>());
assert!(size_of::<Option<crate::mem::raw::Owner<Account<'_>>>>() == size_of::<usize>());
};