use crate::{
NodeId,
collections::id_pages::{IdPages, Vacant},
};
const VIRTUAL: u32 = 1 << 31;
const NO_SLOT: u32 = u32::MAX;
#[derive(Clone, Copy)]
struct Entry {
slot: u32,
generation: u32,
}
impl Entry {
const EMPTY: Self = Self {
slot: NO_SLOT,
generation: 0,
};
fn has_slot(self) -> bool {
self.slot != NO_SLOT
}
}
impl Vacant for Entry {
fn vacant() -> Self {
Self::EMPTY
}
fn is_vacant(&self) -> bool {
!self.has_slot() && self.generation == 0
}
}
#[derive(Default)]
pub(crate) struct StableIndex {
entries: IdPages<Entry>,
live: usize,
}
impl StableIndex {
#[inline]
fn entry(&self, id: NodeId) -> Entry {
self.entries.entry(id.0).copied().unwrap_or(Entry::EMPTY)
}
#[inline]
pub(crate) fn slot(&self, id: NodeId) -> Option<usize> {
let slot = self.entry(id).slot;
(slot != NO_SLOT).then_some(slot as usize)
}
#[inline]
pub(crate) fn slot_and_virtual(&self, id: NodeId) -> Option<(usize, bool)> {
let entry = self.entry(id);
entry
.has_slot()
.then_some((entry.slot as usize, entry.generation & VIRTUAL != 0))
}
pub(crate) fn generation(&self, id: NodeId) -> u32 {
self.entry(id).generation & !VIRTUAL
}
pub(crate) fn set_slot(&mut self, id: NodeId, slot: usize) {
debug_assert!(slot < NO_SLOT as usize, "dense slot {slot} past the index");
self.update(id, |entry| entry.slot = slot as u32);
}
pub(crate) fn insert_fresh(&mut self, id: NodeId, slot: usize) {
debug_assert!(slot < NO_SLOT as usize, "dense slot {slot} past the index");
self.update(id, |entry| {
entry.slot = slot as u32;
entry.generation = 0;
});
}
pub(crate) fn mark_virtual(&mut self, id: NodeId) {
self.update(id, |entry| {
debug_assert!(entry.has_slot(), "only a stored node is virtual");
entry.generation |= VIRTUAL;
});
}
pub(crate) fn release(&mut self, id: NodeId) {
self.update(id, |entry| {
entry.slot = NO_SLOT;
entry.generation = (entry.generation & !VIRTUAL).wrapping_add(1) & !VIRTUAL;
});
}
pub(crate) fn retain_retired(&mut self, keep: impl Fn(NodeId) -> bool) {
self.entries
.retain(|id, entry| entry.has_slot() || keep(NodeId(id)));
}
pub(crate) fn live(&self) -> usize {
self.live
}
pub(crate) fn occupied(&self) -> usize {
self.entries.occupied()
}
pub(crate) fn capacity(&self) -> usize {
self.entries.capacity()
}
fn update(&mut self, id: NodeId, change: impl FnOnce(&mut Entry)) {
let mut had_slot = false;
let mut has_slot = false;
self.entries.update(id.0, |entry| {
had_slot = entry.has_slot();
change(entry);
has_slot = entry.has_slot();
});
self.live = self.live + usize::from(has_slot) - usize::from(had_slot);
}
}
#[cfg(test)]
#[path = "tests/stable_index_tests.rs"]
mod tests;