use std::collections::BTreeMap;
use std::sync::{Arc, RwLock};
static SLOT_HASH_CACHE: once_cell::sync::Lazy<Arc<RwLock<BTreeMap<u64, String>>>> =
once_cell::sync::Lazy::new(|| Arc::new(RwLock::new(BTreeMap::new())));
const MAX_CACHE_SIZE: usize = 1000;
pub fn record_slot_hash(slot: u64, slot_hash: String) {
let mut cache = SLOT_HASH_CACHE.write().expect("RwLock poisoned");
cache.insert(slot, slot_hash);
if cache.len() > MAX_CACHE_SIZE {
let target_size = cache.len() - cache.len() / 4;
while cache.len() > target_size {
cache.pop_first();
}
}
}
pub fn get_slot_hash(slot: u64) -> Option<String> {
let cache = SLOT_HASH_CACHE.read().expect("RwLock poisoned");
cache.get(&slot).cloned()
}
pub fn has_slot_hash(slot: u64) -> bool {
let cache = SLOT_HASH_CACHE.read().expect("RwLock poisoned");
cache.contains_key(&slot)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_slot_hash_cache() {
record_slot_hash(100, "test_hash".to_string());
assert_eq!(get_slot_hash(100), Some("test_hash".to_string()));
assert_eq!(get_slot_hash(101), None);
}
}