use core::hash::Hash;
use hashbrown::HashMap;
use super::{Entry, Table};
#[derive(Debug, Clone)]
pub struct MapTable<K, M, S> {
entries: HashMap<K, Entry<M, S>>,
capacity: usize,
}
impl<K: Eq + Hash, M: Clone, S: Clone> MapTable<K, M, S> {
#[must_use]
pub fn new(capacity: usize) -> Self {
Self {
entries: HashMap::new(),
capacity,
}
}
#[must_use]
pub const fn capacity(&self) -> usize {
self.capacity
}
#[must_use]
pub fn len(&self) -> usize {
self.entries.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn clear(&mut self) {
self.entries.clear();
}
}
impl<K: Eq + Hash, M: Clone, S: Clone> Table<K, M, S> for MapTable<K, M, S> {
fn probe(&mut self, key: &K) -> Option<Entry<M, S>> {
self.entries.get(key).cloned()
}
fn store(&mut self, key: K, entry: Entry<M, S>) {
if self.entries.len() < self.capacity || self.entries.contains_key(&key) {
self.entries.insert(key, entry);
}
}
}
#[cfg(test)]
mod tests {
use super::{MapTable, Table};
use crate::Bound;
use crate::table::Entry;
fn entry(score: i32) -> Entry<u8, i32> {
Entry {
depth: 1,
score,
bound: Bound::Exact,
best: None,
proven: false,
reach: 0,
}
}
#[test]
fn a_full_table_keeps_known_keys_only() {
let mut table = MapTable::new(1);
table.store(1_u64, entry(10));
table.store(2_u64, entry(20));
table.store(1_u64, entry(11));
assert_eq!(table.len(), 1);
assert_eq!(table.probe(&1).map(|entry| entry.score), Some(11));
assert_eq!(table.probe(&2), None);
assert_eq!(table.capacity(), 1);
assert!(!table.is_empty());
table.clear();
assert!(table.is_empty());
}
}