url_preview/cache.rs
1use crate::Preview;
2use dashmap::DashMap;
3use std::num::NonZeroUsize;
4use std::sync::Arc;
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// use crate::Preview;
29// use lru::LruCache;
30// use std::num::NonZeroUsize;
31// use std::sync::Arc;
32// use tokio::sync::Mutex;
33
34// #[derive(Clone)]
35// pub struct Cache {
36// cache: Arc<Mutex<LruCache<String, Preview>>>,
37// }
38
39// impl Cache {
40// pub fn new(capacity: usize) -> Self {
41// let capacity = NonZeroUsize::new(capacity).unwrap_or(NonZeroUsize::new(100).unwrap());
42// Self {
43// cache: Arc::new(Mutex::new(LruCache::new(capacity))),
44// }
45// }
46
47// pub async fn get(&self, key: &str) -> Option<Preview> {
48// let mut cache = self.cache.lock().await;
49// cache.get(key).cloned()
50// }
51
52// pub async fn set(&self, key: String, value: Preview) {
53// let mut cache = self.cache.lock().await;
54// cache.put(key, value);
55// }
56// }