atomic_array/ref_array.rs
1use super::AtomicOptionRefArray;
2use std::sync::Arc;
3
4/// An array of non-optional references in which elements may be updated and retrieved atomically.
5pub struct AtomicRefArray<T> {
6 buf: AtomicOptionRefArray<T>,
7}
8
9impl<T> AtomicRefArray<T> {
10 /// Constructs a new array with the specified length.
11 /// All values will be initialized to their default.
12 pub fn new(len: usize) -> Self
13 where
14 T: Default,
15 {
16 Self {
17 buf: AtomicOptionRefArray::new_with(len, |_| Some(Arc::new(Default::default()))),
18 }
19 }
20
21 /// Constructs a new array with the specified length.
22 /// Uses the given function to construct each value.
23 pub fn new_with<U: Into<Arc<T>>>(len: usize, f: impl Fn(usize) -> U) -> Self {
24 Self {
25 buf: AtomicOptionRefArray::new_with(len, |i| Some(f(i).into())),
26 }
27 }
28
29 /// Returns the number of elements in the array.
30 pub fn len(&self) -> usize {
31 self.buf.len()
32 }
33
34 /// Returns `true` if the array has a length of 0.
35 pub fn is_empty(&self) -> bool {
36 self.buf.is_empty()
37 }
38
39 /// Loads and returns a reference to an value at the given position or `None`
40 /// if the value at the index is not set.
41 ///
42 /// Panics if `index` is out of bounds.
43 pub fn load(&self, index: usize) -> Arc<T> {
44 self.buf.load(index).unwrap()
45 }
46
47 /// Stores the value at the given position.
48 ///
49 /// Panics if `index` is out bounds.
50 pub fn store(&self, index: usize, value: impl Into<Arc<T>>) {
51 self.buf.store(index, value.into());
52 }
53
54 /// Swaps the value at the given position, returning the previous value.
55 ///
56 /// Panics if `index` is out of bounds.
57 pub fn swap(&self, index: usize, value: impl Into<Arc<T>>) -> Arc<T> {
58 self.buf.swap(index, value.into()).unwrap()
59 }
60}