use std::{marker, mem, ptr};
use crate::depot::{index::Stored, map::direct};
#[repr(C)]
pub(in crate::depot) struct Entry<K: crate::depot::raw::Key, V> {
pub(in crate::depot) key: K::Raw,
pub(in crate::depot) value: mem::MaybeUninit<V>,
domain: crate::depot::raw::KeyDomain<K>,
}
impl<K: crate::depot::raw::Key, V> Entry<K, V> {
pub(in crate::depot) fn vacant() -> Self {
Self {
key: K::VACANT,
value: mem::MaybeUninit::uninit(),
domain: marker::PhantomData,
}
}
pub(super) unsafe fn payload(row: ptr::NonNull<Self>) -> ptr::NonNull<V> {
unsafe { row.byte_add(mem::offset_of!(Self, value)).cast() }
}
pub(super) fn key(&self) -> Option<K> {
if self.key == K::VACANT {
return None;
}
Some(unsafe { Self::identity(ptr::NonNull::from(self)) })
}
pub(super) unsafe fn identity(row: ptr::NonNull<Self>) -> K {
unsafe { K::from_raw(Stored::new(ptr::addr_of!((*row.as_ptr()).key).read())) }
}
pub(in crate::depot) unsafe fn occupied(
table: &mut direct::Table<K, V>,
index: usize,
) -> (K, ptr::NonNull<Self>) {
let row = unsafe { ptr::NonNull::new_unchecked(table.block.as_mut_ptr().add(index)) };
(unsafe { Self::identity(row) }, row)
}
}
impl<K: crate::depot::raw::Key, V> Drop for Entry<K, V> {
fn drop(&mut self) {
if self.key == K::VACANT {
return;
}
unsafe { self.value.assume_init_drop() };
}
}
#[must_use = "a vacant entry does nothing unless inserted"]
pub struct Vacant<'a, K: crate::depot::raw::Key, V, P = ()> {
pub(in crate::depot::map::direct) table: &'a mut direct::Table<K, V>,
pub(in crate::depot::map::direct) key: K,
pub(in crate::depot::map::direct) plane: marker::PhantomData<fn(P) -> P>,
}
impl<'a, K: crate::depot::raw::Key, V, P> Vacant<'a, K, V, P> {
pub fn key(&self) -> K {
self.key
}
pub fn table(&self) -> &direct::Table<K, V> {
self.table
}
fn row(&mut self) -> ptr::NonNull<Entry<K, V>> {
unsafe { ptr::NonNull::new_unchecked(self.table.block.as_mut_ptr().add(self.key.index())) }
}
pub fn as_mut_ptr(&mut self) -> ptr::NonNull<V> {
unsafe { Entry::payload(self.row()) }
}
pub unsafe fn assume_init(mut self) -> direct::Occupied<'a, K, V> {
let row = self.row();
unsafe { self.publish(row) }
}
pub fn insert(mut self, value: V) -> direct::Occupied<'a, K, V> {
let row = self.row();
unsafe {
Entry::payload(row).write(value);
self.publish(row)
}
}
unsafe fn publish(self, row: ptr::NonNull<Entry<K, V>>) -> direct::Occupied<'a, K, V> {
unsafe { self.table.publish(row, self.key) };
direct::Occupied {
table: self.table,
row,
plane: marker::PhantomData,
}
}
}