use std::{
array, cell, convert::Infallible, fmt::Debug, hint, marker, mem::MaybeUninit, num::NonZero,
ops, ptr,
};
pub(crate) use account::Account;
use crate::{
base::marker::ThreadBound,
mem::{credit::fair, lease, quota, rc},
};
mod account;
mod occupied;
mod owner;
mod storage;
mod vacant;
pub use occupied::Occupied;
pub use owner::Owner;
pub use storage::Storage;
pub use vacant::Vacant;
pub(crate) unsafe fn initialized<T>(source: &Option<T>) -> &T {
unsafe { source.as_slice().get_unchecked(0) }
}
unsafe fn initialized_mut<T>(source: &mut Option<T>) -> &mut T {
unsafe { &mut *source.as_mut_slice().as_mut_ptr() }
}
pub unsafe trait Convert<T, const BRANCH: u8 = 0> {
fn into(self) -> T;
unsafe fn take_into(source: *mut Self, place: &mut MaybeUninit<T>)
where
Self: Sized,
{
place.write(<Self as Convert<T, BRANCH>>::into(unsafe { source.read() }));
}
}
unsafe impl<T> Convert<T> for T {
fn into(self) -> T {
self
}
}
unsafe impl Convert<()> for Infallible {
fn into(self) {
match self {}
}
}
unsafe impl<L, R> Convert<crate::base::Either<L, R>, 1> for L {
fn into(self) -> crate::base::Either<L, R> {
crate::base::Either::Left(self)
}
}
unsafe impl<L, R> Convert<crate::base::Either<L, R>, 2> for R {
fn into(self) -> crate::base::Either<L, R> {
crate::base::Either::Right(self)
}
}
pub(crate) fn cast_uninit<T, U, const N: usize>(
source: &mut [MaybeUninit<T>; N],
) -> &mut [MaybeUninit<U>; N] {
const {
assert!(size_of::<U>() <= size_of::<T>(), "size");
assert!(align_of::<T>().is_multiple_of(align_of::<U>()), "align");
};
unsafe { &mut *ptr::from_mut(source).cast::<[MaybeUninit<U>; N]>() }
}
#[derive(Debug)]
#[repr(transparent)]
pub struct Count<W: Counter = u32> {
value: cell::Cell<W>,
thread: ThreadBound,
}
impl<W: Counter> Count<W> {
pub const fn empty() -> Self {
Self {
value: cell::Cell::new(W::ZERO),
thread: ThreadBound::NEW,
}
}
pub const fn one() -> Self {
Self {
value: cell::Cell::new(W::ONE),
thread: ThreadBound::NEW,
}
}
}
const _: () = assert!(size_of::<Count>() == size_of::<u32>());
pub unsafe trait Edge<W: Counter = u32> {
fn count(&self) -> &crate::mem::raw::Count<W>;
#[inline]
fn is_empty(&self) -> bool {
self.count().value.get() == W::ZERO
}
#[inline]
fn is_unique(&self) -> bool {
self.count().value.get() == W::ONE
}
#[inline]
unsafe fn activate(&self) {
self.count().value.set(W::ONE);
}
unsafe fn start_pair(&self) {
self.count().value.set(W::TWO);
}
unsafe fn retire(&self) {
self.count().value.set(W::ZERO);
}
#[inline]
unsafe fn try_retain(&self) -> Result<(), rc::Error> {
let count = self.count();
let current: W = Into::into(unsafe { count.value.get().nonzero() });
count
.value
.set(current.checked_add(W::ONE).ok_or(rc::Error::Exhausted)?);
Ok(())
}
#[inline]
unsafe fn release(&self) -> rc::Release {
let count = self.count();
let current: W = Into::into(unsafe { count.value.get().nonzero() });
let next = current - W::ONE;
let release = if next == W::ZERO {
rc::Release::Last
} else {
rc::Release::Shared
};
count.value.set(next);
release
}
}
pub unsafe trait Target<W: Counter = u32>: crate::mem::raw::Edge<W> + Sized {
unsafe fn destroy(pointer: ptr::NonNull<Self>);
}
pub unsafe trait Amount<const N: usize, W: crate::mem::raw::Word>: Copy + Eq {
const AXES: ops::Range<usize> = 0..N;
fn get(self) -> [W; N];
fn try_acquire<const COMMIT: bool>(
self,
held: &cell::Cell<[W; N]>,
shared: &cell::Cell<[W; N]>,
reserve: &[W; N],
) -> Result<(), fair::Cause<W, N>> {
let amount = self.get();
let held = held.as_array_of_cells();
let shared = shared.as_array_of_cells();
let mut next = [const { MaybeUninit::<(W, W)>::uninit() }; N];
for index in Self::AXES {
let current = held[index].get();
let request = amount[index];
let Some(total) = current.checked_add(request) else {
hint::cold_path();
return Err(fair::Cause::Overflow {
axis: fair::Axis::<N>::ALL[index],
held: current,
requested: request,
});
};
let required = required(current, reserve[index], request);
let spare = shared[index].get();
if required > spare {
return Err(fair::Cause::Exhausted {
axis: fair::Axis::<N>::ALL[index],
required,
available: spare,
});
}
if COMMIT {
next[index].write((total, spare - required));
}
}
if COMMIT {
for index in Self::AXES {
let (owned, spare) = unsafe { next[index].assume_init() };
held[index].set(owned);
shared[index].set(spare);
}
}
Ok(())
}
unsafe fn acquire(
self,
held: &cell::Cell<[W; N]>,
shared: &cell::Cell<[W; N]>,
reserve: &[W; N],
) {
let amount = self.get();
let held = held.as_array_of_cells();
let shared = shared.as_array_of_cells();
for axis in Self::AXES {
let current = held[axis].get();
let required = required(current, reserve[axis], amount[axis]);
held[axis].set(current + amount[axis]);
shared[axis].set(shared[axis].get() - required);
}
}
fn demand(self, held: &cell::Cell<[W; N]>, reserve: &[W; N]) -> [W; N] {
let amount = self.get();
let held = held.as_array_of_cells();
array::from_fn(|axis| required(held[axis].get(), reserve[axis], amount[axis]))
}
unsafe fn release(
self,
held: &cell::Cell<[W; N]>,
shared: &cell::Cell<[W; N]>,
reserve: &[W; N],
) {
let amount = self.get();
let held = held.as_array_of_cells();
let shared = shared.as_array_of_cells();
for axis in Self::AXES {
let current = held[axis].get();
let returned = current.sub_or_zero(reserve[axis]).min(amount[axis]);
held[axis].set(current - amount[axis]);
shared[axis].set(shared[axis].get() + returned);
}
}
}
fn required<W: Word>(held: W, reserve: W, amount: W) -> W {
amount.sub_or_zero(reserve.sub_or_zero(held))
}
unsafe impl<const N: usize, W: crate::mem::raw::Word> Amount<N, W> for [W; N] {
fn get(self) -> [W; N] {
self
}
}
unsafe impl<const N: usize, W: Word> Sum<N, W> for [W; N] {
unsafe fn add_raw(self, other: Self) -> Self {
array::from_fn(|axis| self[axis] + other[axis])
}
}
pub unsafe trait Sum<const N: usize, W: Word>: Amount<N, W> {
unsafe fn add_raw(self, other: Self) -> Self;
}
pub unsafe trait Word:
Copy + Eq + Ord + ops::Add<Output = Self> + ops::Sub<Output = Self> + owner::Sealed
{
const ZERO: Self;
fn checked_add(self, other: Self) -> Option<Self>;
fn sub_or_zero(self, other: Self) -> Self;
}
unsafe impl Word for u32 {
const ZERO: Self = 0;
fn checked_add(self, other: Self) -> Option<Self> {
self.checked_add(other)
}
fn sub_or_zero(self, other: Self) -> Self {
self.saturating_sub(other)
}
}
unsafe impl Word for usize {
const ZERO: Self = 0;
fn checked_add(self, other: Self) -> Option<Self> {
self.checked_add(other)
}
fn sub_or_zero(self, other: Self) -> Self {
self.saturating_sub(other)
}
}
pub trait Counter: Word {
type NonZero: Copy + Debug + Into<Self>;
const ONE: Self;
const TWO: Self;
unsafe fn nonzero(self) -> Self::NonZero;
}
impl Counter for u32 {
type NonZero = NonZero<Self>;
const ONE: Self = 1;
const TWO: Self = 2;
unsafe fn nonzero(self) -> Self::NonZero {
unsafe { NonZero::new_unchecked(self) }
}
}
impl Counter for usize {
type NonZero = NonZero<Self>;
const ONE: Self = 1;
const TWO: Self = 2;
unsafe fn nonzero(self) -> Self::NonZero {
unsafe { NonZero::new_unchecked(self) }
}
}
#[must_use = "unused quota is returned when the shared reservation is dropped"]
#[repr(C)]
pub struct Shared<'source, Tag = (), M = lease::Sealed> {
source: &'source Account,
remaining: quota::Ledger<Tag>,
mode: marker::PhantomData<M>,
}
impl<'source, Tag, M> Shared<'source, Tag, M> {
pub fn reserve_up<SourceTag>(source: &'source quota::Ledger<SourceTag>, limit: usize) -> Self {
Self {
source: &source.remaining,
remaining: quota::Ledger::new(source.remaining.reserve_up(limit)),
mode: marker::PhantomData,
}
}
pub fn reserve_all<SourceTag>(source: &'source quota::Ledger<SourceTag>) -> Self {
Self::reserve_up(source, usize::MAX)
}
pub fn lease_up_to<ChildTag>(&self, limit: usize) -> quota::Lease<'_, ChildTag> {
quota::Lease::reserve_up(&self.remaining, limit)
}
pub fn remaining(&self) -> usize {
self.remaining.remaining()
}
}
impl<'source, Tag> Shared<'source, Tag, lease::Open> {
pub fn reserve<SourceTag>(
source: &'source quota::Ledger<SourceTag>,
limit: NonZero<usize>,
debit: bool,
) -> Option<Self> {
let unused = limit.get() - 1;
let source = &source.remaining;
source.reserve(unused + usize::from(debit)).ok()?;
Some(Self {
source,
remaining: quota::Ledger::new(unused),
mode: marker::PhantomData,
})
}
pub unsafe fn settle(&mut self, unused: usize) {
self.remaining.reset(unused);
}
}
impl<Tag, M> Drop for Shared<'_, Tag, M> {
fn drop(&mut self) {
self.source.refund_spare(self.remaining.remaining());
}
}