vm_memory/
atomic_integer.rs1use std::sync::atomic::Ordering;
5
6pub unsafe trait AtomicInteger: Sync + Send {
13 type V;
15
16 fn new(v: Self::V) -> Self;
18
19 fn load(&self, order: Ordering) -> Self::V;
21
22 fn store(&self, val: Self::V, order: Ordering);
24}
25
26macro_rules! impl_atomic_integer_ops {
27 ($T:path, $V:ty) => {
28 unsafe impl AtomicInteger for $T {
32 type V = $V;
33
34 fn new(v: Self::V) -> Self {
35 Self::new(v)
36 }
37
38 fn load(&self, order: Ordering) -> Self::V {
39 self.load(order)
40 }
41
42 fn store(&self, val: Self::V, order: Ordering) {
43 self.store(val, order)
44 }
45 }
46 };
47}
48
49impl_atomic_integer_ops!(std::sync::atomic::AtomicI8, i8);
57impl_atomic_integer_ops!(std::sync::atomic::AtomicI16, i16);
58impl_atomic_integer_ops!(std::sync::atomic::AtomicI32, i32);
59#[cfg(any(
60 target_arch = "x86_64",
61 target_arch = "aarch64",
62 target_arch = "powerpc64",
63 target_arch = "s390x",
64 target_arch = "riscv64"
65))]
66impl_atomic_integer_ops!(std::sync::atomic::AtomicI64, i64);
67
68impl_atomic_integer_ops!(std::sync::atomic::AtomicU8, u8);
69impl_atomic_integer_ops!(std::sync::atomic::AtomicU16, u16);
70impl_atomic_integer_ops!(std::sync::atomic::AtomicU32, u32);
71#[cfg(any(
72 target_arch = "x86_64",
73 target_arch = "aarch64",
74 target_arch = "powerpc64",
75 target_arch = "s390x",
76 target_arch = "riscv64"
77))]
78impl_atomic_integer_ops!(std::sync::atomic::AtomicU64, u64);
79
80impl_atomic_integer_ops!(std::sync::atomic::AtomicIsize, isize);
81impl_atomic_integer_ops!(std::sync::atomic::AtomicUsize, usize);
82
83#[cfg(test)]
84mod tests {
85 use super::*;
86
87 use std::fmt::Debug;
88 use std::sync::atomic::AtomicU32;
89
90 fn check_atomic_integer_ops<A: AtomicInteger>()
91 where
92 A::V: Copy + Debug + From<u8> + PartialEq,
93 {
94 let v = A::V::from(0);
95 let a = A::new(v);
96 assert_eq!(a.load(Ordering::Relaxed), v);
97
98 let v2 = A::V::from(100);
99 a.store(v2, Ordering::Relaxed);
100 assert_eq!(a.load(Ordering::Relaxed), v2);
101 }
102
103 #[test]
104 fn test_atomic_integer_ops() {
105 check_atomic_integer_ops::<AtomicU32>()
106 }
107}