1use std::fmt;
6use std::ops::Deref;
7use std::sync::{Arc, Weak};
8
9use atomic_refcell::AtomicRefCell;
10use malloc_size_of_derive::MallocSizeOf;
11
12#[derive(MallocSizeOf)]
13pub struct ArcRefCell<T> {
14 #[conditional_malloc_size_of]
15 value: Arc<AtomicRefCell<T>>,
16}
17
18impl<T> ArcRefCell<T> {
19 pub fn new(value: T) -> Self {
20 Self {
21 value: Arc::new(AtomicRefCell::new(value)),
22 }
23 }
24
25 pub(crate) fn downgrade(&self) -> WeakRefCell<T> {
26 WeakRefCell {
27 value: Arc::downgrade(&self.value),
28 }
29 }
30
31 pub(crate) fn ptr_eq(&self, other: &Self) -> bool {
32 Arc::ptr_eq(&self.value, &other.value)
33 }
34}
35
36impl<T> Clone for ArcRefCell<T> {
37 fn clone(&self) -> Self {
38 Self {
39 value: self.value.clone(),
40 }
41 }
42}
43
44impl<T> Default for ArcRefCell<T>
45where
46 T: Default,
47{
48 fn default() -> Self {
49 Self {
50 value: Arc::new(AtomicRefCell::new(Default::default())),
51 }
52 }
53}
54
55impl<T> Deref for ArcRefCell<T> {
56 type Target = AtomicRefCell<T>;
57
58 fn deref(&self) -> &Self::Target {
59 &self.value
60 }
61}
62
63impl<T> fmt::Debug for ArcRefCell<T>
64where
65 T: fmt::Debug,
66{
67 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
68 self.value.fmt(formatter)
69 }
70}
71
72#[derive(Debug, MallocSizeOf)]
73pub(crate) struct WeakRefCell<T> {
74 value: Weak<AtomicRefCell<T>>,
75}
76
77impl<T> Clone for WeakRefCell<T> {
78 fn clone(&self) -> Self {
79 Self {
80 value: self.value.clone(),
81 }
82 }
83}
84
85impl<T> WeakRefCell<T> {
86 pub(crate) fn upgrade(&self) -> Option<ArcRefCell<T>> {
87 self.value.upgrade().map(|value| ArcRefCell { value })
88 }
89}