url_preview/cache.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
use crate::Preview;
use dashmap::DashMap;
use std::num::NonZeroUsize;
use std::sync::Arc;
#[derive(Clone)]
pub struct Cache {
cache: Arc<DashMap<String, Preview>>,
}
impl Cache {
pub fn new(capacity: usize) -> Self {
let capacity = NonZeroUsize::new(capacity).unwrap_or(NonZeroUsize::new(100).unwrap());
Self {
cache: Arc::new(DashMap::with_capacity(capacity.get())),
}
}
pub async fn get(&self, key: &str) -> Option<Preview> {
self.cache.get(key).map(|entry| entry.clone())
}
pub async fn set(&self, key: String, value: Preview) {
self.cache.insert(key, value);
}
}
// use crate::Preview;
// use lru::LruCache;
// use std::num::NonZeroUsize;
// use std::sync::Arc;
// use tokio::sync::Mutex;
// #[derive(Clone)]
// pub struct Cache {
// cache: Arc<Mutex<LruCache<String, Preview>>>,
// }
// impl Cache {
// pub fn new(capacity: usize) -> Self {
// let capacity = NonZeroUsize::new(capacity).unwrap_or(NonZeroUsize::new(100).unwrap());
// Self {
// cache: Arc::new(Mutex::new(LruCache::new(capacity))),
// }
// }
// pub async fn get(&self, key: &str) -> Option<Preview> {
// let mut cache = self.cache.lock().await;
// cache.get(key).cloned()
// }
// pub async fn set(&self, key: String, value: Preview) {
// let mut cache = self.cache.lock().await;
// cache.put(key, value);
// }
// }