rsiot_component_core/
cache.rs

1use 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/// Кеширование сообщений
10#[derive(Debug)]
11pub struct Cache<TMsg>(Arc<RwLock<Hash<TMsg>>>);
12
13impl<TMsg> Cache<TMsg> {
14    /// Создаем новый пустой кеш
15    pub fn new() -> Self {
16        Self(Arc::new(RwLock::new(HashMap::new())))
17    }
18
19    /// Блокировка кеша для чтения в синхронном коде
20    pub fn blocking_read(&self) -> RwLockReadGuard<'_, Hash<TMsg>> {
21        self.0.blocking_read()
22    }
23
24    /// Блокировка кеша для чтения
25    pub fn read(&self) -> impl Future<Output = RwLockReadGuard<'_, Hash<TMsg>>> {
26        self.0.read()
27    }
28
29    /// Блокировка кеша для записи
30    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}