once-arc 0.1.1

Initialize-once Arc<T> containers with zero-cost reads
Documentation
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
use std::fmt;
use std::ptr;
use std::sync::Arc;
use std::sync::atomic::{AtomicPtr, Ordering};

/// A thread-safe container that can be atomically initialized once with an `Arc<T>`.
///
/// This is conceptually similar to `Atomic<Option<Arc<T>>>`, but with a critical restriction:
/// the value can only be set once. This restriction is what makes the implementation both
/// sound and extremely fast — `load` is a single atomic read with no reference count
/// manipulation.
///
/// # Examples
///
/// ```
/// use std::sync::Arc;
/// use std::sync::atomic::Ordering;
/// use once_arc::OnceArc;
///
/// let slot: OnceArc<i32> = OnceArc::new();
/// assert!(slot.get(Ordering::Acquire).is_none());
///
/// slot.store(Arc::new(42), Ordering::Release).unwrap();
///
/// // get() returns &T — just a single atomic load
/// assert_eq!(slot.get(Ordering::Acquire), Some(&42));
///
/// // load() returns a cloned Arc
/// let arc = slot.load(Ordering::Acquire).unwrap();
/// assert_eq!(*arc, 42);
///
/// // Second store fails and returns the value back.
/// let err = slot.store(Arc::new(99), Ordering::Release).unwrap_err();
/// assert_eq!(*err, 99);
/// ```
pub struct OnceArc<T> {
  ptr: AtomicPtr<T>,
}

// SAFETY: The inner `T` is behind an `Arc` and only accessible via shared reference.
// `Send` and `Sync` require `T: Send + Sync` to match `Arc<T>`'s bounds.
unsafe impl<T: Send + Sync> Send for OnceArc<T> {}
unsafe impl<T: Send + Sync> Sync for OnceArc<T> {}

impl<T> OnceArc<T> {
  /// Creates a new empty `OnceArc`.
  ///
  /// # Examples
  ///
  /// ```
  /// use once_arc::OnceArc;
  ///
  /// let slot: OnceArc<i32> = OnceArc::new();
  /// ```
  pub const fn new() -> Self {
    Self {
      ptr: AtomicPtr::new(ptr::null_mut()),
    }
  }

  /// Attempts to store the value. Returns `Ok(())` if this is the first call,
  /// or `Err(value)` if a value was already stored.
  ///
  /// `ordering` describes the required ordering for the
  /// read-modify-write operation that takes place if the None-check succeeds.
  /// Using [`Acquire`](std::sync::atomic::Ordering::Acquire) as ordering makes the store part
  /// of this operation [`Relaxed`](std::sync::atomic::Ordering::Relaxed), and using [`Release`](std::sync::atomic::Ordering::Release) makes the load [`Relaxed`](std::sync::atomic::Ordering::Relaxed).
  ///
  /// # Examples
  ///
  /// ```
  /// use std::sync::Arc;
  /// use std::sync::atomic::Ordering;
  /// use once_arc::OnceArc;
  ///
  /// let slot: OnceArc<i32> = OnceArc::new();
  /// assert!(slot.store(Arc::new(42), Ordering::Release).is_ok());
  ///
  /// // Second store fails
  /// let err = slot.store(Arc::new(99), Ordering::Release).unwrap_err();
  /// assert_eq!(*err, 99);
  /// ```
  pub fn store(&self, value: Arc<T>, ordering: Ordering) -> Result<(), Arc<T>> {
    let raw = Arc::into_raw(value) as *mut T;
    match self
      .ptr
      .compare_exchange(ptr::null_mut(), raw, ordering, Ordering::Relaxed)
    {
      Ok(_) => Ok(()),
      Err(_) => {
        // SAFETY: We just created this raw pointer from Arc::into_raw above,
        // and the CAS failed so nobody else owns it.
        let value = unsafe { Arc::from_raw(raw) };
        Err(value)
      }
    }
  }

  /// Returns a reference to the stored value, or `None` if not yet set.
  ///
  /// This is extremely fast: a single atomic load with no reference count
  /// manipulation. The returned reference is valid for as long as `&self` is
  /// valid, because the stored `Arc` is never removed until `self` is dropped.
  ///
  /// # Examples
  ///
  /// ```
  /// use std::sync::Arc;
  /// use std::sync::atomic::Ordering;
  /// use once_arc::OnceArc;
  ///
  /// let slot: OnceArc<i32> = OnceArc::new();
  /// assert_eq!(slot.get(Ordering::Acquire), None);
  ///
  /// slot.store(Arc::new(42), Ordering::Release).unwrap();
  /// assert_eq!(slot.get(Ordering::Acquire), Some(&42));
  /// ```
  pub fn get(&self, ordering: Ordering) -> Option<&T> {
    let ptr = self.ptr.load(ordering);
    if ptr.is_null() {
      None
    } else {
      // SAFETY: Once set, the pointer is never changed or freed until drop.
      // The &T lifetime is tied to &self, and drop requires &mut self,
      // so the data is guaranteed alive for the duration of the borrow.
      Some(unsafe { &*ptr })
    }
  }

