use std::{
marker,
mem::{MaybeUninit, needs_drop, size_of},
num::NonZero,
ptr, slice,
};
use runtime::entry;
type Index = bounded::raw::U32<0, { u32::MAX - 1 }>;
use crate::{
alloc,
base::{marker::ThreadBound, num::bounded},
depot::{
arena::{
hash::{self, errors, runtime},
slab::key,
},
map,
queue::links,
},
};
pub struct Core<T, Tag = ()> {
pub(super) directory: map::raw::Table<Index>,
thread: marker::PhantomData<ThreadBound>,
meta: ptr::NonNull<Meta>,
pub(super) dense: ptr::NonNull<Index>,
pub(super) values: ptr::NonNull<MaybeUninit<T>>,
plan: hash::Plan,
pub(in crate::depot::arena::hash) len: u32,
pub(super) free: Option<links::Index>,
tag: marker::PhantomData<fn(Tag) -> Tag>,
}
impl<T, Tag> Core<T, Tag> {
pub(in crate::depot::arena::hash) fn try_new(
plan: hash::Plan,
) -> Result<Self, crate::alloc::Error> {
let capacity = plan.capacity().get();
let table = plan.table.layout();
let buckets = table.buckets();
let bundle = alloc::raw::Recipe::try_build(Self::recipe(table))?;
let fields = bundle.try_allocate()?;
let dir = unsafe { map::raw::Table::from_fields(fields.prior().prior().prior(), buckets) };
let meta = fields.prior().prior().tail();
let dense = fields.prior().tail();
let values = fields.tail();
for index in 0..capacity {
let next = if index + 1 == capacity {
None
} else {
Some(unsafe { links::Index::new_usize(index + 1) })
};
unsafe { meta.as_ptr().add(index).write(Meta::vacant(next)) };
}
Ok(Self {
directory: dir,
thread: marker::PhantomData,
meta,
dense,
values,
plan,
len: 0,
free: (capacity != 0).then_some(NonZero::<u32>::MIN.into()),
tag: marker::PhantomData,
})
}
pub(in crate::depot::arena::hash) const fn capacity(&self) -> usize {
self.plan.capacity().get()
}
fn position(&self, index: usize) -> Option<(Index, &Meta)> {
if index >= self.capacity() {
return None;
}
let index = unsafe { Index::from_proven(index as u32) };
Some((index, unsafe { self.meta(index) }))
}
pub(super) fn lookup(
&self,
key: key::Handle<runtime::Domain<Tag>>,
) -> Result<Index, errors::Lookup<Tag>> {
let Some((index, meta)) = self.position(key.index() as usize) else {
return Err(errors::Lookup::Index {
key,
capacity: self.capacity(),
});
};
if !meta.is_live() {
return Err(errors::Lookup::Vacant {
key,
actual: meta.generation,
});
}
if meta.generation != key.generation() {
return Err(errors::Lookup::Generation {
key,
actual: meta.generation,
});
}
Ok(index)
}
pub(in crate::depot::arena::hash) fn live_at(
&self,
index: usize,
) -> Option<(Index, key::Generation)> {
let (index, meta) = self.position(index)?;
meta.is_live().then_some((index, meta.generation))
}
pub(super) unsafe fn meta(&self, index: Index) -> &Meta {
unsafe { &*self.meta.as_ptr().add(index.into_usize()) }
}
pub(super) unsafe fn meta_mut(&mut self, index: Index) -> &mut Meta {
unsafe { &mut *self.meta.as_ptr().add(index.into_usize()) }
}
pub(super) unsafe fn value(&self, index: Index) -> &T {
unsafe { (&*self.values.as_ptr().add(index.into_usize())).assume_init_ref() }
}
pub(super) unsafe fn value_mut(&mut self, index: Index) -> &mut T {
unsafe { (&mut *self.values.as_ptr().add(index.into_usize())).assume_init_mut() }
}
pub(super) unsafe fn key_for(&self, index: Index) -> key::Handle<runtime::Domain<Tag>> {
key::Handle::new(index.get(), unsafe { self.meta(index) }.generation)
}
}
impl<T, Tag> Core<T, Tag> {
pub(in crate::depot::arena::hash) fn vacant(&mut self) -> Option<hash::Vacant<'_, T, Tag>> {
let index = Index::from_one(self.free?.position());
Some(hash::Vacant { core: self, index })
}
pub(super) unsafe fn live<P>(&mut self, index: Index) -> entry::Live<'_, T, Tag, P> {
entry::Live {
core: self,
index,
phase: marker::PhantomData,
}
}
pub(super) fn dense(&self) -> &[Index] {
unsafe { slice::from_raw_parts(self.dense.as_ptr(), self.len as usize) }
}
}
impl<T, Tag> Core<T, Tag> {
pub unsafe fn bind(
map: &mut runtime::Map<T, Tag>,
index: links::Index,
) -> entry::Live<'_, T, Tag> {
unsafe { map.core.live(Index::from_one(index.position())) }
}
pub unsafe fn project(entry: &entry::Live<'_, T, Tag>, index: links::Index) -> *mut T {
unsafe { entry.core.values.add(index.get()).cast::<T>().as_ptr() }
}
}
impl<T, Tag> Drop for Core<T, Tag> {
fn drop(&mut self) {
let recipe = Self::recipe(self.plan.table.layout());
let layout = unsafe { alloc::raw::Recipe::build(recipe) };
let pointer = self.directory.base();
if needs_drop::<T>() {
for &index in self.dense().iter().rev() {
unsafe {
self.values
.add(index.into_usize())
.as_mut()
.assume_init_drop()
};
}
}
unsafe { layout.deallocate(pointer) };
}
}
const _: () = assert!(size_of::<Core<u64>>() == 9 * size_of::<usize>());
impl<T, Tag> Core<T, Tag> {
fn recipe(table: map::raw::Layout<Index>) -> impl alloc::raw::Recipe<Fields = Fields<T>> {
use alloc::raw::Recipe as _;
let capacity = table.shape().capacity().get();
alloc::raw::Recipe::tail::<Meta>(table, capacity)
.tail::<Index>(capacity)
.tail::<MaybeUninit<T>>(capacity)
}
}
type Fields<T> = alloc::raw::Tail<
alloc::raw::Tail<
alloc::raw::Tail<<map::raw::Layout<Index> as alloc::raw::Recipe>::Fields, Meta>,
Index,
>,
MaybeUninit<T>,
>;
pub(super) const VACANT: u32 = 1 << 31;
#[derive(Clone, Copy)]
#[repr(C)]
pub(super) struct Meta {
pub(super) generation: key::Generation,
pub(super) slot: u32,
pub(super) bucket: Option<map::raw::Occupied>,
}
impl Meta {
pub(super) const FREE: u32 = (1 << 31) - 1;
fn vacant(next: Option<links::Index>) -> Self {
Self {
generation: key::Generation::MIN,
slot: VACANT | next.map_or(Self::FREE, links::Index::raw),
bucket: None,
}
}
const fn is_live(&self) -> bool {
self.slot & VACANT == 0
}
pub(super) fn next(&self) -> Option<links::Index> {
let next = self.slot & Self::FREE;
if next == Self::FREE {
None
} else {
Some(unsafe { links::Index::new_raw(next) })
}
}
}
const _: () = assert!(size_of::<Meta>() == 3 * size_of::<u32>());
const _: () = assert!(size_of::<Option<map::raw::Occupied>>() == size_of::<u32>());
unsafe impl<'a, T, Tag> map::raw::Query for &'a mut Core<T, Tag> {
const SPARE: bool = true;
type Payload = Index;
type Value = T;
type Occupied = entry::Live<'a, T, Tag, entry::Indexed>;
fn table(&self) -> &map::raw::Table<Self::Payload> {
&self.directory
}
fn value(entry: map::Found<&Self>) -> &T {
let (owner, payload) = entry.project();
let index = *payload;
unsafe { Core::value(owner, index) }
}
fn occupied(entry: map::Found<Self>) -> Self::Occupied {
let (owner, index) = entry.copied();
unsafe { owner.live(index) }
}
}
unsafe impl<'a, T, Tag> map::raw::Insertion for &'a mut Core<T, Tag> {
type Vacant = entry::Vacancy<'a, T, Tag>;
fn vacant(entry: map::Vacancy<Self>, hash: u64) -> Option<Self::Vacant> {
let (core, bucket, ()) = entry.into_parts();
let hash::Vacant { core, index } = core.vacant()?;
Some(entry::Vacancy {
core,
index,
bucket,
hash,
})
}
}
unsafe impl<T, Tag> map::raw::Mutation for &mut Core<T, Tag> {
unsafe fn table_mut(&mut self) -> &mut map::raw::Table<Self::Payload> {
&mut self.directory
}
unsafe fn shift(&mut self, hole: &map::raw::Vacant, next: &map::raw::Occupied, hash: u64) {
let (moved, index) = unsafe { self.directory.shift(hole, next, hash) };
let index = *index;
unsafe { self.meta_mut(index).bucket = Some(moved) };
}
}
unsafe impl<T, Tag, P> map::raw::Query for &runtime::Map<T, Tag, P> {
const SPARE: bool = true;
type Payload = Index;
type Value = T;
type Occupied = key::Handle<runtime::Domain<Tag>>;
fn table(&self) -> &map::raw::Table<Self::Payload> {
&self.core.directory
}
fn value(entry: map::Found<&Self>) -> &T {
let (owner, payload) = entry.project();
unsafe { owner.core.value(*payload) }
}
fn occupied(entry: map::Found<Self>) -> Self::Occupied {
let (owner, index) = entry.copied();
unsafe { owner.core.key_for(index) }
}
}
unsafe impl<T, Tag> map::raw::Query for entry::Live<'_, T, Tag, entry::Staged> {
type Payload = Index;
type Value = T;
type Occupied = (Self, key::Handle<runtime::Domain<Tag>>);
fn table(&self) -> &map::raw::Table<Self::Payload> {
&self.core.directory
}
fn value(entry: map::Found<&Self>) -> &T {
let (owner, index) = entry.project();
unsafe { owner.core.value(*index) }
}
fn occupied(entry: map::Found<Self>) -> Self::Occupied {
let (owner, index) = entry.copied();
let key = unsafe { owner.core.key_for(index) };
(owner, key)
}
}