1use std::{
3 fmt::{Debug, Display},
4 hash::{Hash, Hasher},
5 sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard}
6};
7
8pub struct MutCell<T> {
10 pointer: Arc<RwLock<T>>
11}
12
13impl<T> MutCell<T> {
14 pub fn new(value: T) -> Self {
15 MutCell {
16 pointer: Arc::new(RwLock::new(value))
17 }
18 }
19
20 pub fn as_ref(&self) -> RwLockReadGuard<T> {
21 self.pointer.read().unwrap()
22 }
23
24 pub fn as_mut(&self) -> RwLockWriteGuard<T> {
25 self.pointer.write().unwrap()
26 }
27
28 pub fn raw(&self) -> Arc<RwLock<T>> {
29 self.pointer.clone()
30 }
31}
32
33impl<T> Clone for MutCell<T> {
34 fn clone(&self) -> Self {
35 Self {
36 pointer: self.pointer.clone()
37 }
38 }
39}
40
41impl<T: Clone> MutCell<T> {
42 pub fn clone_out(&self) -> T {
43 self.as_ref().clone()
44 }
45}
46
47impl<T: PartialEq> PartialEq for MutCell<T> {
48 fn eq(&self, other: &Self) -> bool {
49 *self.as_ref() == *other.as_ref()
50 }
51}
52
53impl<T: Eq> Eq for MutCell<T> {}
54
55impl<T: Hash> Hash for MutCell<T> {
56 fn hash<H: Hasher>(&self, state: &mut H) {
57 self.as_ref().hash(state)
58 }
59}
60
61impl<T: Display> Display for MutCell<T> {
62 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63 self.as_ref().fmt(f)
64 }
65}
66
67impl<T: Debug> Debug for MutCell<T> {
68 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69 self.as_ref().fmt(f)
70 }
71}