url_preview/
cache.rs

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