rsiot_component_core/
cache.rs1use std::{collections::HashMap, sync::Arc};
2
3use futures::Future;
4use rsiot_messages_core::Message;
5use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
6
7type Hash<TMsg> = HashMap<String, Message<TMsg>>;
8
9#[derive(Debug)]
11pub struct Cache<TMsg>(Arc<RwLock<Hash<TMsg>>>);
12
13impl<TMsg> Cache<TMsg> {
14 pub fn new() -> Self {
16 Self(Arc::new(RwLock::new(HashMap::new())))
17 }
18
19 pub fn blocking_read(&self) -> RwLockReadGuard<'_, Hash<TMsg>> {
21 self.0.blocking_read()
22 }
23
24 pub fn read(&self) -> impl Future<Output = RwLockReadGuard<'_, Hash<TMsg>>> {
26 self.0.read()
27 }
28
29 pub fn write(&self) -> impl Future<Output = RwLockWriteGuard<'_, Hash<TMsg>>> {
31 self.0.write()
32 }
33}
34
35impl<TMessage> Clone for Cache<TMessage> {
36 fn clone(&self) -> Self {
37 Self(self.0.clone())
38 }
39}
40
41impl<TMessage> Default for Cache<TMessage> {
42 fn default() -> Self {
43 Self::new()
44 }
45}