#[derive(Copy, Clone, PartialEq, PartialOrd)]
struct CacheTableEntry<T: Copy + Clone + PartialEq + PartialOrd> {
hash: u64,
entry: T,
}
pub struct CacheTable<T: Copy + Clone + PartialEq + PartialOrd> {
table: Box<[CacheTableEntry<T>]>,
mask: usize,
}
impl<T: Copy + Clone + PartialEq + PartialOrd> CacheTable<T> {
#[inline]
pub fn new(size: usize, default: T) -> CacheTable<T> {
if size.count_ones() != 1 {
panic!("You cannot create a CacheTable with a non-binary number.");
}
let values = vec![CacheTableEntry { hash: 0, entry: default }; size];
CacheTable { table: values.into_boxed_slice(), mask: size - 1 }
}
#[inline]
pub fn get(&self, hash: u64) -> Option<T> {
let entry = unsafe { *self.table.get_unchecked((hash as usize) & self.mask) };
if entry.hash == hash { Some(entry.entry) } else { None }
}
#[inline]
pub fn add(&mut self, hash: u64, entry: T) {
let e = unsafe { self.table.get_unchecked_mut((hash as usize) & self.mask) };
*e = CacheTableEntry { hash, entry };
}
#[inline(always)]
pub fn replace_if<F: Fn(T) -> bool>(&mut self, hash: u64, entry: T, replace: F) {
let e = unsafe { self.table.get_unchecked_mut((hash as usize) & self.mask) };
if replace(e.entry) {
*e = CacheTableEntry { hash, entry };
}
}
}