use crate::{
alloc::{self, tail},
base::cell::region,
buffer::{self, resident, storage::provided::view},
mem::{self, Rejected, slot},
};
use std::{
cell, marker,
mem::{ManuallyDrop, MaybeUninit, align_of, needs_drop, offset_of, size_of},
num::NonZeroU32,
pin, ptr,
slice::Iter,
};
mod domain;
mod layout;
mod owner;
mod slice;
pub use layout::Layout;
pub use owner::Owner;
pub use slice::Slice;
pub(super) type Loan<'d, L = cell::Cell<u32>> = Slice<&'d mut [u8], Owner<'d, L>>;
use domain::{Data, Phase};
pub(super) use domain::{Domain, Entry};
type Link<L> = ptr::NonNull<Entry<L>>;
struct Node<'d, L: Layout, const READY: bool> {
entry: Link<L>,
scope: marker::PhantomData<fn(&'d L) -> &'d L>,
}
type Empty<'d, L> = Node<'d, L, false>;
type Ready<'d, L> = Node<'d, L, true>;
#[repr(transparent)]
pub struct Arena<T, C = (), L: Layout = cell::Cell<u32>> {
entries: tail::raw::Block<InactiveHeader<C, L>, MaybeUninit<Slot<T, L>>, NonZeroU32>,
}
#[repr(C)]
struct Header<C, S> {
state: S,
context: C,
}
type InactiveHeader<C, L> = Header<C, MaybeUninit<State<L>>>;
type ActiveHeader<C, L> = Header<C, State<L>>;
pub struct Scope<'d, T, L: Layout> {
scope: marker::PhantomData<fn(&'d ()) -> &'d ()>,
slots: Iter<'d, Slot<T, L>>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Full {
pub capacity: NonZeroU32,
}
pub struct Allocation<T, C, L: Layout> {
memory: tail::raw::Uninit<InactiveHeader<C, L>, Slot<T, L>, NonZeroU32>,
}
impl<T, C, L: Layout> Arena<T, C, L> {
pub fn try_allocate(entries: NonZeroU32) -> Result<Allocation<T, C, L>, alloc::Error> {
Ok(Allocation {
memory: tail::Plan::try_new(entries)?.try_allocate()?,
})
}
pub fn context(&self) -> &C {
&tail::raw::View::new(&self.entries).header().context
}
pub fn capacity(&self) -> NonZeroU32 {
self.entries.extent()
}
pub fn into_context(self) -> C {
self.entries.into_header().context
}
fn scope_in<S, R>(
&mut self,
state: pin::Pin<&mut S>,
resident: L::Shared,
run: impl for<'d> FnOnce(
region::Token<region::Identity<'d>>,
Root<'d, T, C, L>,
pin::Pin<&'d mut S>,
) -> R,
) -> R {
let mut input = (self, state);
region::Token::scope_pinned(pin::Pin::new(&mut input), |token, input| {
let (arena, state) = input.get_mut();
let root = unsafe { arena.prepare(arena.capacity().get(), resident) };
let scope = root.scope();
let result = run(token, root, state.as_mut());
for _item in scope {}
result
})
}
unsafe fn prepare<'d>(&'d mut self, limit: u32, resident: L::Shared) -> Root<'d, T, C, L> {
const {
assert!(size_of::<InactiveHeader<C, L>>() == size_of::<ActiveHeader<C, L>>());
assert!(align_of::<InactiveHeader<C, L>>() == align_of::<ActiveHeader<C, L>>());
assert!(
offset_of!(InactiveHeader<C, L>, context)
== offset_of!(ActiveHeader<C, L>, context)
);
}
let capacity = self.entries.extent();
let pointer = tail::raw::View::new(&self.entries).as_ptr();
let (header, values) = self.entries.parts_mut();
let mut free = None;
for slot in values.iter_mut() {
let entry = ptr::NonNull::from(slot).cast::<Entry<L>>();
unsafe {
entry
.as_ptr()
.write(Entry::new(pointer.cast(), MaybeUninit::new(Data { free })))
};
free = Some(entry);
}
header.state.write(State {
domain: Domain::new(resident, limit, capacity),
free: cell::Cell::new(free),
});
Root {
view: unsafe { tail::raw::View::from_raw(pointer) },
slots: marker::PhantomData,
}
}
}
impl<T, C, L: Layout> Allocation<T, C, L> {
pub fn initialize(self, context: C) -> Arena<T, C, L> {
Arena {
entries: self.memory.init(Header {
state: MaybeUninit::uninit(),
context,
}),
}
}
}
impl<T, C: buffer::raw::Fixed<T>> Arena<T, C, ()> {
pub unsafe fn enter(&mut self, accounts: u32) -> Root<'_, T, C, ()> {
let resident = self.context().resident();
unsafe { self.prepare(accounts, resident) }
}
pub unsafe fn refund_ended(&mut self) {
let pointer = tail::raw::View::new(&self.entries).as_ptr();
let root: Root<'_, T, C, ()> = Root {
view: unsafe { tail::raw::View::from_raw(pointer) },
slots: marker::PhantomData,
};
for _item in root.scope() {}
}
pub fn scope<S, R>(
&mut self,
state: pin::Pin<&mut S>,
run: impl for<'d> FnOnce(
region::Token<region::Identity<'d>>,
Root<'d, T, C, ()>,
pin::Pin<&'d mut S>,
) -> R,
) -> R {
let resident = self.context().resident();
self.scope_in(state, resident, run)
}
}
impl<'d, T, L: Layout> Iterator for Scope<'d, T, L> {
type Item = slot::Occupied<'d, T>;
fn next(&mut self) -> Option<Self::Item> {
for slot in self.slots.by_ref() {
if !matches!(unsafe { slot.entry.refund_ended() }, Phase::Empty) {
return Some(unsafe { slot.occupied() });
}
}
None
}
}
const _: () = {
assert!(!needs_drop::<State<()>>());
assert!(size_of::<Arena<(), (), ()>>() == size_of::<usize>());
assert!(size_of::<Root<'_, (), (), ()>>() == size_of::<usize>());
};
impl<T, C> Arena<T, C> {
pub unsafe fn enter_scope(&mut self) -> (Root<'_, T, C>, Scope<'_, T, cell::Cell<u32>>) {
let root = unsafe { self.prepare(self.capacity().get(), ()) };
(root, root.scope())
}
pub fn scope<S, R>(
&mut self,
state: pin::Pin<&mut S>,
run: impl for<'d> FnOnce(
region::Token<region::Identity<'d>>,
Root<'d, T, C>,
pin::Pin<&'d mut S>,
) -> R,
) -> R {
self.scope_in(state, (), run)
}
}
#[repr(C, align(8))]
struct Slot<T, L: Layout> {
entry: Entry<L>,
item: cell::UnsafeCell<MaybeUninit<T>>,
}
impl<T, L: Layout> Slot<T, L> {
unsafe fn occupied(&self) -> slot::Occupied<'_, T> {
unsafe { slot::raw::Vacant::new(&mut *self.item.get()).assume_init() }
}
}
#[repr(transparent)]
pub struct Root<'d, T, C = (), L: Layout = cell::Cell<u32>> {
view: tail::raw::View<'d, ActiveHeader<C, L>, Slot<T, L>, NonZeroU32>,
slots: SlotDomain<'d, T, L>,
}
impl<'d, T, C, L: Layout> Root<'d, T, C, L> {
fn scope(self) -> Scope<'d, T, L> {
Scope {
scope: marker::PhantomData,
slots: self.view.as_slice().iter(),
}
}
pub fn context(&self) -> &'d C {
&self.view.header().context
}
pub fn capacity(&self) -> NonZeroU32 {
self.view.len_proof().extent()
}
fn next_free<X: Copy>(&self, context: X) -> Option<Vacant<'d, T, L, X>> {
let state = &self.view.header().state;
let entry = state.free.get()?;
let slot = unsafe { entry.cast::<Slot<T, L>>().as_ref() };
state
.free
.set(unsafe { slot.entry.data.get().assume_init().free });
Some(Vacant { slot, context })
}
pub fn pop_returned(&self) -> Option<T> {
let state = &self.view.header().state;
let head = state.domain.returned.pop()?;
let slot = unsafe { head.cast::<Slot<T, L>>().as_ref() };
let value = unsafe { slot.occupied() }.into_inner();
state.push_free(Empty {
entry: head,
scope: marker::PhantomData,
});
Some(value)
}
pub fn has_returned(&self) -> bool {
self.view.header().state.domain.returned.has_items()
}
}
impl<T, C, L: Layout> Clone for Root<'_, T, C, L> {
fn clone(&self) -> Self {
*self
}
}
impl<T, C, L: Layout> Copy for Root<'_, T, C, L> {}
impl<'d, T, C> Root<'d, T, C> {
pub fn vacant(&self) -> Option<Vacant<'d, T>> {
self.next_free(())
}
}
impl<'d, T, C> Root<'d, T, C, ()> {
pub fn try_vacant(&self) -> Result<Vacant<'d, T, (), &'d C>, Full> {
self.next_free(self.context()).ok_or(Full {
capacity: self.capacity(),
})
}
}
#[repr(C)]
struct State<L: Layout> {
domain: Domain<L>,
free: cell::Cell<Option<Link<L>>>,
}
impl<L: Layout> State<L> {
fn push_free(&self, node: Empty<'_, L>) {
unsafe { node.entry.as_ref() }
.data
.set(MaybeUninit::new(Data {
free: self.free.get(),
}));
self.free.set(Some(node.entry));
}
unsafe fn from_domain<'d>(domain: ptr::NonNull<Domain<L>>) -> &'d Self {
unsafe { domain.cast::<Self>().as_ref() }
}
}
type SlotDomain<'d, T, L> = marker::PhantomData<fn(&'d Slot<T, L>) -> &'d Slot<T, L>>;
pub struct Vacant<'d, T, L: Layout = cell::Cell<u32>, C: Copy = ()> {
slot: &'d Slot<T, L>,
context: C,
}
impl<T, L: Layout, C: Copy> Drop for Vacant<'_, T, L, C> {
fn drop(&mut self) {
unsafe { State::from_domain(self.slot.entry.domain) }.push_free(Empty {
entry: ptr::NonNull::from(self.slot).cast(),
scope: marker::PhantomData,
});
}
}
impl<'d, T, L: Layout, C: Copy> Vacant<'d, T, L, C> {
fn publish(self, view: buffer::raw::Projection<'d, '_>) -> Loan<'d, L> {
let slot = ManuallyDrop::new(self).slot;
unsafe { Slice::publish(&slot.entry, view.into_inner()) }
}
}
impl<'d, T: AsMut<[u8]>> Vacant<'d, T> {
pub fn try_insert(
self,
item: T,
resident: u32,
) -> Result<Loan<'d>, Rejected<T, view::LengthError>> {
let slot = self.slot;
let item = unsafe { (*slot.item.get()).write(item) };
buffer::raw::Limit::scope(resident, |limit| {
let view = match limit.try_project(item.as_mut()) {
Ok(view) => view,
Err(error) => {
let item = unsafe { (*slot.item.get()).assume_init_read() };
return Err(Rejected::new(item, error));
}
};
slot.entry.resident.set(MaybeUninit::new(resident));
Ok(self.publish(view))
})
}
}
impl<'d, T, C> Vacant<'d, T, (), &'d C> {
pub fn context(&self) -> &'d C {
self.context
}
pub(in crate::buffer) unsafe fn insert_fixed(self, item: T) -> Loan<'d, ()>
where
C: buffer::raw::Fixed<T>,
{
let resident = unsafe { self.slot.entry.capacity() };
let context = self.context;
buffer::raw::Limit::scope(resident, |limit| {
let item = unsafe { (*self.slot.item.get()).write(item) };
self.publish(unsafe { context.project(item, limit) })
})
}
}
const _: () = {
assert!(offset_of!(Slot<u8, ()>, item) == size_of::<Entry<()>>());
assert!(offset_of!(Slot<u64, cell::Cell<u32>>, item) == size_of::<Entry>());
assert!(size_of::<Vacant<'_, ()>>() == size_of::<usize>());
assert!(size_of::<Vacant<'_, (), (), &'_ ()>>() == 2 * size_of::<usize>());
};
#[derive(Debug)]
#[repr(transparent)]
pub struct Registration<'d, L: Layout = cell::Cell<u32>> {
count: mem::raw::Count,
scope: marker::PhantomData<fn(&'d L) -> &'d L>,
}
impl<'d, L: Layout> Registration<'d, L> {
pub(in crate::buffer) fn payer(owner: &mem::raw::Owner<Self>) -> resident::Budget<'d> {
unsafe { owner.as_ptr().cast::<Entry<L>>().as_ref().payer() }
}
pub(in crate::buffer) fn resident(owner: &mem::raw::Owner<Self>) -> usize {
unsafe { owner.as_ptr().cast::<Entry<L>>().as_ref().capacity() as usize }
}
}
unsafe impl<L: Layout> mem::raw::Edge for Registration<'_, L> {
fn count(&self) -> &mem::raw::Count {
&self.count
}
}
unsafe impl<'d, L: Layout> mem::raw::Target for Registration<'d, L> {
unsafe fn destroy(pointer: ptr::NonNull<Self>) {
let pointer = pointer.cast::<Entry<L>>();
let entry = unsafe { pointer.as_ref() };
let domain = unsafe { entry.domain.as_ref() };
domain.accounted.set(domain.accounted.get() - 1);
unsafe { entry.refund() };
if matches!(entry.state.get(), Phase::ReturnOnLastAccount) {
domain.returned.finish(Ready {
entry: pointer,
scope: marker::PhantomData,
});
}
}
}
impl<L: Layout> buffer::Residency for Option<mem::raw::Owner<Registration<'_, L>>> {
fn resident(&self) -> usize {
self.as_ref().map_or(0, Registration::resident)
}
}