1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use async_rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::{
fmt::{Debug, Display, Formatter},
sync::Arc,
};
#[derive(Clone)]
pub struct Handle<T> {
data: Arc<RwLock<T>>,
}
impl<T> Handle<T> {
pub fn new(value: T) -> Self {
Self {
data: Arc::new(RwLock::new(value)),
}
}
pub async fn read(&self) -> RwLockReadGuard<'_, T> {
self.data.read().await
}
pub async fn write(&self) -> RwLockWriteGuard<'_, T> {
self.data.write().await
}
pub fn try_unwrap(self) -> Result<T, Self> {
match Arc::try_unwrap(self.data) {
Ok(lock) => Ok(lock.into_inner()),
Err(data) => Err(Self { data }),
}
}
}
impl<T> Debug for Handle<T>
where
T: Debug,
{
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
futures_lite::future::block_on(async {
let data = self.read().await;
data.fmt(f)
})
}
}
impl<T> Display for Handle<T>
where
T: Display,
{
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
futures_lite::future::block_on(async {
let data = self.read().await;
data.fmt(f)
})
}
}
impl<T> Default for Handle<T>
where
T: Default,
{
fn default() -> Self {
Self::new(T::default())
}
}