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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
#![doc = include_str!("../README.md")]

use std::fmt;
use std::marker::PhantomData;
use std::mem;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Weak};

const EMPTY: usize = 0;
// It's impossible for an Arc to have this address because the inside is at least 2 usizes big
const TAKEN: usize = usize::MAX;

/// A Cell for containing a strong reference
pub struct ArcCell<T> {
    inner: AtomicUsize,
    _marker: PhantomData<Arc<T>>,
}

impl<T> ArcCell<T> {
    /// Constructs an ArcCell which initially points to `value`
    pub fn new(value: Option<Arc<T>>) -> ArcCell<T> {
        ArcCell {
            inner: AtomicUsize::new(arc_to_val(value)),
            _marker: PhantomData,
        }
    }

    fn inner_take(&self) -> Option<Arc<T>> {
        unsafe { val_to_arc(take_val(&self.inner)) }
    }

    fn put(&self, ptr: Option<Arc<T>>) {
        put_val(&self.inner, arc_to_val(ptr));
    }

    /// Get the currently contained pointer and return it, incrementing the reference count
    pub fn get(&self) -> Option<Arc<T>> {
        let ptr = self.inner_take();
        let res = ptr.clone();
        self.put(ptr);
        res
    }

    /// Change the currently stored pointer, returning the old value.
    pub fn set(&self, value: Option<Arc<T>>) -> Option<Arc<T>> {
        let old = self.inner_take();
        self.put(value);
        old
    }

    /// Take the currently stored pointer, replacing it with None
    pub fn take(&self) -> Option<Arc<T>> {
        self.set(None)
    }
}

impl<T> Drop for ArcCell<T> {
    fn drop(&mut self) {
        self.take();
    }
}

impl<T> Clone for ArcCell<T> {
    fn clone(&self) -> ArcCell<T> {
        let value = self.get();
        ArcCell::new(value)
    }
}

impl<T> Default for ArcCell<T> {
    fn default() -> Self {
        ArcCell::new(None)
    }
}

impl<T: fmt::Debug> fmt::Debug for ArcCell<T> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        self.get().fmt(fmt)
    }
}

/// A Cell for containing a weak reference
pub struct WeakCell<T> {
    inner: AtomicUsize,
    _marker: PhantomData<Weak<T>>,
}

impl<T> WeakCell<T> {
    /// Constructs the weak cell with the given value.
    pub fn new(value: Option<Weak<T>>) -> WeakCell<T> {
        WeakCell {
            inner: AtomicUsize::new(unsafe { mem::transmute(value) }),
            _marker: PhantomData,
        }
    }

    fn inner_take(&self) -> Option<Weak<T>> {
        unsafe { val_to_weak(take_val(&self.inner)) }
    }

    fn put(&self, ptr: Option<Weak<T>>) {
        put_val(&self.inner, weak_to_val(ptr));
    }

    /// Get the Weak pointer as it is at this moment
    pub fn get(&self) -> Option<Weak<T>> {
        let ptr = self.inner_take();
        let res = ptr.clone();
        self.put(ptr);
        res
    }

    /// Set a Weak pointer you currently have as the pointer in this cell
    pub fn set(&self, value: Option<Weak<T>>) -> Option<Weak<T>> {
        let old = self.inner_take();
        self.put(value);
        old
    }

    /// Resets the stored value to be empty
    pub fn take(&self) -> Option<Weak<T>> {
        self.set(None)
    }

    /// Try to upgrade the Weak pointer as it is now into a Strong pointer
    pub fn upgrade(&self) -> Option<Arc<T>> {
        self.get().and_then(|weak| weak.upgrade())
    }

    /// Downgrade a Strong pointer and store it in the cell
    pub fn store(&self, value: &Arc<T>) {
        self.set(Some(Arc::downgrade(value)));
    }
}

impl<T> Drop for WeakCell<T> {
    fn drop(&mut self) {
        self.take();
    }
}

impl<T> Clone for WeakCell<T> {
    fn clone(&self) -> WeakCell<T> {
        let value = self.get();
        WeakCell::new(value)
    }
}

impl<T> Default for WeakCell<T> {
    fn default() -> Self {
        WeakCell::new(None)
    }
}

impl<T: fmt::Debug> fmt::Debug for WeakCell<T> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        self.upgrade().fmt(fmt)
    }
}

#[cfg(test)]
mod tests {
    use crate::{ArcCell, WeakCell};
    use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};

    #[test]
    fn arc_cell() {
        let data1 = Arc::new(5);
        let data2 = Arc::new(6);

        let cell = ArcCell::new(Some(data1));
        assert_eq!(cell.get().as_deref(), Some(&5));
        cell.set(Some(data2));
        assert_eq!(cell.get().as_deref(), Some(&6));
    }

    #[test]
    fn weak_cell() {
        let data = Arc::new(5);

        let cell = WeakCell::new(None);
        cell.store(&data);
        assert_eq!(cell.upgrade(), Some(data.clone()));
        drop(data);
        assert_eq!(cell.upgrade(), None);
    }

    #[test]
    fn cell_drops() {
        static DROPS: AtomicUsize = AtomicUsize::new(0);
        struct DropCount;
        impl std::ops::Drop for DropCount {
            fn drop(&mut self) {
                DROPS.fetch_add(1, Ordering::SeqCst);
            }
        }
        {
            let _cell = ArcCell::new(Some(Arc::new(DropCount)));
        }
        assert_eq!(DROPS.load(Ordering::SeqCst), 1);
    }
}

fn take_val(inner: &AtomicUsize) -> usize {
    let mut ptr = inner.load(Ordering::SeqCst);
    loop {
        // Try to take it ourselves
        match inner.compare_exchange_weak(ptr, TAKEN, Ordering::SeqCst, Ordering::SeqCst) {
            Ok(TAKEN) => ptr = TAKEN, // Someone else wass working on it, retry
            Ok(ptr) => break ptr,
            Err(new_ptr) => ptr = new_ptr, // Someone got to it first, retry
        }
    }
}

fn put_val(inner: &AtomicUsize, val: usize) {
    inner.store(val, Ordering::SeqCst);
}

fn arc_to_val<T>(ptr: Option<Arc<T>>) -> usize {
    match ptr {
        Some(ptr) => Arc::into_raw(ptr) as usize,
        None => EMPTY,
    }
}

unsafe fn val_to_arc<T>(val: usize) -> Option<Arc<T>> {
    match val {
        TAKEN => panic!("Something terrible has happened"),
        EMPTY => None,
        ptr => Some(Arc::from_raw(ptr as *const T)),
    }
}

fn weak_to_val<T>(ptr: Option<Weak<T>>) -> usize {
    match ptr {
        Some(ptr) => Weak::into_raw(ptr) as usize,
        None => EMPTY,
    }
}

unsafe fn val_to_weak<T>(val: usize) -> Option<Weak<T>> {
    match val {
        TAKEN => panic!("Something terrible has happened"),
        EMPTY => None,
        ptr => Some(Weak::from_raw(ptr as *const T)),
    }
}