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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use async_rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::{
fmt::{Debug, Display, Formatter},
sync::Arc,
};
unsafe impl<T: Send + ?Sized> Send for Handle<T> {}
unsafe impl<T: Send + Sync + ?Sized> Sync for Handle<T> {}
pub struct Handle<T: ?Sized> {
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 }),
}
}
pub fn ptr_eq(this: &Self, other: &Self) -> bool {
Arc::ptr_eq(&this.data, &other.data)
}
}
impl<T: ?Sized> Clone for Handle<T> {
fn clone(&self) -> Self {
Self {
data: self.data.clone(),
}
}
}
impl<T> Handle<T>
where
T: Clone,
{
pub async fn cloned(&self) -> Self {
let data = self.data.read().await;
Self::new(data.clone())
}
}
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())
}
}