  /// Loads the stored value as a cloned `Arc<T>`. This increments the reference
  /// count, so the caller gets an independent handle to the underlying data.
  ///
  /// Returns `None` if the value has not been set yet.
  ///
  /// # Examples
  ///
  /// ```
  /// use std::sync::Arc;
  /// use std::sync::atomic::Ordering;
  /// use once_arc::OnceArc;
  ///
  /// let slot = OnceArc::from(Arc::new(42));
  /// let arc = slot.load(Ordering::Acquire).unwrap();
  /// assert_eq!(*arc, 42);
  /// ```
  pub fn load(&self, ordering: Ordering) -> Option<Arc<T>> {
    let ptr = self.ptr.load(ordering);
    if ptr.is_null() {
      None
    } else {
      // SAFETY: The pointer is valid and the Arc is alive (same reasoning as get).
      // increment_strong_count keeps the existing Arc alive while we create a new one.
      unsafe { Arc::increment_strong_count(ptr) };
      Some(unsafe { Arc::from_raw(ptr) })
    }
  }

  /// Returns `true` if a value has been stored.
  ///
  /// # Examples
  ///
  /// ```
  /// use std::sync::Arc;
  /// use std::sync::atomic::Ordering;
  /// use once_arc::OnceArc;
  ///
  /// let slot: OnceArc<i32> = OnceArc::new();
  /// assert!(!slot.is_set(Ordering::Relaxed));
  ///
  /// slot.store(Arc::new(1), Ordering::Release).unwrap();
  /// assert!(slot.is_set(Ordering::Relaxed));
  /// ```
  pub fn is_set(&self, ordering: Ordering) -> bool {
    !self.ptr.load(ordering).is_null()
  }

  /// Consumes `self` and returns the stored `Arc<T>`, if any.
  ///
  /// # Examples
  ///
  /// ```
  /// use std::sync::Arc;
  /// use std::sync::atomic::Ordering;
  /// use once_arc::OnceArc;
  ///
  /// let slot = OnceArc::from(Arc::new(42));
  /// let arc = slot.into_inner().unwrap();
  /// assert_eq!(*arc, 42);
  /// ```
  pub fn into_inner(mut self) -> Option<Arc<T>> {
    let ptr = *self.ptr.get_mut();
    std::mem::forget(self); // skip Drop since we're taking ownership of the Arc
    if ptr.is_null() {
      None
    } else {
      // SAFETY: We have exclusive ownership via `self` (by value).
      Some(unsafe { Arc::from_raw(ptr) })
    }
  }

  /// Returns a mutable reference to the stored value, or `None` if not yet set.
  ///
  /// Since this requires `&mut self`, no atomic operations are needed and this
  /// is guaranteed to be the only accessor.
  ///
  /// # Examples
  ///
  /// ```
  /// use std::sync::Arc;
  /// use std::sync::atomic::Ordering;
  /// use once_arc::OnceArc;
  ///
  /// let mut slot = OnceArc::from(Arc::new(10));
  /// *slot.get_mut().unwrap() = 20;
  /// assert_eq!(slot.get(Ordering::Acquire), Some(&20));
  /// ```
  pub fn get_mut(&mut self) -> Option<&mut T> {
    let ptr = *self.ptr.get_mut();
    if ptr.is_null() {
      None
    } else {
      // SAFETY: We have exclusive access via &mut self. The pointer was created
      // by Arc::into_raw and the data is valid until drop. &mut self guarantees
      // no other references exist.
      Some(unsafe { &mut *ptr })
    }
  }
}

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

impl<T: fmt::Debug> fmt::Debug for OnceArc<T> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("OnceArc")
      .field("value", &self.get(Ordering::SeqCst))
      .finish()
  }
}

impl<T> Drop for OnceArc<T> {
  fn drop(&mut self) {
    let ptr = *self.ptr.get_mut();
    if !ptr.is_null() {
      // SAFETY: We have &mut self, so no other references exist.
      // The pointer was created by Arc::into_raw in store().
      unsafe { drop(Arc::from_raw(ptr)) };
    }
  }
}

impl<T> From<Arc<T>> for OnceArc<T> {
  fn from(value: Arc<T>) -> Self {
    Self {
      ptr: AtomicPtr::new(Arc::into_raw(value) as *mut T),
    }
  }
}

