use std::{borrow::Borrow, hash::Hash, num::NonZeroUsize};
use super::{
linked_slots::{LinkedSlots, Order},
recent_hashes::RecentHashes,
};
pub const IDLE_PASSES: u64 = 120;
struct Used<V> {
value: V,
pass: u64,
again: bool,
}
pub struct PassAgedCache<K, V> {
slots: LinkedSlots<K, Used<V>>,
once: Order,
again: Order,
left: RecentHashes,
cap: NonZeroUsize,
pass: u64,
}
impl<K, V> PassAgedCache<K, V>
where
K: Eq + Hash,
{
pub fn with_capacity_at_least_one(capacity: usize) -> Self {
let cap = NonZeroUsize::new(capacity).unwrap_or(NonZeroUsize::MIN);
Self {
slots: LinkedSlots::new(),
once: Order::default(),
again: Order::default(),
left: RecentHashes::new(cap.get()),
cap,
pass: 0,
}
}
pub fn len(&self) -> usize {
self.slots.len()
}
pub fn is_empty(&self) -> bool {
self.slots.is_empty()
}
pub fn clear(&mut self) {
self.slots = LinkedSlots::new();
self.once = Order::default();
self.again = Order::default();
self.left.clear();
}
pub fn get<Q>(&mut self, key: &Q) -> Option<&V>
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
self.get_mut(key).map(|value| &*value)
}
pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
let slot = self.slots.find(key)?;
Some(self.use_again(slot))
}
fn use_again(&mut self, slot: u32) -> &mut V {
let pass = self.pass;
let used = &self.slots.slot(slot).value;
if used.again && used.pass == pass {
self.slots.promote(slot, &mut self.again);
} else {
self.slots.unlink(slot, &mut self.once);
self.slots.link_newest(slot, &mut self.again);
}
let used = &mut self.slots.slot_mut(slot).value;
used.pass = pass;
used.again = true;
&mut used.value
}
pub fn push(&mut self, key: K, value: V) -> Option<(K, V)> {
let hash = self.slots.hash(&key);
if let Some(slot) = self.slots.find_hashed(hash, &key) {
let old = std::mem::replace(self.use_again(slot), value);
return Some((key, old));
}
let again = self.left.contains(hash);
let evicted = if self.slots.len() >= self.cap.get() {
self.evict()
} else {
None
};
let used = Used {
value,
pass: self.pass,
again,
};
let slot = self.slots.insert(hash, (key, used), self.cap);
let order = if again {
&mut self.again
} else {
&mut self.once
};
self.slots.link_newest(slot, order);
evicted
}
#[inline(never)]
fn evict(&mut self) -> Option<(K, V)> {
if let Some(slot) = self.once.oldest {
let (hash, entry) = self.slots.remove(slot, &mut self.once);
self.left.put(hash);
return Some((entry.key, entry.value.value));
}
let slot = self.again.oldest?;
let (_, entry) = self.slots.remove(slot, &mut self.again);
Some((entry.key, entry.value.value))
}
pub fn begin_pass(&mut self, idle_passes: u64, mut dropped: impl FnMut(V)) {
self.pass += 1;
let pass = self.pass;
self.slots.append(&mut self.once, &mut self.again);
while let Some(slot) = self.once.oldest
&& pass - self.slots.slot(slot).value.pass > idle_passes
{
let (_, entry) = self.slots.remove(slot, &mut self.once);
dropped(entry.value.value);
}
}
}
#[cfg(test)]
#[path = "tests/pass_aged_tests.rs"]
mod tests;