television_previewers/previewers/
cache.rsuse rustc_hash::FxHashMap;
use std::sync::Arc;
use crate::previewers::Preview;
use television_utils::cache::RingSet;
use tracing::debug;
const DEFAULT_PREVIEW_CACHE_SIZE: usize = 100;
#[derive(Debug)]
pub struct PreviewCache {
entries: FxHashMap<String, Arc<Preview>>,
ring_set: RingSet<String>,
}
impl PreviewCache {
pub fn new(capacity: usize) -> Self {
PreviewCache {
entries: FxHashMap::default(),
ring_set: RingSet::with_capacity(capacity),
}
}
pub fn get(&self, key: &str) -> Option<Arc<Preview>> {
self.entries.get(key).cloned()
}
pub fn insert(&mut self, key: String, preview: &Arc<Preview>) {
debug!("Inserting preview into cache: {}", key);
self.entries.insert(key.clone(), Arc::clone(preview));
if let Some(oldest_key) = self.ring_set.push(key) {
debug!("Cache full, removing oldest entry: {}", oldest_key);
self.entries.remove(&oldest_key);
}
}
#[allow(dead_code)]
pub fn get_or_insert<F>(&mut self, key: String, f: F) -> Arc<Preview>
where
F: FnOnce() -> Preview,
{
if let Some(preview) = self.get(&key) {
preview
} else {
let preview = Arc::new(f());
self.insert(key, &preview);
preview
}
}
}
impl Default for PreviewCache {
fn default() -> Self {
PreviewCache::new(DEFAULT_PREVIEW_CACHE_SIZE)
}
}