Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use flume::Receiver;
- use parking_lot::{RawRwLock, RwLock};
- use std::{borrow::Borrow, collections::HashMap, hash::Hash, sync::Arc};
- const UPDATES_CHAN_SIZE: usize = 100;
- pub struct Cache<K: 'static + Send, V: 'static + Send> {
- data: RwLock<HashMap<K, V>>,
- updates_tx: flume::Sender<WriteOp<K, V>>,
- }
- unsafe impl<K: Send, V: Send> Sync for Cache<K, V> {}
- struct WriteOp<K, V> {
- key: K,
- value: V,
- }
- impl<K, V> Cache<K, V>
- where
- K: 'static + Send + Eq + Hash,
- V: 'static + Send,
- {
- pub fn with_capacity(capacity: usize) -> Arc<Cache<K, V>> {
- let mut map = HashMap::with_capacity(capacity);
- let data = RwLock::new(map);
- let (updates_tx, updates_rx) = flume::bounded(UPDATES_CHAN_SIZE);
- let result = Arc::new(Cache {
- data,
- // updates_rx,
- updates_tx,
- });
- let for_updater = result.clone();
- tokio::spawn(async move { update_entries(updates_rx.clone(), for_updater) });
- result
- }
- pub fn get<Q>(&self, k: &Q) -> Option<&V>
- where
- K: Borrow<Q>,
- Q: Hash + Eq,
- {
- let map = self.data.read();
- let res = map.get(k);
- res
- }
- }
- async fn update_entries<K, V>(rx: Receiver<WriteOp<K, V>>, map: Arc<Cache<K, V>>)
- where
- K: 'static + Send,
- V: 'static + Send,
- {
- while let Ok(write_op) = rx.recv_async().await {
- //handle updates...
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement