once_ptr/
lib.rs

1//! An wrapper around an [`AtomicPtr`] that can only be set once.
2
3use std::sync::atomic::AtomicPtr;
4
5/// An atomic pointer that can only be initialized once.
6pub struct OncePtr<T>(AtomicPtr<T>);
7
8impl<T> OncePtr<T> {
9    /// Create a new uninitialized pointer.
10    #[inline]
11    pub fn null() -> Self {
12        Self(AtomicPtr::new(std::ptr::null_mut()))
13    }
14
15    /// Create a new initialized pointer for the given data.
16    #[inline]
17    pub fn new(value: T) -> Self {
18        let ptr = Box::into_raw(Box::new(value));
19        Self(AtomicPtr::new(ptr))
20    }
21
22    /// Initialize the store with the provided value.
23    ///
24    /// # Panics
25    ///
26    /// If the store is already initialized before.
27    #[inline]
28    pub fn store(&self, value: T) {
29        let pointer = Box::into_raw(Box::new(value));
30        let previous = self.0.swap(pointer, std::sync::atomic::Ordering::Acquire);
31        if !previous.is_null() {
32            // Safety: The `previous` data is not null.
33            unsafe {
34                drop(Box::from_raw(previous));
35            }
36
37            panic!("Store can only be called once.");
38        }
39    }
40
41    /// Returns true if the store is not initialized and is null.
42    #[inline]
43    pub fn is_null(&self) -> bool {
44        let ptr = self.0.load(std::sync::atomic::Ordering::Relaxed);
45        ptr.is_null()
46    }
47
48    /// Load the atomic store and return a reference to the underlying data or [`None`]
49    /// if the store is not initialized yet.
50    #[inline]
51    pub fn load(&self) -> Option<&T> {
52        let ptr = self.0.load(std::sync::atomic::Ordering::Relaxed);
53        if ptr.is_null() {
54            None
55        } else {
56            Some(unsafe { &*ptr })
57        }
58    }
59
60    /// Load the atomic store and return a reference to the underlying data without
61    /// checking if it's null.
62    ///
63    /// # Safety
64    ///
65    /// It is up to the caller to ensure that the pointer is not null.
66    #[inline]
67    pub unsafe fn load_unchecked(&self) -> &T {
68        let ptr = self.0.load(std::sync::atomic::Ordering::Relaxed);
69        unsafe { &*ptr }
70    }
71
72    /// Load the atomic store and return a mutable reference to the underlying data or
73    /// [`None`] if the store is not initialized yet.
74    ///
75    /// This is safe because the mutable reference guarantees that no other threads are
76    /// concurrently accessing the atomic data.
77    #[inline]
78    pub fn load_mut(&mut self) -> Option<&mut T> {
79        let ptr = *self.0.get_mut();
80        if ptr.is_null() {
81            None
82        } else {
83            Some(unsafe { &mut *ptr })
84        }
85    }
86
87    /// Load the atomic store and return a mutable reference to the underlying data
88    /// without checking if it's null.
89    ///
90    /// # Safety
91    ///
92    /// It is up to the caller to ensure that the pointer is not null.
93    #[inline]
94    pub unsafe fn load_mut_unchecked(&mut self) -> &mut T {
95        let ptr = *self.0.get_mut();
96        unsafe { &mut *ptr }
97    }
98
99    /// Returns the data owned by this store.
100    #[inline]
101    pub fn into_inner(mut self) -> Option<T> {
102        let ptr = self.0.get_mut();
103        if ptr.is_null() {
104            None
105        } else {
106            let ptr = std::mem::replace(ptr, std::ptr::null_mut());
107            Some(*unsafe { Box::from_raw(ptr) })
108        }
109    }
110}
111
112impl<T> Drop for OncePtr<T> {
113    fn drop(&mut self) {
114        let ptr = *self.0.get_mut();
115        if !ptr.is_null() {
116            // SAFETY: We own the data.
117            unsafe {
118                drop(Box::from_raw(ptr));
119            }
120        }
121    }
122}
123
124impl<T> From<T> for OncePtr<T> {
125    fn from(value: T) -> Self {
126        Self::new(value)
127    }
128}
129
130impl<T> Default for OncePtr<T>
131where
132    T: Default,
133{
134    fn default() -> Self {
135        OncePtr::new(T::default())
136    }
137}
138
139#[cfg(test)]
140mod tests {
141    use super::OncePtr;
142
143    #[test]
144    fn is_null_should_work() {
145        let ptr = OncePtr::<Vec<u8>>::null();
146        assert!(ptr.is_null(), "expected pointer to be null.");
147        assert!(ptr.load().is_none());
148        ptr.store(vec![1, 2]);
149        assert!(!ptr.is_null(), "expected pointer to not be null.");
150        assert_eq!(ptr.load(), Some(&vec![1, 2]));
151    }
152
153    #[test]
154    fn new_should_not_be_null() {
155        let ptr = OncePtr::new(vec![1, 2]);
156        assert!(!ptr.is_null(), "expected value to not be null");
157        assert_eq!(ptr.load(), Some(&vec![1, 2]));
158    }
159
160    #[test]
161    #[should_panic]
162    fn double_store_should_panic() {
163        let ptr = OncePtr::null();
164        ptr.store(1);
165        ptr.store(1);
166    }
167
168    #[test]
169    #[should_panic]
170    fn store_after_new_should_panic() {
171        let ptr = OncePtr::new(vec![1, 2]);
172        ptr.store(vec![]);
173    }
174
175    #[test]
176    fn load_mut_should_work() {
177        let mut ptr = OncePtr::<usize>::null();
178        assert_eq!(ptr.load_mut(), None);
179
180        let mut ptr = OncePtr::<usize>::new(1);
181        assert_eq!(ptr.load_mut(), Some(&mut 1));
182    }
183}