1use std::sync::atomic::*;
2
3macro_rules! impl_array {
4 ($name:ident, $type_name:expr, $type:ty, $atomic_type:ident) => {
5 #[doc = "A `"]
6 #[doc = $type_name]
7 #[doc = "` array in which elements may be updated atomically."]
8 pub struct $name {
9 buf: Box<[$atomic_type]>,
10 }
11
12 impl $name {
13 pub fn new(len: usize) -> Self {
16 Self::new_with(len, |_| Default::default())
17 }
18
19 pub fn new_with(len: usize, f: impl Fn(usize) -> $type) -> Self {
22 let mut buf = Vec::with_capacity(len);
23
24 for i in 0..len {
25 buf.push($atomic_type::new(f(i)));
26 }
27
28 Self {
29 buf: buf.into_boxed_slice(),
30 }
31 }
32
33 pub fn len(&self) -> usize {
35 self.buf.len()
36 }
37
38 pub fn is_empty(&self) -> bool {
40 self.buf.is_empty()
41 }
42
43 pub fn load(&self, index: usize) -> $type {
47 self.buf[index].load(Ordering::SeqCst)
48 }
49
50 pub fn store(&self, index: usize, value: $type) {
54 self.buf[index].store(value, Ordering::SeqCst)
55 }
56
57 pub fn swap(&self, index: usize, value: $type) -> $type {
61 self.buf[index].swap(value, Ordering::SeqCst)
62 }
63 }
64 };
65}
66
67impl_array!(AtomicBoolArray, "bool", bool, AtomicBool);
68
69#[cfg(feature = "integer_atomics")]
70mod integer {
71 impl_array!(AtomicI8Array, "i8", i8, AtomicI8);
72 impl_array!(AtomicI16Array, "i16", i16, AtomicI16);
73 impl_array!(AtomicI32Array, "i32", i32, AtomicI32);
74 impl_array!(AtomicI64Array, "i64", i64, AtomicI64);
75
76 impl_array!(AtomicU8Array, "u8", u8, AtomicU8);
77 impl_array!(AtomicU16Array, "u16", u16, AtomicU16);
78 impl_array!(AtomicU32Array, "u32", u32, AtomicU32);
79 impl_array!(AtomicU64Array, "u64", u64, AtomicU64);
80}
81
82#[cfg(feature = "integer_atomics")]
83use self::integer::*;
84
85impl_array!(AtomicUsizeArray, "usize", usize, AtomicUsize);
86impl_array!(AtomicIsizeArray, "isize", isize, AtomicIsize);