use std::mem::size_of;
use std::num::NonZeroU32;
use relate_core::NodeId;
pub(crate) const MIN_SLOTS: usize = 16;
const LOAD_NUM: usize = 3;
const LOAD_DEN: usize = 4;
const FIBONACCI: u64 = 0x9E37_79B9_7F4A_7C15;
#[derive(Debug)]
struct Entry<V> {
stamp: NonZeroU32,
node: NodeId,
value: V,
}
#[derive(Debug)]
pub(crate) struct NodeMap<V> {
slots: Vec<Option<Entry<V>>>,
live: usize,
generation: NonZeroU32,
}
impl<V> Default for NodeMap<V> {
fn default() -> Self {
Self {
slots: Vec::new(),
live: 0,
generation: NonZeroU32::MIN,
}
}
}
impl<V> NodeMap<V> {
pub(crate) fn clear(&mut self) {
self.live = 0;
match self.generation.checked_add(1) {
Some(next) => self.generation = next,
None => {
for slot in &mut self.slots {
*slot = None;
}
self.generation = NonZeroU32::MIN;
}
}
}
#[cfg(test)]
pub(crate) fn len(&self) -> usize {
self.live
}
pub(crate) fn heap_bytes(&self) -> usize {
self.slots.capacity() * size_of::<Option<Entry<V>>>()
}
pub(crate) fn get(&self, node: NodeId) -> Option<&V> {
match self.probe(node) {
Probe::Live(index) => self.slots[index].as_ref().map(|entry| &entry.value),
Probe::Vacant(_) | Probe::Unallocated => None,
}
}
pub(crate) fn get_mut(&mut self, node: NodeId) -> Option<&mut V> {
match self.probe(node) {
Probe::Live(index) => self.slots[index].as_mut().map(|entry| &mut entry.value),
Probe::Vacant(_) | Probe::Unallocated => None,
}
}
pub(crate) fn touch(&mut self, node: NodeId, make: impl FnOnce() -> V) -> (&mut V, bool) {
let (index, inserted) = match self.probe(node) {
Probe::Live(index) => (index, false),
Probe::Vacant(_) | Probe::Unallocated => {
if (self.live + 1) * LOAD_DEN > self.slots.len() * LOAD_NUM {
self.grow();
}
let Probe::Vacant(index) = self.probe(node) else {
unreachable!("a key absent before the growth is absent after it")
};
self.slots[index] = Some(Entry {
stamp: self.generation,
node,
value: make(),
});
self.live += 1;
(index, true)
}
};
let entry = self.slots[index]
.as_mut()
.expect("the probed or just-written slot is occupied");
(&mut entry.value, inserted)
}
pub(crate) fn insert(&mut self, node: NodeId, value: V) {
match self.get_mut(node) {
Some(slot) => *slot = value,
None => {
self.touch(node, || value);
}
}
}
fn is_live(&self, slot: &Option<Entry<V>>) -> bool {
matches!(slot, Some(entry) if entry.stamp == self.generation)
}
fn home(&self, node: NodeId) -> usize {
let bits = self.slots.len().trailing_zeros();
((node as u64).wrapping_mul(FIBONACCI) >> (64 - bits)) as usize
}
fn probe(&self, node: NodeId) -> Probe {
if self.slots.is_empty() {
return Probe::Unallocated;
}
let mask = self.slots.len() - 1;
let mut index = self.home(node);
loop {
let slot = &self.slots[index];
if !self.is_live(slot) {
return Probe::Vacant(index);
}
if slot.as_ref().is_some_and(|entry| entry.node == node) {
return Probe::Live(index);
}
index = (index + 1) & mask;
}
}
fn grow(&mut self) {
let len = (self.slots.len() * 2).max(MIN_SLOTS);
let mut slots = Vec::with_capacity(len);
slots.resize_with(len, || None);
let old = std::mem::replace(&mut self.slots, slots);
let generation = self.generation;
for entry in old.into_iter().flatten() {
if entry.stamp != generation {
continue;
}
let Probe::Vacant(index) = self.probe(entry.node) else {
unreachable!("live keys are distinct, and the grown table has room")
};
self.slots[index] = Some(entry);
}
}
}
enum Probe {
Live(usize),
Vacant(usize),
Unallocated,
}
#[cfg(test)]
mod tests {
use std::num::NonZeroU32;
use super::{NodeMap, MIN_SLOTS};
#[test]
fn touch_inserts_once_and_insert_overwrites() {
let mut map = NodeMap::<u32>::default();
assert_eq!(map.get(5), None);
let (value, inserted) = map.touch(5, || 1);
assert!(inserted);
*value += 1;
let (value, inserted) = map.touch(5, || 99);
assert!(!inserted);
assert_eq!(*value, 2);
map.insert(5, 7);
map.insert(6, 8);
assert_eq!(map.get(5), Some(&7));
assert_eq!(map.get(6), Some(&8));
assert_eq!(map.len(), 2);
}
#[test]
fn clear_retires_every_entry_without_freeing_the_slots() {
let mut map = NodeMap::<u32>::default();
for node in 0..10 {
map.insert(node, node as u32);
}
let bytes = map.heap_bytes();
map.clear();
assert_eq!(map.len(), 0);
assert_eq!(map.heap_bytes(), bytes);
for node in 0..10 {
assert_eq!(map.get(node), None, "{node} is stale after the clear");
}
let (value, inserted) = map.touch(3, || 33);
assert!(inserted, "a stale key inserts afresh");
assert_eq!(*value, 33);
}
#[test]
fn growth_keeps_every_live_entry_and_drops_stale_ones() {
let mut map = NodeMap::<i64>::default();
assert_eq!(map.heap_bytes(), 0);
map.insert(-1, -1);
let first = map.heap_bytes();
assert!(first > 0);
map.clear();
let keys: Vec<i64> = (0..10_000).map(|i| i * 7_919 + (1 << 40)).collect();
for &key in &keys {
map.insert(key, key);
}
assert_eq!(map.len(), keys.len());
assert_eq!(map.get(-1), None, "the stale entry did not survive growth");
for &key in &keys {
assert_eq!(map.get(key), Some(&key));
}
assert!(map.heap_bytes() >= first * keys.len() / MIN_SLOTS);
}
#[test]
fn the_generation_wrap_empties_every_slot() {
let mut map = NodeMap::<u32> {
generation: NonZeroU32::new(u32::MAX - 1).expect("non-zero"),
..NodeMap::default()
};
map.insert(1, 1);
map.clear();
map.insert(2, 2);
assert_eq!(map.generation.get(), u32::MAX);
map.clear();
assert_eq!(map.generation, NonZeroU32::MIN);
assert_eq!(map.get(1), None);
assert_eq!(map.get(2), None);
map.insert(1, 10);
assert_eq!(map.get(1), Some(&10));
}
}