Skip to main content

game_tree_search/table/
map.rs

1//! [`MapTable`]: a hash map of entries with a size cap (feature `hashbrown`).
2
3use core::hash::Hash;
4
5use hashbrown::HashMap;
6
7use super::{Entry, Table};
8
9/// A transposition table backed by a hash map, holding up to a fixed number of entries.
10///
11/// Unlike [`SlotTable`](crate::SlotTable), keys never share a slot, so an entry stays until
12/// [`MapTable::clear`]. Once the map is full, entries for new keys are dropped, while known
13/// keys are still updated. Keys need [`Hash`], and memory grows with the entries stored.
14///
15/// Available with the `hashbrown` feature.
16///
17/// # Examples
18///
19/// ```
20/// use game_tree_search::{MapTable, Table};
21///
22/// let mut table = MapTable::<u64, u8, i32>::new(1);
23/// assert!(table.is_empty());
24/// assert_eq!(table.capacity(), 1);
25/// ```
26#[derive(Debug, Clone)]
27pub struct MapTable<K, M, S> {
28    /// The entries by key; never more than [`MapTable::capacity`].
29    entries: HashMap<K, Entry<M, S>>,
30    /// The most entries kept.
31    capacity: usize,
32}
33
34impl<K: Eq + Hash, M: Clone, S: Clone> MapTable<K, M, S> {
35    /// An empty table that keeps up to `capacity` entries.
36    #[must_use]
37    pub fn new(capacity: usize) -> Self {
38        Self {
39            entries: HashMap::new(),
40            capacity,
41        }
42    }
43
44    /// The most entries the table keeps.
45    #[must_use]
46    pub const fn capacity(&self) -> usize {
47        self.capacity
48    }
49
50    /// The number of entries stored.
51    #[must_use]
52    pub fn len(&self) -> usize {
53        self.entries.len()
54    }
55
56    /// Whether the table holds no entries.
57    #[must_use]
58    pub fn is_empty(&self) -> bool {
59        self.entries.is_empty()
60    }
61
62    /// Removes every entry, for example before searching a different game.
63    pub fn clear(&mut self) {
64        self.entries.clear();
65    }
66}
67
68impl<K: Eq + Hash, M: Clone, S: Clone> Table<K, M, S> for MapTable<K, M, S> {
69    fn probe(&mut self, key: &K) -> Option<Entry<M, S>> {
70        self.entries.get(key).cloned()
71    }
72
73    fn store(&mut self, key: K, entry: Entry<M, S>) {
74        if self.entries.len() < self.capacity || self.entries.contains_key(&key) {
75            self.entries.insert(key, entry);
76        }
77    }
78}
79
80/// Unit tests for the size cap.
81#[cfg(test)]
82mod tests {
83    use super::{MapTable, Table};
84    use crate::Bound;
85    use crate::table::Entry;
86
87    /// An exact entry of `score` at depth 1.
88    fn entry(score: i32) -> Entry<u8, i32> {
89        Entry {
90            depth: 1,
91            score,
92            bound: Bound::Exact,
93            best: None,
94            proven: false,
95            reach: 0,
96        }
97    }
98
99    /// A full table drops new keys but still updates known ones.
100    #[test]
101    fn a_full_table_keeps_known_keys_only() {
102        let mut table = MapTable::new(1);
103        table.store(1_u64, entry(10));
104        table.store(2_u64, entry(20));
105        table.store(1_u64, entry(11));
106        assert_eq!(table.len(), 1);
107        assert_eq!(table.probe(&1).map(|entry| entry.score), Some(11));
108        assert_eq!(table.probe(&2), None);
109
110        assert_eq!(table.capacity(), 1);
111        assert!(!table.is_empty());
112
113        table.clear();
114        assert!(table.is_empty());
115    }
116}