use std::{cell, marker, mem, num::NonZero, ptr};
use super::{entry, root::Domain};
use crate::{
alloc::{self, tail},
buffer::storage::provided,
mem::slot,
};
pub unsafe trait Context {
fn resident(&self) -> NonZero<u32>;
unsafe fn project(&self, bid: u16, len: usize) -> &mut [u8];
}
#[repr(C)]
struct Header<C, D = mem::MaybeUninit<Domain<'static, ()>>> {
domain: D,
issued: cell::Cell<u32>,
context: C,
}
pub struct Allocation<C> {
memory: tail::Uninit<Header<C>, entry::Entry<'static, ()>, NonZero<u16>>,
}
pub struct Arena<C> {
entries: tail::Block<Header<C>, mem::MaybeUninit<entry::Entry<'static, ()>>, NonZero<u16>>,
}
pub struct Root<'d, C> {
header: &'d Header<C, Domain<'d, ()>>,
}
pub struct Pending<'d, C> {
entry: ptr::NonNull<entry::Entry<'d, ()>>,
context: marker::PhantomData<&'d C>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Index {
pub index: u16,
pub capacity: NonZero<u16>,
}
pub use provided::view::LengthError as Length;
impl<C> Arena<C> {
pub fn try_allocate(count: NonZero<u16>) -> Result<Allocation<C>, alloc::Error> {
Ok(Allocation {
memory: tail::Plan::try_new(count)?.try_allocate()?,
})
}
pub fn context(&self) -> &C {
&tail::View::new(&self.entries).header().context
}
pub fn capacity(&self) -> NonZero<u32> {
self.entries.extent().into()
}
pub fn into_context(self) -> C {
self.entries.into_header().context
}
pub unsafe fn refund_ended(&mut self) {
for entry in self.entries.as_mut_slice() {
unsafe { entry.assume_init_ref().refund_ended() };
}
}
}
impl<C: Context> Arena<C> {
pub unsafe fn enter(&mut self, accounts: u32) -> Root<'_, C> {
const {
assert!(size_of::<Header<C>>() == size_of::<Header<C, Domain<'_, ()>>>());
assert!(align_of::<Header<C>>() == align_of::<Header<C, Domain<'_, ()>>>());
assert!(
mem::offset_of!(Header<C>, context)
== mem::offset_of!(Header<C, Domain<'_, ()>>, context)
);
}
let capacity = self.entries.extent();
let resident = self.context().resident();
let (header, entries) = self.entries.parts_mut();
let pointer = ptr::from_mut(header).cast::<Header<C, Domain<'_, ()>>>();
let header = unsafe {
(&raw mut (*pointer).domain)
.write(Domain::new(resident, accounts.min(u32::from(capacity.get()))));
&*pointer
};
header.issued.set(0);
for entry in entries {
unsafe {
entry
.as_mut_ptr()
.cast::<entry::Entry<'_, ()>>()
.write(entry::Entry::new(
&header.domain,
(),
mem::MaybeUninit::uninit(),
))
};
}
Root { header }
}
}
impl<C> Allocation<C> {
pub fn initialize(self, context: C) -> Arena<C> {
Arena {
entries: self.memory.init(Header {
domain: mem::MaybeUninit::uninit(),
issued: cell::Cell::new(0),
context,
}),
}
}
}
impl<'d, C> Root<'d, C> {
fn view(
&self,
) -> tail::View<'d, Header<C, Domain<'d, ()>>, entry::Entry<'d, ()>, NonZero<u16>> {
unsafe { tail::View::from_raw(ptr::NonNull::from(self.header).cast()) }
}
pub fn context(&self) -> &'d C {
&self.header.context
}
pub fn capacity(&self) -> NonZero<u32> {
self.view().len_proof().extent().into()
}
pub fn is_full(&self) -> bool {
self.header.issued.get() == self.capacity().get()
}
pub fn has_returned(&self) -> bool {
self.header.domain.tail.get().is_some()
}
pub unsafe fn select(&self, bid: u16) -> Result<Pending<'d, C>, Index> {
let view = self.view();
let entry = match view.as_slice().get(usize::from(bid)) {
Some(entry) => entry,
None => {
return Err(Index {
index: bid,
capacity: view.len_proof().extent(),
});
}
};
Ok(Pending {
entry: ptr::NonNull::from(entry),
context: marker::PhantomData,
})
}
pub fn pop_returned(&self) -> Option<u16> {
let entry = self.header.domain.pop_returned()?;
let pending = Pending {
entry,
context: marker::PhantomData::<&C>,
};
unsafe { entry.as_ref() }.state.set(entry::State::Empty);
self.header.issued.set(self.header.issued.get() - 1);
Some(pending.into_index())
}
}
impl<C> Copy for Root<'_, C> {}
impl<C> Clone for Root<'_, C> {
fn clone(&self) -> Self {
*self
}
}
impl<'d, C> Pending<'d, C> {
fn root(&self) -> Root<'d, C> {
let header = unsafe {
&*ptr::from_ref(self.entry.as_ref().domain).cast::<Header<C, Domain<'d, ()>>>()
};
Root { header }
}
pub fn into_index(self) -> u16 {
let root = self.root();
let index = unsafe {
self.entry
.as_ptr()
.offset_from(root.view().as_slice().as_ptr())
};
index as u16
}
}
impl<'d, C: Context> Pending<'d, C> {
pub unsafe fn publish<'event>(
self,
original_bid: u16,
len: usize,
output: slot::Vacant<'event, provided::Unique<'d, ()>>,
) -> Result<slot::Occupied<'event, provided::Unique<'d, ()>>, (Self, Length)> {
let root = self.root();
let capacity = root.header.domain.resident.get();
if len > capacity as usize {
return Err((self, Length::new(len, capacity)));
}
let bytes = unsafe { root.context().project(original_bid, len) };
unsafe { self.entry.as_ref() }
.state
.set(entry::State::Occupied);
root.header.issued.set(root.header.issued.get() + 1);
Ok(output.insert(provided::Unique {
bytes,
owner: provided::Owner { entry: self.entry },
}))
}
}
const _: () = {
assert!(size_of::<Root<'_, ()>>() == size_of::<usize>());
assert!(size_of::<Pending<'_, ()>>() == size_of::<usize>());
assert!(size_of::<Arena<()>>() == size_of::<usize>());
};