use std::mem;
use crate::depot::{
heap,
map::{
self,
priority::sealed::{Core, Node},
},
queue::links,
};
pub struct Occupied<'a, K, P: Ord, V> {
pub(super) core: &'a mut Core<K, V, P>,
pub(super) index: u32,
}
impl<K, V, P: Ord> Occupied<'_, K, P, V> {
pub fn index(&self) -> links::Index {
unsafe { links::Index::new_raw(self.index) }
}
fn node(&self) -> &Node<K, V, P> {
unsafe { self.core.node(self.index) }
}
pub fn key(&self) -> &K {
&self.node().key
}
pub fn get(&self) -> &V {
&self.node().value
}
pub fn priority(&self) -> &P {
&self.node().priority
}
pub fn get_mut(&mut self) -> &mut V {
&mut unsafe { self.core.node_mut(self.index) }.value
}
pub fn set(&mut self, priority: P) {
let node = unsafe { self.core.node_mut(self.index) };
let position = unsafe { node.position.assume_init() } as usize;
let _old = mem::replace(&mut node.priority, priority);
unsafe { heap::raw::Source::replace::<false>(self.core, position, self.index) };
}
pub fn remove(self) -> V {
self.remove_parts().1
}
pub fn remove_parts(self) -> (K, V, P) {
let index = self.index;
let node = self.node();
let position = unsafe { node.position.assume_init() } as usize;
let bucket = unsafe { map::raw::Occupied::new(node.bucket as usize) };
let len = self.core.len;
let tail = len - 1;
self.core.len = tail;
if len > self.core.retired {
self.core.retired = len;
}
if position != tail as usize {
let last = unsafe { self.core.indices.add(tail as usize).replace(index) };
unsafe { heap::raw::Source::replace::<false>(self.core, position, last) };
}
let hole = unsafe { self.core.table.directory.vacate(bucket) };
unsafe { map::raw::close(self.core, hole) };
let node = unsafe { self.core.nodes.add(index as usize).read() };
(node.key, node.value, node.priority)
}
}
pub struct Vacant<'a, K, P: Ord, V> {
pub(super) core: &'a mut Core<K, V, P>,
pub(super) bucket: map::raw::Vacant,
pub(super) hash: u64,
pub(super) index: u32,
pub(super) key: K,
}
impl<K, V, P: Ord> Vacant<'_, K, P, V> {
pub fn index(&self) -> links::Index {
unsafe { links::Index::new_raw(self.index) }
}
pub fn insert(self, priority: P, value: V) {
let Self {
core,
bucket,
hash,
index,
key,
} = self;
let node = Node {
key,
value,
priority,
bucket: bucket.index() as u32,
position: mem::MaybeUninit::uninit(),
};
unsafe {
core.nodes.add(index as usize).write(node);
heap::raw::Source::append(core, index);
core.table.insert(bucket, hash, index);
}
}
}