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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
#![doc = include_str!("../README.md")]
#![cfg_attr(feature = "const-new", feature(const_fn_trait_bound))]

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

/// Atomically swappable/clonable Arc pointer value.
pub type ArcCell<T> = AtomicCell<Arc<T>>;
/// Atomically swappable/clonable Weak Arc pointer value.
pub type WeakCell<T> = AtomicCell<Weak<T>>;

/// Atomically swappable/clonable/optional Arc pointer value.
pub type OptionalArcCell<T> = AtomicCell<Option<Arc<T>>>;
/// Atomically swappable/clonable/optional Weak Arc pointer value.
pub type OptionalWeakCell<T> = AtomicCell<Option<Weak<T>>>;

/// An atomic-based cell designed for holding Arc-style pointers.
pub struct AtomicCell<T: AtomicCellStorable> {
    value: AtomicUsize,
    _marker: PhantomData<T>,
}

impl<T: AtomicCellStorable> AtomicCell<T> {
    /// Create a new AtomicCell with the given initial value.
    pub fn new(value: T) -> Self {
        AtomicCell {
            value: AtomicUsize::new(value.into_value()),
            _marker: PhantomData,
        }
    }

    /// Replace the value in the cell, returning the old value.
    pub fn set(&self, value: T) -> T {
        let old = self.internal_take();
        self.internal_put(value);
        old
    }

    fn internal_take(&self) -> T {
        unsafe {
            let mut current = self.value.load(Ordering::SeqCst);
            T::from_value(loop {
                // Try to take it ourselves
                match self.value.compare_exchange_weak(
                    current,
                    T::TAKEN_VALUE,
                    Ordering::SeqCst,
                    Ordering::SeqCst,
                ) {
                    Ok(val) if val != T::TAKEN_VALUE => break val,
                    Ok(_) => current = T::TAKEN_VALUE, // Someone else was working on it, retry
                    Err(new_val) => current = new_val, // Someone got to it first, retry
                }

                // Hint to the CPU we're in a spin loop to reduce power consumption and allow
                // another hyperthread to possibly start.
                core::hint::spin_loop();
            })
        }
    }

    fn internal_put(&self, value: T) {
        let _old = self.value.swap(value.into_value(), Ordering::SeqCst);
        debug_assert_eq!(_old, T::TAKEN_VALUE);
    }
}

impl<T: AtomicCellStorable> Drop for AtomicCell<T> {
    fn drop(&mut self) {
        unsafe {
            let _ = T::from_value(self.value.load(Ordering::SeqCst));
        }
    }
}

impl<T: AtomicCellStorable + Clone> AtomicCell<T> {
    /// Returns a clone of the stored value.
    pub fn get(&self) -> T {
        let value = self.internal_take();
        let copy = value.clone();
        self.internal_put(value);
        copy
    }
}

impl<T: AtomicCellStorable + Clone> Clone for AtomicCell<T> {
    fn clone(&self) -> AtomicCell<T> {
        AtomicCell::new(self.get())
    }
}

impl<T: AtomicCellStorable + Default> AtomicCell<T> {
    /// Take the value stored in the cell, replacing it with the default value.
    pub fn take(&self) -> T {
        // We must construct the new value first in case it panics.
        let new_value = T::default();

        let value = self.internal_take();
        self.internal_put(new_value);

        value
    }
}

impl<T: AtomicCellStorable + Default> Default for AtomicCell<T> {
    fn default() -> Self {
        AtomicCell::new(T::default())
    }
}

#[cfg(feature = "const-new")]
impl<T: AtomicCellStorable + AtomicCellConstInit> AtomicCell<T> {
    pub const fn const_new() -> Self {
        AtomicCell {
            value: AtomicUsize::new(T::DEFAULT_VALUE),
            _marker: PhantomData,
        }
    }
}

impl<T> AtomicCell<Weak<T>> {
    /// Create a new AtomicCell with an empty Weak<T> stored inside.
    pub fn empty() -> Self {
        AtomicCell::new(Weak::new())
    }

