use std::num::NonZeroU32;
const MOST_BUCKETS: usize = 1 << 31;
pub struct RecentHashes<const WAYS: usize = 1> {
buckets: Vec<[Option<NonZeroU32>; WAYS]>,
shift: u32,
}
impl<const WAYS: usize> RecentHashes<WAYS> {
pub const fn new(slots: usize) -> Self {
let buckets = slots.div_ceil(WAYS);
let buckets = if buckets < 2 {
2
} else if buckets > MOST_BUCKETS {
MOST_BUCKETS
} else {
buckets.next_power_of_two()
};
Self {
buckets: Vec::new(),
shift: u32::BITS - buckets.ilog2(),
}
}
#[inline]
pub fn contains(&self, hash: u64) -> bool {
let (bucket, tag) = self.bucket_and_tag(hash);
self.buckets
.get(bucket)
.is_some_and(|tags| tags.contains(&Some(tag)))
}
#[inline]
pub fn put(&mut self, hash: u64) {
if self.buckets.is_empty() {
self.take_room();
}
let (bucket, tag) = self.bucket_and_tag(hash);
if let Some(tags) = self.buckets.get_mut(bucket) {
put_first(tags, tag);
}
}
pub const fn slots(&self) -> usize {
self.bucket_count() * WAYS
}
pub fn grow_to(&mut self, slots: usize) {
let grown = Self::new(slots);
if grown.shift >= self.shift {
return;
}
self.shift = grown.shift;
if self.buckets.is_empty() {
return;
}
let room = vec![[None; WAYS]; self.bucket_count()];
let old = std::mem::replace(&mut self.buckets, room);
for tag in old.iter().flat_map(|tags| tags.iter().rev().flatten()) {
let bucket = self.bucket_of(*tag);
if let Some(tags) = self.buckets.get_mut(bucket) {
put_first(tags, *tag);
}
}
}
pub fn clear(&mut self) {
self.buckets = Vec::new();
}
const fn bucket_count(&self) -> usize {
1 << (u32::BITS - self.shift)
}
#[cold]
#[inline(never)]
fn take_room(&mut self) {
self.buckets = vec![[None; WAYS]; self.bucket_count()];
}
fn bucket_and_tag(&self, hash: u64) -> (usize, NonZeroU32) {
let top = u32::try_from(hash >> u32::BITS).unwrap_or(0);
let tag = NonZeroU32::MIN | top;
(self.bucket_of(tag), tag)
}
fn bucket_of(&self, tag: NonZeroU32) -> usize {
usize::try_from(tag.get() >> self.shift).unwrap_or(0)
}
}
fn put_first<const WAYS: usize>(tags: &mut [Option<NonZeroU32>; WAYS], tag: NonZeroU32) {
if let [way] = tags.as_mut_slice() {
*way = Some(tag);
return;
}
if tags.contains(&Some(tag)) {
return;
}
let mut moved = Some(tag);
for way in tags {
moved = std::mem::replace(way, moved);
if moved.is_none() {
break;
}
}
}
#[cfg(test)]
#[path = "tests/recent_hashes_tests.rs"]
mod tests;