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(pub(super) cell::Cell<u32>);
#[derive(Debug)]
#[repr(transparent)]
pub struct Registration<'d, L: Layout = cell::Cell<u32>> {
count: raw::Count,
scope: marker::PhantomData<fn(&'d L) -> &'d L>,
}
#[derive(Clone, Copy)]
pub(super) enum State {
Empty,
ReturnOnLastAccount,
Occupied,
}
pub(super) union Data<'d, L: Layout> {
pub(super) free: Option<arena::Link<'d, L>>,
pub(super) returned: arena::Link<'d, L>,
budget: resident::Budget<'d>,
}
#[repr(C, align(8))]
pub(in crate::buffer::storage::provided) struct Entry<'d, L: Layout = cell::Cell<u32>> {
registration: Registration<'d, L>,
pub(super) state: cell::Cell<State>,
pub(super) resident: L::Slot,
pub(super) data: cell::Cell<MaybeUninit<Data<'d, L>>>,
pub(super) domain: &'d arena::root::Domain<'d, L>,
}
impl<'d, L: Layout> provided::Account<'d, L> {
pub(in crate::buffer) fn payer(&self) -> resident::Budget<'d> {
unsafe {
self.as_ptr()
.cast::<Entry<'d, L>>()
.as_ref()
.data
.get()
.assume_init()
.budget
}
}
}
impl<L: Layout> Registration<'_, L> {
pub(in crate::buffer) fn resident(&self) -> usize {
unsafe {
ptr::NonNull::from(self)
.cast::<Entry<'_, L>>()
.as_ref()
.capacity() as usize
}
}
}
impl<'d, L: Layout> provided::Prefix<'_, 'd, &[u8], L> {
#[inline]
pub(in crate::buffer) fn try_account_with<A, F, T>(
&self,
budget: resident::Budget<'d>,
admission: A,
place: &mut MaybeUninit<T>,
) -> Result<ops::ControlFlow<A::Declined>, account::Cause>
where
A: resident::Admission,
F: From<storage::Shared<Option<provided::Account<'d, L>>>>,
T: From<F>,
{
if self.bytes.is_empty() {
place.write(T::from(F::from(storage::Shared::<
Option<provided::Account<'d, L>>,
>::new())));
return Ok(ops::ControlFlow::Continue(()));
}
let pointer = self.owner.entry;
let entry: &'d Entry<'d, L> = unsafe { pointer.as_ref() };
let registration = &entry.registration;
if !registration.is_empty() {
let paying = unsafe { entry.data.get().assume_init().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()) };
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(MaybeUninit::new(Data { budget }));
unsafe { registration.activate() };
}
let owner = unsafe { provided::Account::from_raw(pointer.cast()) };
let extent = unsafe { storage::Shared::assume(self.bytes, Some(owner)) };
place.write(T::from(F::from(extent)));
Ok(ops::ControlFlow::Continue(()))
}
}
impl<'d, L: Layout> Entry<'d, L> {
pub(super) fn new(
domain: &'d arena::root::Domain<'d, L>,
resident: L::Slot,
data: MaybeUninit<Data<'d, L>>,
) -> Self {
Self {
registration: Registration {
count: raw::Count::empty(),
scope: marker::PhantomData,
},
state: cell::Cell::new(State::Empty),
resident,
data: cell::Cell::new(data),
domain,
}
}
pub(in crate::buffer::storage::provided) unsafe fn capacity(&self) -> u32 {
unsafe { L::resident(&self.resident, &self.domain.resident) }
}
unsafe fn refund(&self, domain: &arena::root::Domain<'d, L>) {
unsafe {
self.data
.get()
.assume_init()
.budget
.release(L::resident(&self.resident, &domain.resident) as usize)
};
}
pub(super) unsafe fn refund_ended(&self) {
if !matches!(self.state.get(), State::Empty) && !self.registration.is_empty() {
unsafe { self.refund(self.domain) };
}
}
pub(super) unsafe fn release(owner: &mut provided::Owner<'d, L>) {
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) unsafe fn revoke<T>(
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(entry.domain) };
}
Some(unsafe { slot.occupied() })
}
}
}
}
impl<T, L: Layout> arena::Slot<'_, T, L> {
pub(super) unsafe fn take_returned(&self) -> T {
let value = unsafe { self.occupied() }.into_inner();
self.entry.state.set(State::Empty);
value
}
}
impl<'d, L: Layout> arena::Ready<'d, L> {
pub(super) fn publish(self, view: Projection<'d, '_>) -> provided::Unique<'d, L> {
unsafe { self.entry.as_ref() }.state.set(State::Occupied);
provided::Unique::new(view, provided::Owner { entry: self.entry })
}
}
unsafe impl<L: Layout> raw::Edge for Registration<'_, L> {
fn count(&self) -> &raw::Count {
&self.count
}
}
unsafe impl<'d, L: Layout> raw::Target for Registration<'d, L> {
unsafe fn destroy(pointer: ptr::NonNull<Self>) {
let pointer = pointer.cast::<Entry<'d, L>>();
let entry = unsafe { pointer.as_ref() };
let domain = entry.domain;
domain.accounted.0.set(domain.accounted.0.get() - 1);
unsafe { entry.refund(domain) };
if matches!(entry.state.get(), State::ReturnOnLastAccount) {
domain.finish(arena::Ready { entry: pointer });
}
}
}
const _: () = {
assert!(size_of::<Entry<'_>>() == 4 * size_of::<usize>());
assert!(size_of::<Entry<'_, ()>>() == 3 * size_of::<usize>());
assert!(align_of::<Entry<'_>>() == 8);
};
pub trait Layout: capacity::Sealed + std::fmt::Debug + Unpin + 'static {
type Slot;
type Shared;
fn empty() -> Self::Slot;
unsafe fn resident(slot: &Self::Slot, shared: &Self::Shared) -> u32;
}
mod capacity {
pub trait Sealed {}
impl Sealed for () {}
impl Sealed for std::cell::Cell<u32> {}
}
impl Layout for () {
type Slot = ();
type Shared = NonZero<u32>;
fn empty() {}
unsafe fn resident(_: &(), shared: &Self::Shared) -> u32 {
shared.get()
}
}
impl Layout for cell::Cell<u32> {
type Slot = cell::Cell<MaybeUninit<u32>>;
type Shared = ();
fn empty() -> Self::Slot {
cell::Cell::new(MaybeUninit::uninit())
}
unsafe fn resident(slot: &Self::Slot, _: &()) -> u32 {
unsafe { slot.get().assume_init() }
}
}
impl<L: Layout> Clone for Data<'_, L> {
fn clone(&self) -> Self {
*self
}
}
impl<L: Layout> Copy for Data<'_, L> {}