Advertisement
Guest User

ttl cache

a guest
Jan 24th, 2021
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.45 KB | None | 0 0
  1. use flume::Receiver;
  2. use parking_lot::{RawRwLock, RwLock};
  3. use std::{borrow::Borrow, collections::HashMap, hash::Hash, sync::Arc};
  4.  
  5. const UPDATES_CHAN_SIZE: usize = 100;
  6.  
  7. pub struct Cache<K: 'static + Send, V: 'static + Send> {
  8.     data: RwLock<HashMap<K, V>>,
  9.     updates_tx: flume::Sender<WriteOp<K, V>>,
  10. }
  11.  
  12. unsafe impl<K: Send, V: Send> Sync for Cache<K, V> {}
  13.  
  14. struct WriteOp<K, V> {
  15.     key: K,
  16.     value: V,
  17. }
  18.  
  19. impl<K, V> Cache<K, V>
  20. where
  21.     K: 'static + Send + Eq + Hash,
  22.    V: 'static + Send,
  23. {
  24.     pub fn with_capacity(capacity: usize) -> Arc<Cache<K, V>> {
  25.         let mut map = HashMap::with_capacity(capacity);
  26.         let data = RwLock::new(map);
  27.         let (updates_tx, updates_rx) = flume::bounded(UPDATES_CHAN_SIZE);
  28.         let result = Arc::new(Cache {
  29.             data,
  30.             // updates_rx,
  31.             updates_tx,
  32.         });
  33.         let for_updater = result.clone();
  34.         tokio::spawn(async move { update_entries(updates_rx.clone(), for_updater) });
  35.         result
  36.     }
  37.  
  38.     pub fn get<Q>(&self, k: &Q) -> Option<&V>
  39.     where
  40.         K: Borrow<Q>,
  41.         Q: Hash + Eq,
  42.     {
  43.         let map = self.data.read();
  44.         let res = map.get(k);
  45.         res
  46.     }
  47. }
  48.  
  49. async fn update_entries<K, V>(rx: Receiver<WriteOp<K, V>>, map: Arc<Cache<K, V>>)
  50. where
  51.     K: 'static + Send,
  52.    V: 'static + Send,
  53. {
  54.     while let Ok(write_op) = rx.recv_async().await {
  55.         //handle updates...
  56.     }
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement