Skip to main content

game_tree_search/table/
slot.rs

1//! [`SlotTable`]: a fixed-size array of entries, one per slot.
2
3use alloc::vec::Vec;
4use core::iter;
5
6use super::{Entry, Table, TableKey};
7
8/// A transposition table with a fixed number of slots, each holding at most one entry.
9///
10/// A key's slot comes from the low bits of [`TableKey::slot`]. Storing always replaces what
11/// the slot held, so memory stays fixed and recent positions win; a probe whose key differs
12/// from the slot's misses.
13///
14/// # Examples
15///
16/// ```
17/// # use game_tree_search::{Game, Side};
18/// # struct Nim;
19/// # impl Game for Nim {
20/// #     type Position = (u32, Side);
21/// #     type Move = u32;
22/// #     type Score = i32;
23/// #     fn side_to_move(&self, &(_, side): &Self::Position) -> Side { side }
24/// #     fn moves(&self, &(stones, _): &Self::Position, moves: &mut Vec<u32>) {
25/// #         moves.extend((1..=2).filter(|&take| take <= stones));
26/// #     }
27/// #     fn play(&self, &(stones, side): &Self::Position, take: &u32) -> Self::Position {
28/// #         (stones - take, if side == Side::Max { Side::Min } else { Side::Max })
29/// #     }
30/// #     fn evaluate(&self, &(stones, side): &Self::Position) -> i32 {
31/// #         match (stones, side) { (0, Side::Max) => -1, (0, Side::Min) => 1, _ => 0 }
32/// #     }
33/// # }
34/// use game_tree_search::{Hashed, Searcher, SlotTable, alpha_beta};
35///
36/// impl Hashed for Nim {
37///     type Key = u64;
38///
39///     fn key(&self, &(stones, side): &Self::Position) -> u64 {
40///         u64::from(stones) * 2 + u64::from(side == Side::Max)
41///     }
42/// }
43///
44/// // Many move orders lead to the same pile, so the table saves most of the work.
45/// let mut searcher = Searcher::with_table(SlotTable::new(1024));
46/// let remembered = searcher.search(&Nim, &(20, Side::Max), 20);
47/// let plain = alpha_beta(&Nim, &(20, Side::Max), 20);
48/// assert_eq!(remembered.score, plain.score);
49/// assert!(remembered.stats.nodes < plain.stats.nodes / 10);
50/// ```
51#[derive(Debug, Clone)]
52pub struct SlotTable<K, M, S> {
53    /// The slots; their number is a power of two.
54    slots: Vec<Option<(K, Entry<M, S>)>>,
55}
56
57impl<K: TableKey, M: Clone, S: Clone> SlotTable<K, M, S> {
58    /// A table with `capacity` slots, rounded up to a power of two (at least one).
59    ///
60    /// # Panics
61    ///
62    /// Panics if the rounded capacity does not fit in `usize`.
63    #[must_use]
64    pub fn new(capacity: usize) -> Self {
65        let slots = capacity
66            .max(1)
67            .checked_next_power_of_two()
68            .expect("the capacity fits in usize when rounded up");
69
70        Self {
71            slots: iter::repeat_with(|| None).take(slots).collect(),
72        }
73    }
74
75    /// The number of slots.
76    #[must_use]
77    pub fn capacity(&self) -> usize {
78        self.slots.len()
79    }
80
81    /// Empties every slot, for example before searching a different game.
82    pub fn clear(&mut self) {
83        self.slots.fill_with(|| None);
84    }
85
86    /// The slot of `key`: its low bits, as many as the slot count needs.
87    fn index(&self, key: &K) -> usize {
88        let mask = u64::try_from(self.slots.len() - 1).expect("a slot count fits in u64");
89        usize::try_from(key.slot() & mask).expect("a masked slot is below the slot count")
90    }
91}
92
93impl<K: TableKey, M: Clone, S: Clone> Table<K, M, S> for SlotTable<K, M, S> {
94    fn probe(&mut self, key: &K) -> Option<Entry<M, S>> {
95        let index = self.index(key);
96        let (stored, entry) = self.slots[index].as_ref()?;
97
98        (stored == key).then(|| entry.clone())
99    }
100
101    // shortcut: always replaces; upgrade to depth-preferred buckets if hit rates suffer.
102    fn store(&mut self, key: K, entry: Entry<M, S>) {
103        let index = self.index(&key);
104        self.slots[index] = Some((key, entry));
105    }
106}
107
108/// Unit tests for slot placement and replacement.
109#[cfg(test)]
110mod tests {
111    use super::{SlotTable, Table};
112    use crate::Bound;
113    use crate::table::{Entry, TableKey};
114
115    /// An exact entry of `score` at depth 1.
116    fn entry(score: i32) -> Entry<u8, i32> {
117        Entry {
118            depth: 1,
119            score,
120            bound: Bound::Exact,
121            best: None,
122            proven: false,
123            reach: 0,
124        }
125    }
126
127    /// Capacities round up to a power of two, and zero becomes one slot.
128    #[test]
129    fn capacity_rounds_up() {
130        assert_eq!(SlotTable::<u64, u8, i32>::new(0).capacity(), 1);
131        assert_eq!(SlotTable::<u64, u8, i32>::new(5).capacity(), 8);
132    }
133
134    /// Two keys sharing a slot replace each other; the evicted one misses.
135    #[test]
136    fn keys_sharing_a_slot_replace_each_other() {
137        let mut table = SlotTable::new(4);
138        table.store(1_u64, entry(10));
139        table.store(5_u64, entry(50));
140        assert_eq!(table.probe(&1), None);
141        assert_eq!(table.probe(&5).map(|entry| entry.score), Some(50));
142
143        table.clear();
144        assert_eq!(table.probe(&5), None);
145    }
146
147    /// Wide keys fold into 64 slot bits.
148    #[test]
149    fn wide_keys_fold_into_slot_bits() {
150        assert_eq!((1_u128 << 64 | 3).slot(), 2);
151        assert_eq!((7_u64, 9_u64).slot(), 7);
152        assert_eq!(4_u64.slot(), 4);
153    }
154}