game_tree_search/table/
map.rs1use core::hash::Hash;
4
5use hashbrown::HashMap;
6
7use super::{Entry, Table};
8
9#[derive(Debug, Clone)]
27pub struct MapTable<K, M, S> {
28 entries: HashMap<K, Entry<M, S>>,
30 capacity: usize,
32}
33
34impl<K: Eq + Hash, M: Clone, S: Clone> MapTable<K, M, S> {
35 #[must_use]
37 pub fn new(capacity: usize) -> Self {
38 Self {
39 entries: HashMap::new(),
40 capacity,
41 }
42 }
43
44 #[must_use]
46 pub const fn capacity(&self) -> usize {
47 self.capacity
48 }
49
50 #[must_use]
52 pub fn len(&self) -> usize {
53 self.entries.len()
54 }
55
56 #[must_use]
58 pub fn is_empty(&self) -> bool {
59 self.entries.is_empty()
60 }
61
62 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#[cfg(test)]
82mod tests {
83 use super::{MapTable, Table};
84 use crate::Bound;
85 use crate::table::Entry;
86
87 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 #[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}