impl<T> From<Option<Arc<T>>> for OnceArc<T> {
  fn from(value: Option<Arc<T>>) -> Self {
    match value {
      Some(arc) => Self::from(arc),
      None => Self::new(),
    }
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use std::sync::Arc;
  use std::sync::atomic::Ordering;

  #[test]
  fn empty_loads_none() {
    let slot: OnceArc<i32> = OnceArc::new();
    assert!(slot.get(Ordering::Acquire).is_none());
    assert!(slot.load(Ordering::Acquire).is_none());
    assert!(!slot.is_set(Ordering::Relaxed));
  }

  #[test]
  fn set_once_and_load() {
    let slot: OnceArc<i32> = OnceArc::new();
    slot.store(Arc::new(42), Ordering::Release).unwrap();
    assert_eq!(*slot.get(Ordering::Acquire).unwrap(), 42);
    assert!(slot.is_set(Ordering::Relaxed));
  }

  #[test]
  fn set_twice_fails() {
    let slot: OnceArc<i32> = OnceArc::new();
    slot.store(Arc::new(1), Ordering::Release).unwrap();
    let err = slot.store(Arc::new(2), Ordering::Release).unwrap_err();
    assert_eq!(*err, 2);
    assert_eq!(*slot.get(Ordering::Acquire).unwrap(), 1);
  }

  #[test]
  fn load_returns_arc() {
    let slot: OnceArc<&str> = OnceArc::new();
    let original = Arc::new("hello");
    slot.store(original.clone(), Ordering::Release).unwrap();

    let loaded = slot.load(Ordering::Acquire).unwrap();
    assert!(Arc::ptr_eq(&original, &loaded));
    assert_eq!(Arc::strong_count(&original), 3); // original + slot + loaded
  }

  #[test]
  fn into_inner_returns_arc() {
    let slot: OnceArc<i32> = OnceArc::new();
    let original = Arc::new(100);
    slot.store(original.clone(), Ordering::Release).unwrap();

    let inner = slot.into_inner().unwrap();
    assert!(Arc::ptr_eq(&original, &inner));
    assert_eq!(Arc::strong_count(&original), 2); // original + inner (slot consumed)
  }

  #[test]
  fn into_inner_empty() {
    let slot: OnceArc<i32> = OnceArc::new();
    assert!(slot.into_inner().is_none());
  }

  #[test]
  fn drop_decrements_refcount() {
    let arc = Arc::new(42);
    assert_eq!(Arc::strong_count(&arc), 1);
    {
      let slot: OnceArc<i32> = OnceArc::new();
      slot.store(arc.clone(), Ordering::Release).unwrap();
      assert_eq!(Arc::strong_count(&arc), 2);
    }
    assert_eq!(Arc::strong_count(&arc), 1);
  }

  #[test]
  fn from_arc() {
    let slot = OnceArc::from(Arc::new(7));
    assert_eq!(*slot.get(Ordering::Acquire).unwrap(), 7);
  }

  #[test]
  fn from_none() {
    let slot = OnceArc::<i32>::from(None);
    assert!(slot.get(Ordering::Acquire).is_none());
  }

  #[test]
  fn from_some() {
    let slot = OnceArc::from(Some(Arc::new(55)));
    assert_eq!(*slot.get(Ordering::Acquire).unwrap(), 55);
  }

  #[test]
  fn debug_fmt() {
    let slot: OnceArc<i32> = OnceArc::new();
    slot.store(Arc::new(42), Ordering::Release).unwrap();
    let dbg = format!("{:?}", slot);
    assert!(dbg.contains("42"));
  }

  #[test]
  fn concurrent_set_exactly_one_wins() {
    use std::sync::Barrier;
    use std::thread;

    let slot = Arc::new(OnceArc::<i32>::new());
    let barrier = Arc::new(Barrier::new(10));
    let mut handles = Vec::new();

    for i in 0..10 {
      let slot = slot.clone();
      let barrier = barrier.clone();
      handles.push(thread::spawn(move || {
        barrier.wait();
        slot.store(Arc::new(i), Ordering::Release).is_ok()
      }));
    }

    let successes: Vec<bool> = handles.into_iter().map(|h| h.join().unwrap()).collect();
    assert_eq!(successes.iter().filter(|&&s| s).count(), 1);
    assert!(slot.is_set(Ordering::Relaxed));
  }

  #[test]
  fn concurrent_loads_after_set() {
    use std::sync::Barrier;
    use std::thread;

    let slot = Arc::new(OnceArc::from(Arc::new(99)));
    let barrier = Arc::new(Barrier::new(10));
    let mut handles = Vec::new();

    for _ in 0..10 {
      let slot = slot.clone();
      let barrier = barrier.clone();
      handles.push(thread::spawn(move || {
        barrier.wait();
        *slot.get(Ordering::Acquire).unwrap()
      }));
    }

    for h in handles {
      assert_eq!(h.join().unwrap(), 99);
    }
  }

  #[test]
  fn get_mut_empty() {
    let mut slot: OnceArc<i32> = OnceArc::new();
    assert!(slot.get_mut().is_none());
  }

  #[test]
  fn get_mut_modifies_value() {
    let mut slot: OnceArc<i32> = OnceArc::new();
    slot.store(Arc::new(10), Ordering::Release).unwrap();
    *slot.get_mut().unwrap() = 20;
    assert_eq!(*slot.get(Ordering::Acquire).unwrap(), 20);
  }
}