atomic_state/flag/
flag.rs1use crate::prelude::*;
2
3#[derive(Clone)]
5pub struct Flag {
6 state: Arc<AtomicBool>,
7 notify: Arc<Notify>,
8}
9
10impl Flag {
11 pub fn new(initial: bool) -> Self {
13 Flag {
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::default::Default for Flag {
59 fn default() -> Self {
60 Self::new(false)
61 }
62}
63
64impl ::std::fmt::Debug for Flag {
65 fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
66 write!(f, "{:?}", &self.get())
67 }
68}
69
70impl ::std::fmt::Display for Flag {
71 fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
72 write!(f, "{}", &self.get())
73 }
74}
75
76impl ::std::cmp::Eq for Flag {}
77
78impl ::std::cmp::PartialEq for Flag {
79 fn eq(&self, other: &Self) -> bool {
80 self.get() == other.get()
81 }
82}
83
84impl ::std::cmp::PartialEq<bool> for Flag {
85 fn eq(&self, other: &bool) -> bool {
86 &self.get() == other
87 }
88}
89
90impl ::std::convert::From<bool> for Flag {
91 fn from(value: bool) -> Self {
92 Self::new(value)
93 }
94}
95
96impl ::std::convert::Into<bool> for Flag {
97 fn into(self) -> bool {
98 self.get()
99 }
100}