1use std::{
8 cell::{Ref, RefCell, RefMut},
9 rc::Rc,
10 sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard},
11};
12
13#[derive(Default)]
19pub struct Shared<T> {
20 data: Rc<RefCell<T>>,
21}
22
23impl<T> Clone for Shared<T> {
24 fn clone(&self) -> Self {
25 Self {
26 data: self.data.clone(),
27 }
28 }
29}
30
31impl<T> Shared<T> {
32 pub fn new(data: T) -> Self {
34 Self {
35 data: Rc::new(RefCell::new(data)),
36 }
37 }
38
39 pub fn try_consume(self) -> Result<T, Self> {
42 match Rc::try_unwrap(self.data) {
43 Ok(data) => Ok(data.into_inner()),
44 Err(data) => Err(Self { data }),
45 }
46 }
47
48 pub fn read(&'_ self) -> Option<Ref<'_, T>> {
51 self.data.try_borrow().ok()
52 }
53
54 pub fn write(&'_ self) -> Option<RefMut<'_, T>> {
57 self.data.try_borrow_mut().ok()
58 }
59
60 pub fn swap(&self, data: T) -> Option<T> {
63 let mut value = self.data.try_borrow_mut().ok()?;
64 Some(std::mem::replace(&mut value, data))
65 }
66
67 pub fn references_count(&self) -> usize {
69 Rc::strong_count(&self.data)
70 }
71
72 pub fn does_share_reference(&self, other: &Self) -> bool {
74 Rc::ptr_eq(&self.data, &other.data)
75 }
76}
77
78#[derive(Default)]
83pub struct AsyncShared<T> {
84 data: Arc<RwLock<T>>,
85}
86
87impl<T> Clone for AsyncShared<T> {
88 fn clone(&self) -> Self {
89 Self {
90 data: self.data.clone(),
91 }
92 }
93}
94
95impl<T> AsyncShared<T> {
96 pub fn new(data: T) -> Self {
98 Self {
99 data: Arc::new(RwLock::new(data)),
100 }
101 }
102
103 pub fn try_consume(self) -> Result<T, Self> {
106 match Arc::try_unwrap(self.data) {
107 Ok(data) => Ok(data.into_inner().unwrap()),
108 Err(data) => Err(Self { data }),
109 }
110 }
111
112 pub fn read(&'_ self) -> Option<RwLockReadGuard<'_, T>> {
115 self.data.read().ok()
116 }
117
118 pub fn write(&'_ self) -> Option<RwLockWriteGuard<'_, T>> {
121 self.data.write().ok()
122 }
123
124 pub fn swap(&self, data: T) -> Option<T> {
127 let mut value = self.data.write().ok()?;
128 Some(std::mem::replace(&mut value, data))
129 }
130
131 pub fn references_count(&self) -> usize {
133 Arc::strong_count(&self.data)
134 }
135
136 pub fn does_share_reference(&self, other: &Self) -> bool {
138 Arc::ptr_eq(&self.data, &other.data)
139 }
140}
141
142#[cfg(test)]
143mod tests {
144 use super::Shared;
145
146 #[test]
147 fn test_shared() {
148 let a = Shared::new(42);
149 assert_eq!(a.references_count(), 1);
150 assert_eq!(*a.read().unwrap(), 42);
151 let b = a.clone();
152 assert_eq!(a.references_count(), 2);
153 assert_eq!(b.references_count(), 2);
154 assert_eq!(*b.read().unwrap(), 42);
155 *b.write().unwrap() = 10;
156 assert_eq!(*a.read().unwrap(), 10);
157 assert_eq!(*b.read().unwrap(), 10);
158 assert!(b.try_consume().is_err());
159 assert_eq!(a.try_consume().ok().unwrap(), 10);
160 }
161}