1use std::collections::HashMap;
10use std::sync::RwLock;
11
12use crate::cache::Cache;
13use crate::options::EntryOptions;
14
15pub trait DefaultEntryOptionsProvider: Send + Sync {
19 fn options_for(&self, key: &str) -> Option<EntryOptions>;
21}
22
23pub struct CacheRegistry<V: Clone + Send + Sync + 'static> {
28 caches: RwLock<HashMap<String, Cache<V>>>,
29}
30
31impl<V: Clone + Send + Sync + 'static> CacheRegistry<V> {
32 #[must_use]
34 pub fn new() -> Self {
35 Self {
36 caches: RwLock::new(HashMap::new()),
37 }
38 }
39
40 pub fn register(&self, name: impl Into<String>, cache: Cache<V>) {
42 if let Ok(mut map) = self.caches.write() {
43 map.insert(name.into(), cache);
44 }
45 }
46
47 #[must_use]
49 pub fn get(&self, name: &str) -> Option<Cache<V>> {
50 self.caches.read().ok()?.get(name).cloned()
51 }
52
53 pub fn get_or_create(&self, name: &str, build: impl FnOnce() -> Cache<V>) -> Cache<V> {
55 if let Some(existing) = self.get(name) {
56 return existing;
57 }
58 let cache = build();
59 self.register(name.to_owned(), cache.clone());
60 cache
61 }
62
63 #[must_use]
65 pub fn len(&self) -> usize {
66 self.caches.read().map(|m| m.len()).unwrap_or(0)
67 }
68
69 #[must_use]
71 pub fn is_empty(&self) -> bool {
72 self.len() == 0
73 }
74}
75
76impl<V: Clone + Send + Sync + 'static> Default for CacheRegistry<V> {
77 fn default() -> Self {
78 Self::new()
79 }
80}