You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
39 lines
1.1 KiB
39 lines
1.1 KiB
use once_cell::sync::Lazy; |
|
use std::cmp::Eq; |
|
use std::collections::HashMap; |
|
use std::hash::Hash; |
|
use std::ops::Deref; |
|
use std::sync::Arc; |
|
use std::sync::{Mutex, MutexGuard}; |
|
|
|
//improve this later, replace job cacher with it |
|
//possibly add different backends (memory, disk) |
|
pub struct SharedStorage<Key, Val>(Arc<Mutex<HashMap<Key, Val>>>); |
|
|
|
impl<Key: Eq + Hash, Val> SharedStorage<Key, Val> { |
|
pub fn new() -> Lazy<SharedStorage<Key, Val>> { |
|
Lazy::new(|| SharedStorage(Arc::new(Mutex::new(HashMap::new())))) |
|
} |
|
|
|
pub fn lock(&self) -> MutexGuard<'_, HashMap<Key, Val>> { |
|
self.0.lock().unwrap() |
|
} |
|
|
|
pub fn get<'get, 'slf: 'get>(&'slf self, key: &'get Key) -> Option<RefHolder<'get, Key, Val>> { |
|
if !self.lock().contains_key(key) { |
|
return None; |
|
} |
|
let lock = self.lock(); |
|
Some(RefHolder(lock, key)) |
|
} |
|
} |
|
|
|
pub struct RefHolder<'h, Key, Val>(pub MutexGuard<'h, HashMap<Key, Val>>, pub &'h Key); |
|
|
|
impl<'h, Key: Eq + Hash, Val> Deref for RefHolder<'h, Key, Val> { |
|
type Target = Val; |
|
|
|
fn deref(&self) -> &Self::Target { |
|
self.0.get(self.1).unwrap() |
|
} |
|
}
|
|
|