use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::Mutex;
use std::time::{Duration, Instant};
#[derive(Clone)]
struct CacheEntry<V> {
value: V,
expires_at: Instant,
}
impl<V> CacheEntry<V> {
fn is_expired(&self, now: Instant) -> bool {
now >= self.expires_at
}
}
pub struct RpcCache<V> {
inner: Mutex<HashMap<u64, CacheEntry<V>>>,
ttl: Duration,
max_entries: usize,
}
impl<V: Clone> RpcCache<V> {
pub fn new(ttl: Duration) -> Self {
Self {
inner: Mutex::new(HashMap::new()),
ttl,
max_entries: 1024,
}
}
pub fn with_max_entries(ttl: Duration, max_entries: usize) -> Self {
Self {
inner: Mutex::new(HashMap::new()),
ttl,
max_entries,
}
}
pub fn insert(&self, key: u64, value: V) {
let mut guard = self.inner.lock().expect("RpcCache lock poisoning");
let now = Instant::now();
guard.retain(|_, entry| !entry.is_expired(now));
while guard.len() >= self.max_entries {
if let Some(evicted_key) = guard.keys().next().copied() {
guard.remove(&evicted_key);
} else {
break;
}
}
guard.insert(
key,
CacheEntry {
value,
expires_at: now + self.ttl,
},
);
}
pub fn get(&self, key: u64) -> Option<V> {
let mut guard = self.inner.lock().expect("RpcCache lock poisoning");
let now = Instant::now();
match guard.get(&key) {
Some(entry) if !entry.is_expired(now) => Some(entry.value.clone()),
_ => {
guard.remove(&key);
None
}
}
}
pub fn purge_expired(&self) {
let mut guard = self.inner.lock().expect("RpcCache lock poisoning");
let now = Instant::now();
guard.retain(|_, entry| !entry.is_expired(now));
}
pub fn clear(&self) {
self.inner.lock().expect("RpcCache lock poisoning").clear();
}
pub fn len(&self) -> usize {
self.inner.lock().expect("RpcCache lock poisoning").len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
#[inline]
pub fn hash_bytes(bytes: &[u8]) -> u64 {
use std::collections::hash_map::DefaultHasher;
let mut hasher = DefaultHasher::new();
bytes.hash(&mut hasher);
hasher.finish()
}
#[inline]
pub fn hash_key<K: Hash>(key: &K) -> u64 {
use std::collections::hash_map::DefaultHasher;
let mut hasher = DefaultHasher::new();
key.hash(&mut hasher);
hasher.finish()
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
#[test]
fn insert_and_get() {
let cache = RpcCache::new(Duration::from_secs(60));
cache.insert(42, "hello".to_string());
assert_eq!(cache.get(42), Some("hello".to_string()));
}
#[test]
fn miss_on_unknown_key() {
let cache: RpcCache<String> = RpcCache::new(Duration::from_secs(60));
assert_eq!(cache.get(999), None);
}
#[test]
fn miss_on_expired() {
let cache = RpcCache::new(Duration::from_millis(1));
cache.insert(1, "expired_value".to_string());
std::thread::sleep(Duration::from_millis(10));
assert_eq!(cache.get(1), None);
}
#[test]
fn clear_removes_all() {
let cache = RpcCache::new(Duration::from_secs(60));
cache.insert(1, "a".to_string());
cache.insert(2, "b".to_string());
cache.clear();
assert!(cache.is_empty());
}
#[test]
fn len_and_is_empty() {
let cache = RpcCache::new(Duration::from_secs(60));
assert!(cache.is_empty());
assert_eq!(cache.len(), 0);
cache.insert(1, "x".to_string());
assert!(!cache.is_empty());
assert_eq!(cache.len(), 1);
}
#[test]
fn hash_bytes_is_deterministic() {
let h1 = hash_bytes(b"hello");
let h2 = hash_bytes(b"hello");
assert_eq!(h1, h2);
}
#[test]
fn hash_bytes_different_for_different_inputs() {
let h1 = hash_bytes(b"hello");
let h2 = hash_bytes(b"world");
assert_ne!(h1, h2);
}
#[test]
fn max_entries_eviction() {
let cache = RpcCache::with_max_entries(Duration::from_secs(60), 2);
cache.insert(1, "a".to_string());
cache.insert(2, "b".to_string());
cache.insert(3, "c".to_string()); let count = cache.len();
assert!(count <= 2, "The cache must not exceed max_entries");
}
#[test]
fn purge_expired_cleans_up() {
let cache = RpcCache::new(Duration::from_millis(1));
cache.insert(1, "x".to_string());
cache.insert(2, "y".to_string());
std::thread::sleep(Duration::from_millis(10));
cache.purge_expired();
assert!(cache.is_empty());
}
}