use std::{
cell, marker,
mem::{MaybeUninit, size_of},
num::NonZero,
ops, ptr,
};
use provided::account;
use crate::{
buffer::{
raw::{Policy as _, Projection},
resident, storage,
storage::{provided, provided::arena},
},
mem::raw::{self, Edge},
mem::slot,
};
#[repr(transparent)]
#[derive(Default)]
pub(super) struct Counter(cell::Cell<u32>);
#[derive(Debug)]
#[repr(transparent)]
pub(super) struct Registration<'d> {
count: raw::Count,
scope: marker::PhantomData<fn(&'d ()) -> &'d ()>,
}
#[derive(Clone, Copy)]
enum State {
Empty,
ReturnOnLastAccount,
Occupied,
}
#[derive(Clone, Copy)]
pub(super) union Data<'d> {
pub(super) free: Option<ptr::NonNull<Entry<'d>>>,
pub(super) returned: ptr::NonNull<Entry<'d>>,
budget: resident::Budget<'d>,
}
#[repr(C, align(8))]
pub(in crate::buffer::storage::provided) struct Entry<'d> {
registration: Registration<'d>,
state: cell::Cell<State>,
pub(super) resident: cell::Cell<MaybeUninit<usize>>,
pub(super) data: cell::Cell<Data<'d>>,
pub(super) domain: &'d arena::State<'d>,
}
impl<'d> storage::NonEmpty<provided::Prefix<'_, 'd, &[u8]>> {
#[inline]
pub(in crate::buffer::storage::provided) fn try_account<A: resident::Admission>(
self,
budget: resident::Budget<'d>,
admission: A,
) -> Result<
ops::ControlFlow<A::Declined, storage::Shared<Option<provided::Account<'d>>>>,
account::Cause,
> {
let prefix = self.into_storage();
let pointer = prefix.owner.entry;
let entry: &'d Entry<'d> = unsafe { pointer.as_ref() };
let registration = &entry.registration;
if !registration.is_empty() {
let paying = unsafe { entry.data.get().budget };
if !ptr::eq(paying.core(), budget.core()) {
return Err(account::Cause::Foreign);
}
if let ops::ControlFlow::Break(declined) = admission.check(budget, 0) {
return Ok(ops::ControlFlow::Break(declined));
}
unsafe { registration.try_retain() }.map_err(account::Cause::Retain)?;
} else {
let domain = entry.domain;
let count = domain.accounted.0.get();
let limit = domain.limit;
if count >= limit {
return Err(account::Cause::Exhausted { count, limit });
}
let resident = unsafe { NonZero::new_unchecked(*entry.capacity() as u32) };
if let ops::ControlFlow::Break(declined) =
admission.check(budget, resident.get() as usize)
{
return Ok(ops::ControlFlow::Break(declined));
}
budget
.try_acquire(resident)
.map_err(account::Cause::Budget)?;
domain.accounted.0.set(count + 1);
entry.data.set(Data { budget });
unsafe { registration.activate() };
}
let owner = provided::Account {
registration: unsafe { raw::Owner::from_raw(pointer.cast()) },
};
Ok(ops::ControlFlow::Continue(unsafe {
storage::Shared::assume(prefix.bytes, Some(owner))
}))
}
}
impl<'d> Entry<'d> {
pub(super) fn new(
domain: &'d arena::State<'d>,
resident: MaybeUninit<usize>,
next: Option<arena::Empty<'d>>,
) -> Self {
Self {
registration: Registration {
count: raw::Count::empty(),
scope: marker::PhantomData,
},
state: cell::Cell::new(State::Empty),
resident: cell::Cell::new(resident),
data: cell::Cell::new(Data {
free: next.map(|node| node.entry),
}),
domain,
}
}
pub(in crate::buffer::storage::provided) unsafe fn capacity(&self) -> &usize {
unsafe { (&*self.resident.as_ptr()).assume_init_ref() }
}
unsafe fn refund(&self) {
unsafe { self.data.get().budget.release(*self.capacity()) };
}
pub(super) unsafe fn release(owner: &mut provided::Owner<'d>) {
let entry = unsafe { owner.entry.as_ref() };
if entry.registration.is_empty() {
entry.domain.finish(arena::Ready { entry: owner.entry });
} else {
entry.state.set(State::ReturnOnLastAccount);
}
}
pub(super) fn recycle(node: arena::Ready<'d>) {
let entry = unsafe { node.entry.as_ref() };
entry.state.set(State::Empty);
entry.domain.push_free(arena::Empty { entry: node.entry });
}
pub(super) unsafe fn revoke<T, L>(
slot: &'d arena::Slot<'d, T, L>,
) -> Option<slot::Occupied<'d, T>> {
let entry = &slot.entry;
match entry.state.get() {
State::Empty => None,
State::ReturnOnLastAccount | State::Occupied => {
if !entry.registration.is_empty() {
unsafe { entry.refund() };
}
Some(unsafe { slot.occupied() })
}
}
}
}
impl<'d> arena::Ready<'d> {
pub(super) fn publish(self, view: Projection<'d, '_>) -> provided::Unique<'d> {
unsafe { self.entry.as_ref() }.state.set(State::Occupied);
provided::Unique::new(view, provided::Owner { entry: self.entry })
}
}
unsafe impl raw::Edge for Registration<'_> {
fn count(&self) -> &raw::Count {
&self.count
}
}
unsafe impl<'d> raw::Target for Registration<'d> {
unsafe fn destroy(pointer: ptr::NonNull<Self>) {
let pointer = pointer.cast::<Entry<'d>>();
let entry = unsafe { pointer.as_ref() };
let domain = entry.domain;
domain.accounted.0.set(domain.accounted.0.get() - 1);
unsafe { entry.refund() };
if matches!(entry.state.get(), State::ReturnOnLastAccount) {
domain.finish(arena::Ready { entry: pointer });
}
}
}
const _: () = {
assert!(size_of::<Entry<'_>>() == 4 * size_of::<usize>());
assert!(align_of::<Entry<'_>>() == 8);
};