use std::collections::HashMap;
use std::hash::Hash;
use std::ptr::NonNull;
use std::marker::PhantomData;
use crate::{CachePolicy, PrefetchStrategy};
use crate::prefetch::{PrefetchType, NoPrefetch};
use super::{BenchmarkablePolicy, PolicyType};
pub struct LruCache<K, V>
where
K: Hash + Eq + Clone,
V: Clone,
{
map: HashMap<K, NonNull<Node<K, V>>>,
head: Option<NonNull<Node<K, V>>>,
tail: Option<NonNull<Node<K, V>>>,
len: usize,
capacity: usize,
prefetch_strategy: Box<dyn PrefetchStrategy<K>>,
prefetch_buffer: HashMap<K, V>,
prefetch_buffer_size: usize,
prefetch_stats: PrefetchStats,
_marker: PhantomData<Box<Node<K, V>>>,
}
#[derive(Debug, Clone, Default)]
pub struct PrefetchStats {
pub predictions_made: u64,
pub prefetch_hits: u64,
pub prefetch_misses: u64,
pub cache_hits_from_prefetch: u64,
}
impl PrefetchStats {
pub fn hit_rate(&self) -> f64 {
if self.predictions_made == 0 {
0.0
} else {
(self.prefetch_hits as f64 / self.predictions_made as f64) * 100.0
}
}
pub fn effectiveness(&self) -> f64 {
if self.prefetch_hits == 0 {
0.0
} else {
(self.cache_hits_from_prefetch as f64 / self.prefetch_hits as f64) * 100.0
}
}
}
struct Node<K, V> {
key: K,
value: V,
prev: Option<NonNull<Node<K, V>>>,
next: Option<NonNull<Node<K, V>>>,
}
impl<K, V> Node<K, V> {
fn new(key: K, value: V) -> Self {
Self {
key,
value,
prev: None,
next: None,
}
}
}
impl<K, V> LruCache<K, V>
where
K: Hash + Eq + Clone,
V: Clone,
{
pub fn new(capacity: usize) -> Self {
Self::with_custom_prefetch(capacity, Box::new(NoPrefetch))
}
pub fn with_custom_prefetch(
capacity: usize,
prefetch_strategy: Box<dyn PrefetchStrategy<K>>
) -> Self {
assert!(capacity > 0, "LRU cache capacity must be greater than 0");
Self {
map: HashMap::new(),
head: None,
tail: None,
len: 0,
capacity,
prefetch_strategy,
prefetch_buffer: HashMap::new(),
prefetch_buffer_size: (capacity / 4).max(1),
prefetch_stats: PrefetchStats::default(),
_marker: PhantomData,
}
}
pub fn with_default_capacity() -> Self {
Self::new(100)
}
pub fn prefetch_stats(&self) -> &PrefetchStats {
&self.prefetch_stats
}
pub fn reset_prefetch_stats(&mut self) {
self.prefetch_stats = PrefetchStats::default();
self.prefetch_strategy.reset();
}
pub fn set_prefetch_buffer_size(&mut self, size: usize) {
self.prefetch_buffer_size = size.max(1);
self.trim_prefetch_buffer();
}
fn trim_prefetch_buffer(&mut self) {
while self.prefetch_buffer.len() > self.prefetch_buffer_size {
if let Some(key) = self.prefetch_buffer.keys().next().cloned() {
self.prefetch_buffer.remove(&key);
} else {
break;
}
}
}
fn perform_prefetch(&mut self, accessed_key: &K) {
self.prefetch_strategy.update_access_pattern(accessed_key);
let predictions = self.prefetch_strategy.predict_next(accessed_key);
for predicted_key in predictions {
self.prefetch_stats.predictions_made += 1;
if !self.map.contains_key(&predicted_key) &&
!self.prefetch_buffer.contains_key(&predicted_key) {
}
}
self.trim_prefetch_buffer();
}
unsafe fn move_to_front(&mut self, node_ptr: NonNull<Node<K, V>>) {
let _node = unsafe { node_ptr.as_ref() };
if self.head == Some(node_ptr) {
return;
}
unsafe { self.remove_from_list(node_ptr) };
unsafe { self.add_to_front(node_ptr) };
}
unsafe fn remove_from_list(&mut self, node_ptr: NonNull<Node<K, V>>) {
let node = unsafe { node_ptr.as_ref() };
if let Some(mut prev) = node.prev {
unsafe { prev.as_mut() }.next = node.next;
} else {
self.head = node.next;
}
if let Some(mut next) = node.next {
unsafe { next.as_mut() }.prev = node.prev;
} else {
self.tail = node.prev;
}
}
unsafe fn add_to_front(&mut self, mut node_ptr: NonNull<Node<K, V>>) {
let node = unsafe { node_ptr.as_mut() };
node.prev = None;
node.next = self.head;
if let Some(mut old_head) = self.head {
unsafe { old_head.as_mut() }.prev = Some(node_ptr);
} else {
self.tail = Some(node_ptr);
}
self.head = Some(node_ptr);
}
fn evict_lru(&mut self) -> Option<K> {
if let Some(tail_ptr) = self.tail {
unsafe {
let tail_node = Box::from_raw(tail_ptr.as_ptr());
let key = tail_node.key.clone();
self.map.remove(&key);
self.tail = tail_node.prev;
if let Some(mut new_tail) = self.tail {
new_tail.as_mut().next = None;
} else {
self.head = None;
}
self.len -= 1;
Some(key)
}
} else {
None
}
}
}
impl LruCache<i32, String> {
pub fn with_prefetch_i32(capacity: usize, prefetch_type: PrefetchType) -> Self {
assert!(capacity > 0, "LRU cache capacity must be greater than 0");
let prefetch_strategy = crate::prefetch::create_prefetch_strategy_i32(prefetch_type);
Self::with_custom_prefetch(capacity, prefetch_strategy)
}
}
impl LruCache<i64, String> {
pub fn with_prefetch_i64(capacity: usize, prefetch_type: PrefetchType) -> Self {
assert!(capacity > 0, "LRU cache capacity must be greater than 0");
let prefetch_strategy = crate::prefetch::create_prefetch_strategy_i64(prefetch_type);
Self::with_custom_prefetch(capacity, prefetch_strategy)
}
}
impl LruCache<usize, String> {
pub fn with_prefetch_usize(capacity: usize, prefetch_type: PrefetchType) -> Self {
assert!(capacity > 0, "LRU cache capacity must be greater than 0");
let prefetch_strategy = crate::prefetch::create_prefetch_strategy_usize(prefetch_type);
Self::with_custom_prefetch(capacity, prefetch_strategy)
}
}
impl<K, V> CachePolicy<K, V> for LruCache<K, V>
where
K: Hash + Eq + Clone,
V: Clone,
{
fn get(&mut self, key: &K) -> Option<&V> {
if let Some(_) = self.prefetch_buffer.get(key) {
if let Some(value) = self.prefetch_buffer.remove(key) {
self.prefetch_stats.cache_hits_from_prefetch += 1;
self.insert(key.clone(), value);
return self.get(key); }
}
if let Some(&node_ptr) = self.map.get(key) {
unsafe {
self.move_to_front(node_ptr);
self.perform_prefetch(key);
Some(&node_ptr.as_ref().value)
}
} else {
None
}
}
fn insert(&mut self, key: K, value: V) {
self.prefetch_buffer.remove(&key);
if let Some(existing_ptr) = self.map.get_mut(&key) {
let existing_ptr_value = *existing_ptr; unsafe {
(*existing_ptr_value.as_ptr()).value = value;
self.move_to_front(existing_ptr_value);
}
return;
}
let new_node = Box::new(Node::new(key.clone(), value));
let node_ptr = unsafe { NonNull::new_unchecked(Box::into_raw(new_node)) };
self.map.insert(key, node_ptr);
unsafe {
self.add_to_front(node_ptr);
}
self.len += 1;
if self.len > self.capacity {
self.evict_lru();
}
}
fn remove(&mut self, key: &K) -> Option<V> {
if let Some(value) = self.prefetch_buffer.remove(key) {
return Some(value);
}
if let Some(node_ptr) = self.map.remove(key) {
unsafe {
self.remove_from_list(node_ptr);
let node = Box::from_raw(node_ptr.as_ptr());
self.len -= 1;
Some(node.value)
}
} else {
None
}
}
fn len(&self) -> usize {
self.len
}
fn clear(&mut self) {
while let Some(_) = self.evict_lru() {}
self.map.clear();
self.head = None;
self.tail = None;
self.len = 0;
self.prefetch_buffer.clear();
}
fn capacity(&self) -> usize {
self.capacity
}
}
impl<K, V> BenchmarkablePolicy<K, V> for LruCache<K, V>
where
K: Hash + Eq + Clone,
V: Clone,
{
fn policy_type(&self) -> PolicyType {
PolicyType::Lru
}
fn benchmark_name(&self) -> String {
format!("{}_cap_{}_prefetch", self.policy_type().name(), self.capacity())
}
fn reset_for_benchmark(&mut self) {
self.clear();
self.reset_prefetch_stats();
}
}
impl<K, V> Drop for LruCache<K, V>
where
K: Hash + Eq + Clone,
V: Clone,
{
fn drop(&mut self) {
self.clear();
}
}
unsafe impl<K, V> Send for LruCache<K, V>
where
K: Hash + Eq + Clone + Send,
V: Clone + Send,
{
}
unsafe impl<K, V> Sync for LruCache<K, V>
where
K: Hash + Eq + Clone + Sync,
V: Clone + Sync,
{
}