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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
//! this crate provides a way that you can load or store value atomically like
//! Golang `AtomicValue`.

#[cfg(not(loom))]
use std::cell::UnsafeCell;
#[cfg(not(loom))]
use std::hint::spin_loop as spin_loop_hint;
use std::mem;
#[cfg(not(loom))]
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
#[cfg(not(loom))]
use std::sync::Arc;

#[cfg(loom)]
use loom::cell::UnsafeCell;
#[cfg(loom)]
use loom::sync::atomic::{spin_loop_hint, AtomicBool};
#[cfg(loom)]
use loom::sync::Arc;

#[derive(Debug)]
/// A wrapper provides an atomic load and store of a value.
///
/// You can use [`load`] to get the current value which is wrapped by `Arc`, or use [`store`] to
/// set a new value atomically.
///
/// [`load`]: AtomicValue::load
/// [`store`]: AtomicValue::store
///
/// # Example
///
/// ```
/// use atomic_value::AtomicValue;
///
/// let value = AtomicValue::new(10);
///
/// assert_eq!(*value.load(), 10);
/// ```
pub struct AtomicValue<T> {
    using: AtomicBool,
    value: UnsafeCell<Arc<T>>,
}

impl<T> AtomicValue<T> {
    /// Create an `AtomicValue` with provide value.
    ///
    /// # Example
    ///
    /// ```
    /// use atomic_value::AtomicValue;
    ///
    /// let value = AtomicValue::new(100);
    /// ```
    pub fn new(value: T) -> Self {
        Self {
            using: AtomicBool::new(false),
            value: UnsafeCell::new(Arc::new(value)),
        }
    }

    /// Load current value atomically.
    ///
    /// This function will return a value which wrapped by an `Arc`.
    /// After get the value, it won't be effect by [`store`], [`swap`] or [`compare_and_swap`].
    ///
    /// [`store`]: AtomicValue::store
    /// [`swap`]: AtomicValue::swap
    /// [`compare_and_swap`]: AtomicValue::compare_and_swap
    ///
    /// # Example
    ///
    /// ```
    /// use atomic_value::AtomicValue;
    ///
    /// let value = AtomicValue::new(10);
    ///
    /// assert_eq!(*value.load(), 10);
    /// ```
    ///
    pub fn load(&self) -> Arc<T> {
        while self
            .using
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
            .is_err()
        {
            spin_loop_hint()
        }

        #[cfg(loom)]
        let value = unsafe { &*self.value.with(|pointer| pointer) }.clone();

        #[cfg(not(loom))]
        let value = unsafe { &*self.value.get() }.clone();

        self.using.store(false, Ordering::Release);

        value
    }

    /// Store a new value atomically.
    ///
    /// The new value won't change any loaded value. This method like [`swap`] but won't return
    /// old value.
    ///
    /// [`swap`]: AtomicValue::swap
    ///
    /// # Example
    ///
    /// ```
    /// use atomic_value::AtomicValue;
    ///
    /// let value = AtomicValue::new(10);
    ///
    /// let old = value.load();
    ///
    /// assert_eq!(*old, 10);
    ///
    /// value.store(100);
    ///
    /// assert_eq!(*value.load(), 100);
    /// ```
    ///
    pub fn store(&self, new_value: T) {
        self.swap(new_value);
    }

    /// Store a new value into `AtomicValue`, and return the old value with `Arc` wrapping.
    ///
    /// The new value won't change any loaded value. This method like [`store`] but will return
    /// old value.
    ///
    /// [`store`]: AtomicValue::store
    ///
    /// # Example
    ///
    /// ```
    /// use atomic_value::AtomicValue;
    ///
    /// let value = AtomicValue::new(10);
    ///
    /// let old = value.load();
    ///
    /// assert_eq!(*old, 10);
    ///
    /// let old = value.swap(100);
    ///
    /// assert_eq!(*old ,10);
    ///
    /// assert_eq!(*value.load(), 100);
    /// ```
    ///
    pub fn swap(&self, new_value: T) -> Arc<T> {
        while self
            .using
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
            .is_err()
        {
            spin_loop_hint()
        }

        #[cfg(loom)]
        let pointer = unsafe { &mut *self.value.with_mut(|pointer| pointer) };

        #[cfg(not(loom))]
        let pointer = unsafe { &mut *self.value.get() };

        let old_value = mem::replace(pointer, Arc::new(new_value));

        self.using.store(false, Ordering::Release);

        old_value
    }

