use crate::{
alloc,
base::num::Step,
depot::{
map,
map::resident::{self, Key, Table},
queue::links,
},
};
pub struct Occupied<'a, T, H, const MAX: u32> {
pub(in crate::depot::map::resident) table: &'a mut Table<T, H, MAX>,
pub(in crate::depot::map::resident) bucket: Option<map::raw::Occupied>,
pub(in crate::depot::map::resident) index: links::Index,
}
impl<T, H: map::Hasher<resident::Id>, const MAX: u32> Occupied<'_, T, H, MAX> {
fn record(&self) -> &resident::raw::Record<T, MAX> {
unsafe { resident::raw::published(self.table, self.index) }
}
pub fn key(&self) -> Key<MAX> {
Key::new(self.index, self.record().generation)
}
pub fn id(&self) -> resident::Id {
self.record().id()
}
pub fn get(&self) -> &T {
&self.record().value
}
pub fn get_mut(&mut self) -> &mut T {
unsafe { resident::raw::value_mut(self.table, self.index.get()) }
}
pub fn remove(self) -> T {
let table = self.table;
let index = self.index;
let bucket = match self.bucket {
Some(bucket) => bucket,
None => {
let id = unsafe { resident::raw::published(table, index) }.id();
unsafe { map::raw::member(table, table.hash.hash(&id), |entry| entry.1 == index) }
}
};
let offset = bucket.index();
unsafe {
*table.buckets.get_unchecked_mut(offset) = None;
map::raw::close(table, map::raw::Vacant::new(offset));
}
let record = unsafe { table.records.get_unchecked_mut(index.get()) };
let value = unsafe { record.value.assume_init_read() };
if let Some(next) = record.generation.next() {
record.generation = next;
record.id = resident::raw::FREE | u64::from(links::Index::encode(table.free));
table.free = Some(index);
table.available = table.available.wrapping_add(1);
} else {
record.id = resident::raw::FREE | u64::from(links::Index::END);
}
value
}
}
pub struct Vacant<'a, T, H, const MAX: u32> {
pub(super) table: &'a mut Table<T, H, MAX>,
pub(super) bucket: map::raw::Vacant,
pub(super) id: resident::Id,
}
impl<'a, T, H, const MAX: u32> Vacant<'a, T, H, MAX> {
pub fn insert(self, value: T) -> Occupied<'a, T, H, MAX> {
let Self { table, bucket, id } = self;
let index = match table.free {
Some(index) => {
let record = unsafe { table.records.get_unchecked_mut(index.get()) };
table.free = links::Index::decode(record.id as u32);
record.id = id.get();
record.value.write(value);
index
}
None => {
let index = unsafe { links::Index::new_usize(table.records.len()) };
unsafe { alloc::raw::Vacant::new(&mut table.records) }
.insert(resident::raw::Record::new(id, value));
index
}
};
table.available = table.available.wrapping_sub(1);
let offset = bucket.index();
unsafe { *table.buckets.get_unchecked_mut(offset) = Some(index) };
let bucket = unsafe { map::raw::Occupied::new(offset) };
Occupied {
table,
bucket: Some(bucket),
index,
}
}
}