use std::{mem, ptr};
use crate::{
base::num::Generation,
depot::{
map,
map::resident::{self, Key, Table, scoped},
queue::links,
},
};
pub(super) const FREE: u64 = 1 << 63;
pub(super) fn slot<const MAX: u32>(key: Key<MAX>) -> links::Index {
unsafe { links::Index::new_raw(key.index()) }
}
pub(super) unsafe fn published<T, H, const MAX: u32>(
table: &Table<T, H, MAX>,
index: links::Index,
) -> &Record<T, MAX> {
unsafe { table.records.get_unchecked(index.get()).live() }
}
pub(super) unsafe fn value_mut<T, H, const MAX: u32>(
table: &mut Table<T, H, MAX>,
index: usize,
) -> &mut T {
unsafe {
table
.records
.get_unchecked_mut(index)
.value
.assume_init_mut()
}
}
pub(super) fn project<'a, 'id, T, H, const MAX: u32>(
scope: &'a mut scoped::Scope<'_, 'id, T, H, MAX>,
lease: &scoped::Lease<'id, MAX>,
) -> &'a mut T {
unsafe { value_mut(scope.table, lease.key().index() as usize) }
}
unsafe impl<T, H: map::Hasher<resident::Id>, const MAX: u32> map::raw::Directory
for Table<T, H, MAX>
{
type Occupied = (map::raw::Occupied, links::Index);
fn buckets(&self) -> usize {
self.buckets.len()
}
unsafe fn hash(&self, index: usize) -> Option<u64> {
let slot = unsafe { *self.buckets.get_unchecked(index) }?;
Some(self.hash.hash(&unsafe { published(self, slot) }.id()))
}
unsafe fn candidate(&self, index: usize, _: u64) -> map::raw::Candidate<Self::Occupied> {
match unsafe { *self.buckets.get_unchecked(index) } {
Some(slot) => {
map::raw::Candidate::Occupied((unsafe { map::raw::Occupied::new(index) }, slot))
}
None => map::raw::Candidate::Vacant,
}
}
}
unsafe impl<T, H: map::Hasher<resident::Id>, const MAX: u32> map::raw::Shift for Table<T, H, MAX> {
fn directory(&self) -> &impl map::raw::Directory {
self
}
unsafe fn shift(&mut self, hole: &map::raw::Vacant, next: &map::raw::Occupied, _: u64) {
let cell = unsafe { self.buckets.get_unchecked_mut(next.index()) }.take();
unsafe { *self.buckets.get_unchecked_mut(hole.index()) = cell };
}
}
#[repr(C)]
pub(super) struct Record<T, const MAX: u32> {
pub(super) id: u64,
pub(super) generation: Generation<MAX>,
pub(super) value: T,
}
impl<T, const MAX: u32> Record<mem::MaybeUninit<T>, MAX> {
pub(super) fn new(id: resident::Id, value: T) -> Self {
Self {
id: id.get(),
generation: Generation::INITIAL,
value: mem::MaybeUninit::new(value),
}
}
pub(super) const fn is_live(&self) -> bool {
self.id & FREE == 0
}
pub(super) unsafe fn live(&self) -> &Record<T, MAX> {
unsafe { &*ptr::from_ref(self).cast() }
}
}
impl<T, const MAX: u32> Record<T, MAX> {
pub(super) fn has_id(&self, id: resident::Id) -> bool {
self.id == id.get()
}
pub(super) fn id(&self) -> resident::Id {
resident::Id::mask(self.id)
}
}
const _: () = assert!(mem::size_of::<Record<mem::MaybeUninit<[u32; 3]>, { u32::MAX }>>() == 24);