1use std::{collections::HashMap, sync::Arc};
2
3use futures::Future;
4use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
5
6use crate::message::{Message, MsgDataBound};
7
8type Hash<TMsg> = HashMap<String, Message<TMsg>>;
9
10#[derive(Debug)]
12pub struct Cache<TMsg>(Arc<RwLock<Hash<TMsg>>>);
13
14impl<TMsg> Cache<TMsg>
15where
16 TMsg: MsgDataBound,
17{
18 pub fn new() -> Self {
20 Self(Arc::new(RwLock::new(HashMap::new())))
21 }
22
23 pub fn blocking_read(&self) -> RwLockReadGuard<'_, Hash<TMsg>> {
25 self.0.blocking_read()
26 }
27
28 pub fn read(&self) -> impl Future<Output = RwLockReadGuard<'_, Hash<TMsg>>> {
30 self.0.read()
31 }
32
33 pub fn write(&self) -> impl Future<Output = RwLockWriteGuard<'_, Hash<TMsg>>> {
35 self.0.write()
36 }
37
38 pub async fn clear(&mut self) {
40 let mut lock = self.0.write().await;
41 lock.clear()
42 }
43
44 pub async fn insert(&mut self, msg: Message<TMsg>) {
46 let mut lock = self.0.write().await;
47 let key = msg.key.clone();
48 lock.insert(key, msg);
49 }
50}
51
52impl<TMessage> Clone for Cache<TMessage> {
53 fn clone(&self) -> Self {
54 Self(self.0.clone())
55 }
56}
57
58impl<TMessage> Default for Cache<TMessage>
59where
60 TMessage: MsgDataBound,
61{
62 fn default() -> Self {
63 Self::new()
64 }
65}