    /// Attempt to upgrade the Weak pointer to a strong Arc pointer.
    pub fn upgrade(&self) -> Option<Arc<T>> {
        self.get().upgrade()
    }

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

impl<T> AtomicCell<Option<Weak<T>>> {
    /// Attempt to upgrade the Weak pointer to a strong Arc pointer (if it is not None).
    pub fn upgrade(&self) -> Option<Arc<T>> {
        self.get().and_then(|weak| weak.upgrade())
    }

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

impl<T: AtomicCellStorable + Clone + Debug> Debug for AtomicCell<T> {
    fn fmt(&self, fmt: &mut Formatter) -> std::fmt::Result {
        fmt.debug_tuple("AtomicCell").field(&self.get()).finish()
    }
}

/// It is up to the implementer to ensure this is safe to implement.
///
/// `from_value` and `into_value` should never panic nor return TAKEN_VALUE.
/// It is also up to the implementer to ensure that if T implements Clone,
/// its implementation of clone() will never panic.
pub unsafe trait AtomicCellStorable {
    /// A sentinel value that a valid instance should never occupy.
    const TAKEN_VALUE: usize;
    /// Convert an instance into a raw value, transferring ownership.
    fn into_value(self) -> usize;
    /// Convert a raw value back into an instance.
    unsafe fn from_value(value: usize) -> Self;
}

unsafe impl<T> AtomicCellStorable for Arc<T> {
    const TAKEN_VALUE: usize = usize::MAX;

    fn into_value(self) -> usize {
        Arc::into_raw(self) as usize
    }

    unsafe fn from_value(value: usize) -> Self {
        Arc::from_raw(value as *const T)
    }
}

unsafe impl<T> AtomicCellStorable for Weak<T> {
    // This must be MAX-1 because MAX is the sentinel value Weak uses for the empty state.
    const TAKEN_VALUE: usize = usize::MAX - 1;

    fn into_value(self) -> usize {
        Weak::into_raw(self) as usize
    }

    unsafe fn from_value(value: usize) -> Self {
        Weak::from_raw(value as *const T)
    }
}

const EMPTY_OPTION: usize = 0;

unsafe impl<T> AtomicCellStorable for Option<Arc<T>> {
    const TAKEN_VALUE: usize = <Arc<T> as AtomicCellStorable>::TAKEN_VALUE;

    fn into_value(self) -> usize {
        match self {
            None => EMPTY_OPTION,
            Some(arc) => Arc::into_raw(arc) as usize,
        }
    }

    unsafe fn from_value(value: usize) -> Self {
        match value {
            EMPTY_OPTION => None,
            value => Some(Arc::from_raw(value as *const T)),
        }
    }
}

unsafe impl<T> AtomicCellStorable for Option<Weak<T>> {
    const TAKEN_VALUE: usize = <Weak<T> as AtomicCellStorable>::TAKEN_VALUE;

    fn into_value(self) -> usize {
        match self {
            None => EMPTY_OPTION,
            Some(arc) => Weak::into_raw(arc) as usize,
        }
    }

    unsafe fn from_value(value: usize) -> Self {
        match value {
            EMPTY_OPTION => None,
            value => Some(Weak::from_raw(value as *const T)),
        }
    }
}

pub unsafe trait AtomicCellConstInit {
    const DEFAULT_VALUE: usize;
}

unsafe impl<T> AtomicCellConstInit for Option<Arc<T>> {
    const DEFAULT_VALUE: usize = EMPTY_OPTION;
}

unsafe impl<T> AtomicCellConstInit for Option<Weak<T>> {
    const DEFAULT_VALUE: usize = EMPTY_OPTION;
}

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

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

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

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

        let cell = WeakCell::empty();
        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(Arc::new(DropCount));
        }
        assert_eq!(DROPS.load(Ordering::SeqCst), 1);
    }
}