shuttle_std/sync/atomic/
bool.rs1use crate::sync::atomic::Atomic;
2#[cfg(test)]
3use crate::sync::ResourceSignature;
4use std::sync::atomic::Ordering;
5
6pub struct AtomicBool {
8 inner: Atomic<bool>,
9}
10
11impl Default for AtomicBool {
12 fn default() -> Self {
13 Self::new(Default::default())
14 }
15}
16
17impl From<bool> for AtomicBool {
18 fn from(b: bool) -> Self {
19 Self::new(b)
20 }
21}
22
23impl std::fmt::Debug for AtomicBool {
24 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
25 std::fmt::Debug::fmt(unsafe { &self.raw_load() }, f)
26 }
27}
28
29impl AtomicBool {
30 #[track_caller]
32 pub const fn new(v: bool) -> Self {
33 Self { inner: Atomic::new(v) }
34 }
35
36 pub fn get_mut(&mut self) -> &mut bool {
38 self.inner.get_mut()
39 }
40
41 pub fn into_inner(self) -> bool {
43 self.inner.into_inner()
44 }
45
46 pub fn load(&self, order: Ordering) -> bool {
48 self.inner.load(order)
49 }
50
51 pub fn store(&self, val: bool, order: Ordering) {
53 self.inner.store(val, order)
54 }
55
56 pub fn swap(&self, val: bool, order: Ordering) -> bool {
58 self.inner.swap(val, order)
59 }
60
61 pub fn fetch_update<F>(&self, set_order: Ordering, fetch_order: Ordering, f: F) -> Result<bool, bool>
65 where
66 F: FnMut(bool) -> Option<bool>,
67 {
68 self.inner.fetch_update(set_order, fetch_order, f)
69 }
70
71 #[deprecated(since = "0.0.6", note = "Use `compare_exchange` or `compare_exchange_weak` instead")]
74 pub fn compare_and_swap(&self, current: bool, new: bool, order: Ordering) -> bool {
75 match self.compare_exchange(current, new, order, order) {
76 Ok(v) => v,
77 Err(v) => v,
78 }
79 }
80
81 pub fn compare_exchange(
88 &self,
89 current: bool,
90 new: bool,
91 success: Ordering,
92 failure: Ordering,
93 ) -> Result<bool, bool> {
94 self.fetch_update(success, failure, |val| (val == current).then_some(new))
95 }
96
97 pub fn compare_exchange_weak(
106 &self,
107 current: bool,
108 new: bool,
109 success: Ordering,
110 failure: Ordering,
111 ) -> Result<bool, bool> {
112 self.compare_exchange(current, new, success, failure)
113 }
114
115 pub fn fetch_and(&self, val: bool, order: Ordering) -> bool {
117 self.fetch_update(order, order, |old| Some(old & val)).unwrap()
118 }
119
120 pub fn fetch_nand(&self, val: bool, order: Ordering) -> bool {
122 self.fetch_update(order, order, |old| Some(!(old & val))).unwrap()
123 }
124
125 pub fn fetch_or(&self, val: bool, order: Ordering) -> bool {
127 self.fetch_update(order, order, |old| Some(old | val)).unwrap()
128 }
129
130 pub fn fetch_xor(&self, val: bool, order: Ordering) -> bool {
132 self.fetch_update(order, order, |old| Some(old ^ val)).unwrap()
133 }
134
135 pub unsafe fn raw_load(&self) -> bool {
143 self.inner.raw_load()
144 }
145
146 #[cfg(test)]
147 pub(crate) fn signature(&self) -> ResourceSignature {
148 self.inner.signature()
149 }
150}