use alloc::vec::Vec;
use core::hash::{BuildHasher, Hash};
use hashbrown::DefaultHashBuilder;
use search_core::Cost;
pub(crate) trait Transpositions<S, C> {
fn next_iteration(&mut self);
fn covers(&self, state: &S, g: C) -> bool;
fn record(&mut self, state: &S, g: C);
}
pub(crate) struct NoTable;
impl<S, C> Transpositions<S, C> for NoTable {
fn next_iteration(&mut self) {}
fn covers(&self, _: &S, _: C) -> bool {
false
}
fn record(&mut self, _: &S, _: C) {}
}
struct Slot<S, C> {
state: S,
g: C,
iteration: u32,
}
pub(crate) struct Table<S, C> {
slots: Vec<Option<Slot<S, C>>>,
iteration: u32,
hasher: DefaultHashBuilder,
}
impl<S, C> Table<S, C> {
pub(crate) fn new(capacity: usize) -> Self {
let mut slots = Vec::new();
slots.resize_with(capacity, || None);
Self {
slots,
iteration: 0,
hasher: DefaultHashBuilder::default(),
}
}
}
impl<S: Hash + Eq + Clone, C: Cost> Table<S, C> {
fn index(&self, state: &S) -> Option<usize> {
if self.slots.is_empty() {
return None;
}
let hash = u128::from(self.hasher.hash_one(state));
let len = self.slots.len() as u128;
usize::try_from((hash * len) >> 64).ok()
}
}
impl<S: Hash + Eq + Clone, C: Cost> Transpositions<S, C> for Table<S, C> {
fn next_iteration(&mut self) {
self.iteration = self.iteration.wrapping_add(1);
if self.iteration == 0 {
self.slots.iter_mut().for_each(|slot| *slot = None);
}
}
fn covers(&self, state: &S, g: C) -> bool {
let Some(index) = self.index(state) else {
return false;
};
self.slots[index].as_ref().is_some_and(|slot| {
slot.iteration == self.iteration && slot.g <= g && slot.state == *state
})
}
fn record(&mut self, state: &S, g: C) {
if let Some(index) = self.index(state) {
self.slots[index] = Some(Slot {
state: state.clone(),
g,
iteration: self.iteration,
});
}
}
}
#[cfg(test)]
mod tests {
use super::{Table, Transpositions};
#[test]
fn covers_within_iteration() {
let mut table = Table::<u32, u32>::new(16);
table.next_iteration();
table.record(&7, 3);
assert!(table.covers(&7, 3));
assert!(table.covers(&7, 5));
assert!(!table.covers(&7, 2));
assert!(!table.covers(&8, 9));
table.next_iteration();
assert!(!table.covers(&7, 5));
}
#[test]
fn zero_capacity_is_disabled() {
let mut table = Table::<u32, u32>::new(0);
table.record(&1, 0);
assert!(!table.covers(&1, 0));
}
#[test]
fn one_slot_overwrites() {
let mut table = Table::<u32, u32>::new(1);
table.record(&1, 0);
table.record(&2, 0);
assert!(!table.covers(&1, 0));
assert!(table.covers(&2, 0));
}
}