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
use std::sync::Arc;
use std::sync::atomic::{AtomicPtr, Ordering};
use std::mem;

struct ArcCellInner<T> {
    arc: AtomicPtr<T>
}

impl<T> Drop for ArcCellInner<T> {
    fn drop(&mut self) {
        // by the time we get to this point, we *should* be the only ArcCellInner<T> remaining.
        unsafe { Arc::from_raw(self.arc.load(Ordering::Relaxed)); }
    }
}

impl<T> ArcCellInner<T> {
    // TOCO const fn
    #[inline]
    pub unsafe fn new(v: Arc<T>) -> Self {
        ArcCellInner { arc: AtomicPtr::new(Arc::into_raw(v) as *mut T) }
    }

    #[inline]
    pub unsafe fn set(&self, v: Arc<T>, order: Ordering) {
        // May need to use SeqCst for correctness?
        // I think not using SeqCst may trigger memory leaks or double-free under some
        // circumstances.
        // TODO test this.
        // (Also might need fences.)
        Arc::from_raw(self.arc.swap(Arc::into_raw(v) as *mut T, order));
    }

    #[inline]
    pub unsafe fn get(&self, order: Ordering) -> Arc<T> {
        let old = Arc::from_raw(self.arc.load(order));
        // Arc.clone() must not panic as that would cause double-frees and things like that, so
        // this is "safe".
        let new = old.clone();
        // must not drop old!
        mem::forget(old);
        new
    }

    #[inline]
    pub unsafe fn swap(&self, other: Arc<T>, order: Ordering) -> Arc<T> {
        Arc::from_raw(self.arc.swap(Arc::into_raw(other) as *mut T, order))
    }

    #[inline]
    pub unsafe fn compare_and_swap(&self, current: Arc<T>, new: Arc<T>, order: Ordering) -> Arc<T> {
        let nptr = Arc::into_raw(new) as *mut T;
        let cptr = Arc::into_raw(current) as *mut T;
        let res = self.arc.compare_and_swap(cptr, nptr, order);
        if res != cptr {
            Arc::from_raw(nptr);
        }
        Arc::from_raw(res)
    }

    #[inline]
    pub unsafe fn compare_exchange(&self, current: Arc<T>, new: Arc<T>, success: Ordering, failure: Ordering) -> Result<Arc<T>, Arc<T>> {
        let ptr = Arc::into_raw(new) as *mut T;
        match self.arc.compare_exchange(Arc::into_raw(current) as *mut T, ptr, success, failure) {
            Result::Ok(x) => Ok(Arc::from_raw(x)),
            Result::Err(x) => { Arc::from_raw(ptr); Err(Arc::from_raw(x)) }
        }
    }

    #[inline]
    pub unsafe fn compare_exchange_weak(&self, current: Arc<T>, new: Arc<T>, success: Ordering, failure: Ordering) -> Result<Arc<T>, Arc<T>> {
        let ptr = Arc::into_raw(new) as *mut T;
        match self.arc.compare_exchange_weak(Arc::into_raw(current) as *mut T, ptr, success, failure) {
            Result::Ok(x) => Ok(Arc::from_raw(x)),
            Result::Err(x) => { Arc::from_raw(ptr); Err(Arc::from_raw(x)) }
        }
    }
}

#[cfg(feature = "experimental")]
pub type ExperimentalArcCell<T> = ArcCellInner<T>;

/// A thread-safe, lock-free mutable reference.
///
/// # Examples
///
/// Using ArcCell for atomic compare-and-swap functionality:
///
/// ```
/// use arccell::ArcCell;
/// use std::sync::Arc;
///
/// let acell = ArcCell::new(Arc::new(1i32));
///
/// let mut old = acell.get();
/// let mut new = Arc::new(*old + 1);
/// loop {
///     match acell.compare_exchange(old, new) {
///         Ok(x) => {
///             old = x;
///             break;
///         },
///         Err(x) => {
///             old = x;
///             new = Arc::new(*old + 1);
///         }
///     }
/// }
/// assert_eq!(*old + 1, *acell.get());
/// ```
///
/// Using ArcCell with Arc<T> (remember, ArcCell by itself is not an Arc, it only refers to an
/// Arc):
///
/// ```
/// use arccell::ArcCell;
/// use std::sync::Arc;
///
/// let acell = ArcCell::new(Arc::new(1i32));
///
/// let arc = Arc::new(acell);
///
/// let other = arc.clone();
///
/// assert!(Arc::ptr_eq(&arc.get(), &other.get()));
///
/// assert_eq!(*other.get(), 1);
/// ```
///
/// Note: For simple examples like this, it might be best to use [one of the `Atomic`
/// types][atomic].
///
/// [atomic]: https://doc.rust-lang.org/std/sync/atomic/index.html
pub struct ArcCell<T> {
    inner: ArcCellInner<T>
}

impl<T> ArcCell<T> {
    /// Creates a new `ArcCell` initialized with the given `Arc<T>`.
    #[inline]
    pub fn new(v: Arc<T>) -> Self {
        unsafe { ArcCell { inner: ArcCellInner::new(v) } }
    }

    #[inline]
    pub fn set(&self, v: Arc<T>) {
        unsafe { self.inner.set(v, Ordering::SeqCst) }
    }

    #[inline]
    pub fn get(&self) -> Arc<T> {
        unsafe { self.inner.get(Ordering::SeqCst) }
    }

    #[inline]
    pub fn swap(&self, v: Arc<T>) -> Arc<T> {
        unsafe { self.inner.swap(v, Ordering::SeqCst) }
    }

    #[inline]
    pub fn compare_and_swap(&self, current: Arc<T>, other: Arc<T>) -> Arc<T> {
        unsafe { self.inner.compare_and_swap(current, other, Ordering::SeqCst) }
    }

    #[inline]
    pub fn compare_exchange(&self, current: Arc<T>, other: Arc<T>) -> Result<Arc<T>, Arc<T>> {
        unsafe { self.inner.compare_exchange(current, other, Ordering::SeqCst, Ordering::SeqCst) }
    }

    #[inline]
    pub fn compare_exchange_weak(&self, current: Arc<T>, other: Arc<T>) -> Result<Arc<T>, Arc<T>> {
        unsafe { self.inner.compare_exchange_weak(current, other, Ordering::SeqCst, Ordering::SeqCst) }
    }
}