Skip to main content

game_tree_search/
table.rs

1//! Transposition tables: remembering what a search learned about a position, so the same
2//! position reached by another move order is not searched again.
3//!
4//! A game opts in by implementing [`Hashed`]. A [`Searcher`](crate::Searcher) built with
5//! [`Searcher::with_table`](crate::Searcher::with_table) then asks its [`Table`] before
6//! searching a position and tells it the result afterwards. [`SlotTable`] is the default
7//! table; `MapTable` (feature `hashbrown`) or any other type implementing [`Table`] can
8//! replace it.
9
10#[cfg(feature = "hashbrown")]
11mod map;
12#[cfg(feature = "parallel")]
13mod packed;
14#[cfg(feature = "parallel")]
15mod shared;
16mod slot;
17#[cfg(feature = "parallel")]
18mod sync;
19
20#[cfg(feature = "hashbrown")]
21pub use map::MapTable;
22#[cfg(feature = "parallel")]
23pub use packed::{Packed, PackedTable};
24#[cfg(feature = "parallel")]
25pub use shared::SharedTable;
26pub use slot::SlotTable;
27
28use crate::{Bound, Game};
29
30/// A game whose positions have a hash key, so a transposition table can recognize them.
31///
32/// Two positions must get the same key exactly when they play out the same from here on:
33/// the same side to move, the same moves and the same scores below. Keys that differ only
34/// by chance (hash collisions) make a search reuse a wrong result, so use a well-mixed hash
35/// of 64 or 128 bits.
36pub trait Hashed: Game {
37    /// The key type; `u64`, `u128` or a pair of `u64` halves.
38    type Key: TableKey;
39
40    /// The key of `position`.
41    fn key(&self, position: &Self::Position) -> Self::Key;
42}
43
44/// A position key that a fixed-size table can place in a slot.
45pub trait TableKey: Copy + Eq {
46    /// 64 well-mixed bits of the key; a table uses the low bits to pick a slot.
47    fn slot(&self) -> u64;
48}
49
50impl TableKey for u64 {
51    fn slot(&self) -> u64 {
52        *self
53    }
54}
55
56impl TableKey for u128 {
57    #[expect(
58        clippy::cast_possible_truncation,
59        reason = "folding 128 bits into 64 is the point"
60    )]
61    fn slot(&self) -> u64 {
62        (*self ^ (*self >> 64)) as u64
63    }
64}
65
66impl TableKey for (u64, u64) {
67    fn slot(&self) -> u64 {
68        self.0
69    }
70}
71
72/// What a search learned about a position.
73///
74/// Non-exhaustive: tables store and return entries, only searches create them.
75#[derive(Debug, Clone, PartialEq, Eq)]
76#[non_exhaustive]
77pub struct Entry<M, S> {
78    /// The plies that were left to search below the position.
79    pub depth: u32,
80    /// The score found, from [`Side::Max`](crate::Side::Max)'s point of view.
81    pub score: S,
82    /// How [`Entry::score`] relates to the position's minimax value at [`Entry::depth`].
83    pub bound: Bound,
84    /// The best move found, tried first when the position is searched again.
85    pub best: Option<M>,
86    /// Whether no line below the position ran into the depth limit.
87    pub proven: bool,
88    /// For a [`proven`](Entry::proven) entry: the fewest plies left at which a search of the
89    /// position runs into no depth limit, so the entry holds for any depth from there on.
90    pub reach: u32,
91}
92
93impl<M, S> Entry<M, S> {
94    /// Whether the entry answers a search of its position with `depth` plies left.
95    ///
96    /// Only an entry from the same depth, or a proven one deep enough, is used: an entry from
97    /// a deeper search would give a different score than a search to `depth`.
98    pub(crate) const fn serves(&self, depth: u32) -> bool {
99        self.depth == depth || (self.proven && depth >= self.reach)
100    }
101}
102
103/// Storage for [`Entry`] values by position key.
104///
105/// Implemented by [`SlotTable`] and, with the `hashbrown` feature, `MapTable`. Entries are
106/// handed out by value, never by reference, so a table shared between threads can implement
107/// this trait on a reference to itself.
108pub trait Table<K, M, S> {
109    /// The entry stored for `key`, if any.
110    fn probe(&mut self, key: &K) -> Option<Entry<M, S>>;
111
112    /// Stores `entry` for `key`; the table may keep or drop it, or evict another entry.
113    fn store(&mut self, key: K, entry: Entry<M, S>);
114}
115
116/// No transposition table: every position is searched, nothing is remembered.
117///
118/// The default of [`Searcher`](crate::Searcher); works for every game, [`Hashed`] or not.
119#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
120pub struct NoTable;
121
122/// How a [`Searcher`](crate::Searcher) remembers positions of a game `G`.
123///
124/// Implemented for [`NoTable`], which remembers nothing, and for [`Transpositions`], a
125/// [`Table`] of a [`Hashed`] game; there is no need to implement it directly.
126pub trait Memory<G: Game> {
127    /// What identifies a position: the game's key, or nothing for [`NoTable`].
128    type Key;
129
130    /// The key of `position` in `game`.
131    fn key(&self, game: &G, position: &G::Position) -> Self::Key;
132
133    /// The entry remembered for `key`, if any.
134    fn recall(&mut self, key: &Self::Key) -> Option<Entry<G::Move, G::Score>>;
135
136    /// Remembers `entry` for `key`.
137    fn remember(&mut self, key: Self::Key, entry: Entry<G::Move, G::Score>);
138}
139
140impl<G: Game> Memory<G> for NoTable {
141    type Key = ();
142
143    fn key(&self, _: &G, _: &G::Position) {}
144
145    fn recall(&mut self, (): &()) -> Option<Entry<G::Move, G::Score>> {
146        None
147    }
148
149    fn remember(&mut self, (): (), _: Entry<G::Move, G::Score>) {}
150}
151
152/// A [`Table`] serving as a searcher's [`Memory`]; built by
153/// [`Searcher::with_table`](crate::Searcher::with_table).
154#[derive(Debug, Clone, Default)]
155pub struct Transpositions<T>(pub(crate) T);
156
157impl<G: Hashed, T: Table<G::Key, G::Move, G::Score>> Memory<G> for Transpositions<T> {
158    type Key = G::Key;
159
160    fn key(&self, game: &G, position: &G::Position) -> G::Key {
161        game.key(position)
162    }
163
164    fn recall(&mut self, key: &G::Key) -> Option<Entry<G::Move, G::Score>> {
165        self.0.probe(key)
166    }
167
168    fn remember(&mut self, key: G::Key, entry: Entry<G::Move, G::Score>) {
169        self.0.store(key, entry);
170    }
171}