atomic_state/flag/
flag.rs1use crate::prelude::*;
2
3#[derive(Clone)]
5pub struct AtomicFlag {
6 state: Arc<AtomicBool>,
7 notify: Arc<Notify>,
8}
9
10impl AtomicFlag {
11 pub fn new(initial: bool) -> Self {
13 AtomicFlag {
14 state: Arc::new(AtomicBool::new(initial)),
15 notify: Arc::new(Notify::new()),
16 }
17 }
18
19 pub fn is_true(&self) -> bool {
21 self.get()
22 }
23
24 pub fn is_false(&self) -> bool {
26 !self.get()
27 }
28
29 pub fn get(&self) -> bool {
31 self.state.load(Ordering::SeqCst)
32 }
33
34 pub fn set(&self, value: bool) {
36 self.state.store(value, Ordering::SeqCst);
37 self.notify.notify_waiters();
38 }
39
40 pub async fn wait(&self, value: bool) {
42 loop {
43 if self.get() == value {
44 break;
45 }
46
47 self.notify.notified().await;
48 }
49 }
50
51 pub async fn swap(&self, value: bool) {
53 self.wait(!value).await;
54 self.set(value);
55 }
56}
57
58impl ::std::fmt::Debug for AtomicFlag {
59 fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
60 write!(f, "{:?}", &self.get())
61 }
62}
63
64impl ::std::fmt::Display for AtomicFlag {
65 fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
66 write!(f, "{}", &self.get())
67 }
68}
69
70impl ::std::cmp::Eq for AtomicFlag {}
71
72impl ::std::cmp::PartialEq for AtomicFlag {
73 fn eq(&self, other: &Self) -> bool {
74 self.get() == other.get()
75 }
76}
77
78impl ::std::cmp::PartialEq<bool> for AtomicFlag {
79 fn eq(&self, other: &bool) -> bool {
80 &self.get() == other
81 }
82}
83
84impl ::std::convert::From<bool> for AtomicFlag {
85 fn from(value: bool) -> Self {
86 Self::new(value)
87 }
88}
89
90impl ::std::convert::Into<bool> for AtomicFlag {
91 fn into(self) -> bool {
92 self.get()
93 }
94}