kabu_core_actors/
shared_state.rs

1use std::sync::Arc;
2
3use eyre::Result;
4use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard, TryLockError};
5
6//#[derive(Clone)]
7pub struct SharedState<T> {
8    inner: Arc<RwLock<T>>,
9}
10
11impl<T> SharedState<T> {
12    pub fn new(shared_data: T) -> SharedState<T> {
13        SharedState { inner: Arc::new(RwLock::new(shared_data)) }
14    }
15
16    pub async fn read(&self) -> RwLockReadGuard<T> {
17        self.inner.read().await
18    }
19
20    pub fn try_read(&self) -> Result<RwLockReadGuard<T>, TryLockError> {
21        self.inner.try_read()
22    }
23
24    pub async fn write(&self) -> RwLockWriteGuard<T> {
25        self.inner.write().await
26    }
27
28    pub fn try_write(&self) -> Result<RwLockWriteGuard<T>, TryLockError> {
29        self.inner.try_write()
30    }
31
32    pub fn inner(&self) -> Arc<RwLock<T>> {
33        self.inner.clone()
34    }
35
36    pub async fn update(&self, inner: T) {
37        let mut guard = self.inner.write().await;
38        *guard = inner
39    }
40}
41
42impl<T> Clone for SharedState<T> {
43    fn clone(&self) -> Self {
44        SharedState { inner: self.inner().clone() }
45    }
46}