use std::{mem, ptr};
use crate::{
alloc,
depot::{
map,
queue::{indexed::fifo::store, links},
},
};
pub struct Record<K, V> {
key: K,
value: V,
bucket: map::raw::Occupied,
}
type Membership<'a, K, V, const N: usize, const Q: usize> =
store::Membership<'a, (), mem::MaybeUninit<Record<K, V>>, N, Q>;
pub struct Table<K, V, const N: usize> {
nodes: store::Store<(), mem::MaybeUninit<Record<K, V>>, N>,
table: map::raw::Table<links::Index>,
shape: map::raw::Shape<links::Index>,
}
pub struct Occupied<'a, K, V, const N: usize, const Q: usize = N> {
owner: &'a mut Table<K, V, N>,
index: links::Index,
}
pub struct Vacant<'a, K, V, const N: usize> {
place: map::Vacancy<&'a mut Table<K, V, N>, u64>,
index: links::Index,
key: K,
}
#[derive(Debug)]
pub enum Error<K> {
Bounds {
key: K,
index: usize,
capacity: usize,
},
Occupied {
key: K,
stored: K,
index: usize,
},
Key {
key: K,
stored: K,
index: usize,
},
}
impl<K, V> Record<K, V> {
pub fn key(&self) -> &K {
&self.key
}
pub fn get(&self) -> &V {
&self.value
}
}
impl<K, V, const N: usize> Table<K, V, N> {
pub fn try_new(plan: map::Plan) -> Result<Self, alloc::Error> {
let layout = map::raw::Layout::try_plan(plan)?;
let nodes = store::Store::try_count(plan.capacity(), |_index| mem::MaybeUninit::uninit())?;
let shape = layout.shape();
let table = map::raw::Table::try_new(layout)?;
Ok(Self {
nodes,
table,
shape,
})
}
pub fn len_in<const Q: usize>(&self) -> usize {
self.nodes.queue::<Q>().len()
}
pub fn is_empty<const Q: usize>(&self) -> bool {
self.nodes.queue::<Q>().is_empty()
}
pub fn get<Q: Eq + ?Sized>(&self, hash: u64, key: &Q) -> Option<&Record<K, V>>
where
K: AsRef<Q>,
{
map::raw::Query::find(self, hash, |stored| stored.as_ref() == key)
}
pub fn entry<Q: Eq + ?Sized>(&mut self, hash: u64, key: &Q) -> Option<Occupied<'_, K, V, N>>
where
K: AsRef<Q>,
{
map::raw::Query::find(self, hash, |stored| stored.as_ref() == key)
}
pub fn at(&self, index: usize) -> Option<&Record<K, V>> {
self.row(index)?.1
}
pub fn slot(&mut self, index: usize) -> Option<Occupied<'_, K, V, N>> {
let (index, Some(_)) = self.row(index)? else {
return None;
};
Some(Occupied { owner: self, index })
}
pub fn front<const Q: usize>(&self) -> Option<&Record<K, V>> {
let index = self.nodes.queue::<Q>().chain().first()?;
Some(unsafe { self.record(index) })
}
pub fn front_entry<const Q: usize>(&mut self) -> Option<Occupied<'_, K, V, N, Q>> {
let index = self.nodes.queue::<Q>().chain().first()?;
Some(Occupied { owner: self, index })
}
pub fn try_vacant<Q: Eq + ?Sized>(
&mut self,
index: usize,
hash: u64,
key: K,
) -> Result<Vacant<'_, K, V, N>, Error<K>>
where
K: Copy + AsRef<Q>,
{
let Some((position, record)) = self.row(index) else {
return Err(Error::Bounds {
key,
index,
capacity: self.nodes.capacity(),
});
};
if let Some(record) = record {
return Err(Error::Occupied {
key,
stored: record.key,
index,
});
}
match unsafe { map::raw::spare(self, hash, |stored| stored.as_ref() == key.as_ref()) } {
map::Entry::Vacant(place) => Ok(Vacant {
place: place.with_phase(hash),
index: position,
key,
}),
map::Entry::Occupied(found) => Err(Error::Key {
key,
stored: *found.key(),
index,
}),
}
}
fn row(&self, index: usize) -> Option<(links::Index, Option<&Record<K, V>>)> {
let row = self.nodes.get(index)?;
let record = if row.is_linked::<0>() {
Some(unsafe { row.state().assume_init_ref() })
} else {
None
};
Some((row.position(), record))
}
unsafe fn record(&self, index: links::Index) -> &Record<K, V> {
unsafe { self.nodes.at(index.get()).state().assume_init_ref() }
}
unsafe fn value_mut(&mut self, index: links::Index) -> &mut V {
let record = unsafe { self.nodes.resident_ptr(index) }.cast::<Record<K, V>>();
unsafe { &mut *ptr::addr_of_mut!((*record).value) }
}
}
impl<K, V, const N: usize> Vacant<'_, K, V, N> {
pub fn insert(self, value: V) {
let Self { place, index, key } = self;
let (owner, bucket, hash) = place.into_parts();
let reverse = unsafe { map::raw::Occupied::new(bucket.index()) };
unsafe {
owner.table.insert(bucket, hash, index);
owner
.nodes
.resident_ptr(index)
.write(mem::MaybeUninit::new(Record {
key,
value,
bucket: reverse,
}));
owner.nodes.at(index.get()).write_back::<0, false>(());
}
}
}
impl<'a, K, V, const N: usize, const Q: usize> Occupied<'a, K, V, N, Q> {
pub fn key(&self) -> &K {
unsafe { &self.owner.record(self.index).key }
}
pub fn get(&self) -> &V {
unsafe { &self.owner.record(self.index).value }
}
pub fn get_mut(&mut self) -> &mut V {
unsafe { self.owner.value_mut(self.index) }
}
pub fn remove(self) -> (K, V) {
let Self { owner, index } = self;
let bucket = unsafe { owner.record(index) }.bucket;
unsafe {
owner.nodes.at(index.get()).release::<Q>();
map::raw::Hole::retire(&mut *owner, bucket);
}
let record = unsafe { owner.nodes.resident_ptr(index).read().assume_init() };
(record.key, record.value)
}
pub fn pop(self) -> Occupied<'a, K, V, N> {
const { assert!(Q > 0 && Q < N) };
unsafe { self.owner.nodes.at(self.index.get()).unlink::<Q, true>() };
Occupied {
owner: self.owner,
index: self.index,
}
}
}
impl<K, V, const N: usize> Occupied<'_, K, V, N> {
pub fn split<const Q: usize>(&mut self) -> (&mut V, Membership<'_, K, V, N, Q>) {
const { assert!(Q > 0 && Q < N) };
let record = unsafe { self.owner.nodes.resident_ptr(self.index) }.cast::<Record<K, V>>();
let plane = unsafe { self.owner.nodes.at(self.index.get()).classify::<Q>() };
(unsafe { &mut *ptr::addr_of_mut!((*record).value) }, plane)
}
pub fn plane<const Q: usize>(&mut self) -> Membership<'_, K, V, N, Q> {
const { assert!(Q > 0 && Q < N) };
unsafe { self.owner.nodes.at(self.index.get()).classify::<Q>() }
}
}
unsafe impl<'a, K, V, const N: usize> map::raw::Query for &'a Table<K, V, N> {
const SPARE: bool = true;
type Payload = links::Index;
type Value = K;
type Occupied = &'a Record<K, V>;
fn table(&self) -> &map::raw::Table<links::Index> {
&self.table
}
fn value(entry: map::Found<&Self>) -> &K {
let (owner, index) = entry.project();
unsafe { &owner.record(*index).key }
}
fn occupied(entry: map::Found<Self>) -> Self::Occupied {
let (owner, index) = entry.copied();
unsafe { owner.record(index) }
}
}
unsafe impl<'a, K, V, const N: usize> map::raw::Query for &'a mut Table<K, V, N> {
const SPARE: bool = true;
type Payload = links::Index;
type Value = K;
type Occupied = Occupied<'a, K, V, N>;
fn table(&self) -> &map::raw::Table<links::Index> {
&self.table
}
fn value(entry: map::Found<&Self>) -> &K {
let (owner, index) = entry.project();
unsafe { &owner.record(*index).key }
}
fn occupied(entry: map::Found<Self>) -> Self::Occupied {
let (owner, index) = entry.copied();
Occupied { owner, index }
}
}
unsafe impl<K, V, const N: usize> map::raw::Mutation for &mut Table<K, V, N> {
unsafe fn table_mut(&mut self) -> &mut map::raw::Table<links::Index> {
&mut self.table
}
unsafe fn shift(&mut self, hole: &map::raw::Vacant, next: &map::raw::Occupied, hash: u64) {
let (bucket, index) = unsafe { self.table.shift(hole, next, hash) };
let index = *index;
let record = unsafe { self.nodes.resident_ptr(index) }.cast::<Record<K, V>>();
unsafe { ptr::addr_of_mut!((*record).bucket).write(bucket) };
}
}
impl<K, V, const N: usize> Drop for Table<K, V, N> {
fn drop(&mut self) {
unsafe { self.shape.layout().bundle().deallocate(self.table.base()) };
if mem::needs_drop::<Record<K, V>>() {
let mut next = self.nodes.queue::<0>().chain().first();
while let Some(index) = next {
next = unsafe { self.nodes.at(index.get()) }.hooks()[0].next_index();
unsafe { (&mut *self.nodes.resident_ptr(index)).assume_init_drop() };
}
}
}
}