atomic_ref2/
ref_.rs

1use super::AtomicOptionRef;
2use std::sync::Arc;
3
4/// An atomic reference that may be updated atomically.
5pub struct AtomicRef<T> {
6    inner: AtomicOptionRef<T>,
7}
8
9impl<T> AtomicRef<T> {
10    /// Creates a new atomic reference with a default initial value.
11    pub fn new() -> Self
12    where
13        T: Default,
14    {
15        Self::default()
16    }
17
18    /// Creates a new atomic reference from the given initial value.
19    pub fn from(value: impl Into<Arc<T>>) -> Self {
20        Self {
21            inner: AtomicOptionRef::from(value.into()),
22        }
23    }
24
25    /// Loads and returns a reference to the value.
26    pub fn load(&self) -> Arc<T> {
27        self.inner.load().unwrap()
28    }
29
30    /// Stores the value.
31    pub fn store(&self, value: impl Into<Arc<T>>) {
32        self.inner.store(value.into())
33    }
34
35    /// Swaps the value, returning the previous value.
36    pub fn swap(&self, value: impl Into<Arc<T>>) -> Arc<T> {
37        self.inner.swap(value.into()).unwrap()
38    }
39}
40
41impl<T> Default for AtomicRef<T>
42where
43    T: Default,
44{
45    fn default() -> Self {
46        Self::from(T::default())
47    }
48}