use std::num::NonZeroU32;
pub struct RecentHashes {
tags: Vec<Option<NonZeroU32>>,
shift: u32,
}
impl RecentHashes {
pub const fn new(slots: usize) -> Self {
let slots = if slots < 2 {
2
} else {
slots.next_power_of_two()
};
Self {
tags: Vec::new(),
shift: u64::BITS - slots.ilog2(),
}
}
#[inline]
pub fn contains(&self, hash: u64) -> bool {
let (slot, tag) = self.slot_and_tag(hash);
self.tags.get(slot) == Some(&Some(tag))
}
#[inline]
pub fn put(&mut self, hash: u64) {
if self.tags.is_empty() {
self.take_room();
}
let (slot, tag) = self.slot_and_tag(hash);
if let Some(kept) = self.tags.get_mut(slot) {
*kept = Some(tag);
}
}
pub fn clear(&mut self) {
self.tags = Vec::new();
}
#[cold]
#[inline(never)]
fn take_room(&mut self) {
self.tags = vec![None; 1 << (u64::BITS - self.shift)];
}
fn slot_and_tag(&self, hash: u64) -> (usize, NonZeroU32) {
let slot = usize::try_from(hash >> self.shift).unwrap_or(0);
let low = u32::try_from(hash & u64::from(u32::MAX)).unwrap_or(0);
(slot, NonZeroU32::MIN | low)
}
}