#[cfg(feature = "hashbrown")]
mod map;
mod slot;
#[cfg(feature = "hashbrown")]
pub use map::MapTable;
pub use slot::SlotTable;
use crate::{Bound, Game};
pub trait Hashed: Game {
type Key: TableKey;
fn key(&self, position: &Self::Position) -> Self::Key;
}
pub trait TableKey: Copy + Eq {
fn slot(&self) -> u64;
}
impl TableKey for u64 {
fn slot(&self) -> u64 {
*self
}
}
impl TableKey for u128 {
#[expect(
clippy::cast_possible_truncation,
reason = "folding 128 bits into 64 is the point"
)]
fn slot(&self) -> u64 {
(*self ^ (*self >> 64)) as u64
}
}
impl TableKey for (u64, u64) {
fn slot(&self) -> u64 {
self.0
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Entry<M, S> {
pub depth: u32,
pub score: S,
pub bound: Bound,
pub best: Option<M>,
pub proven: bool,
pub reach: u32,
}
impl<M, S> Entry<M, S> {
pub(crate) const fn serves(&self, depth: u32) -> bool {
self.depth == depth || (self.proven && depth >= self.reach)
}
}
pub trait Table<K, M, S> {
fn probe(&mut self, key: &K) -> Option<Entry<M, S>>;
fn store(&mut self, key: K, entry: Entry<M, S>);
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct NoTable;
pub trait Memory<G: Game> {
type Key;
fn key(&self, game: &G, position: &G::Position) -> Self::Key;
fn recall(&mut self, key: &Self::Key) -> Option<Entry<G::Move, G::Score>>;
fn remember(&mut self, key: Self::Key, entry: Entry<G::Move, G::Score>);
}
impl<G: Game> Memory<G> for NoTable {
type Key = ();
fn key(&self, _: &G, _: &G::Position) {}
fn recall(&mut self, (): &()) -> Option<Entry<G::Move, G::Score>> {
None
}
fn remember(&mut self, (): (), _: Entry<G::Move, G::Score>) {}
}
#[derive(Debug, Clone, Default)]
pub struct Transpositions<T>(pub(crate) T);
impl<G: Hashed, T: Table<G::Key, G::Move, G::Score>> Memory<G> for Transpositions<T> {
type Key = G::Key;
fn key(&self, game: &G, position: &G::Position) -> G::Key {
game.key(position)
}
fn recall(&mut self, key: &G::Key) -> Option<Entry<G::Move, G::Score>> {
self.0.probe(key)
}
fn remember(&mut self, key: G::Key, entry: Entry<G::Move, G::Score>) {
self.0.store(key, entry);
}
}