    /// Stores a value into the AtomicValue if the current value is the same as the `current`
    /// value.
    ///
    /// The new value won't change any loaded values.
    ///
    /// [`swap`]: AtomicValue::swap
    ///
    /// # Example
    ///
    /// ```
    /// use atomic_value::{AtomicValue, Error};
    /// use std::sync::atomic::Ordering;
    ///
    /// let value = AtomicValue::new(10);
    ///
    /// let result = value.compare_exchange(&10, 20, Ordering::AcqRel, Ordering::Acquire);
    /// assert_eq!(*result.unwrap(), 10);
    ///
    /// let result = value.compare_exchange(&10, 30, Ordering::AcqRel, Ordering::Acquire);
    /// let Error(current, new_value) = result.unwrap_err();
    ///
    /// assert_eq!(*current, 20);
    /// assert_eq!(new_value, 30);
    /// ```
    pub fn compare_exchange(
        &self,
        current: &T,
        new_value: T,
        success: Ordering,
        failure: Ordering,
    ) -> Result<Arc<T>, Error<T>>
    where
        T: PartialEq,
    {
        while self
            .using
            .compare_exchange(false, true, success, failure)
            .is_err()
        {
            spin_loop_hint()
        }

        #[cfg(loom)]
        let pointer = unsafe { &mut *self.value.with_mut(|pointer| pointer) };

        #[cfg(not(loom))]
        let pointer = unsafe { &mut *self.value.get() };

        let result = if **pointer == *current {
            Ok(mem::replace(pointer, Arc::new(new_value)))
        } else {
            Err(Error(pointer.clone(), new_value))
        };

        self.using.store(false, Ordering::Release);

        result
    }
}

unsafe impl<T: Send + Sync> Sync for AtomicValue<T> {}

/// compare exchange error.
///
/// `.0` is the current value, `.1` is the new value that is wanted set.
#[derive(Debug)]
pub struct Error<T>(pub Arc<T>, pub T);

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(not(loom))]
    #[test]
    fn load() {
        let n = 100;

        let atomic_value = AtomicValue::new(n);

        assert_eq!(*atomic_value.load(), n)
    }

    #[cfg(loom)]
    #[test]
    fn load() {
        loom::model(|| {
            let n = 100;

            let atomic_value = AtomicValue::new(n);

            assert_eq!(*atomic_value.load(), n)
        })
    }

    #[cfg(not(loom))]
    #[test]
    fn store() {
        let n = 100;

        let atomic_value = AtomicValue::new(0);

        atomic_value.store(n);

        assert_eq!(*atomic_value.load(), n)
    }

    #[cfg(loom)]
    #[test]
    fn store() {
        loom::model(|| {
            let n = 100;

            let atomic_value = AtomicValue::new(0);

            atomic_value.store(n);

            assert_eq!(*atomic_value.load(), n)
        })
    }

    #[cfg(not(loom))]
    #[test]
    fn compare_exchange() {
        let atomic_value = AtomicValue::new(0);

        let result = atomic_value.compare_exchange(&0, 100, Ordering::AcqRel, Ordering::Acquire);
        assert_eq!(*result.unwrap(), 0);

        let result = atomic_value.compare_exchange(&0, 200, Ordering::AcqRel, Ordering::Acquire);
        let Error(current, new_value) = result.unwrap_err();

        assert_eq!(*current, 100);
        assert_eq!(new_value, 200);
    }

    #[cfg(loom)]
    #[test]
    fn compare_exchange() {
        loom::model(|| {
            let atomic_value = AtomicValue::new(0);

            let result =
                atomic_value.compare_exchange(&0, 100, Ordering::AcqRel, Ordering::Acquire);
            assert_eq!(*result.unwrap(), 0);

            let result =
                atomic_value.compare_exchange(&0, 200, Ordering::AcqRel, Ordering::Acquire);
            let Error(current, new_value) = result.unwrap_err();

            assert_eq!(*current, 100);
            assert_eq!(new_value, 200);
        })
    }
}