fedimint_hbbft/binary_agreement/
bool_set.rs1use rand_derive::Rand;
4use serde::{Deserialize, Serialize};
5
6pub const NONE: BoolSet = BoolSet(0b00);
8
9pub const FALSE: BoolSet = BoolSet(0b01);
11
12pub const TRUE: BoolSet = BoolSet(0b10);
14
15pub const BOTH: BoolSet = BoolSet(0b11);
17
18#[derive(
20 Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Rand, Default,
21)]
22pub struct BoolSet(u8);
23
24impl BoolSet {
25 pub fn insert(&mut self, b: bool) -> bool {
28 let prev = *self;
29 self.0 |= Self::from(b).0;
30 prev != *self
31 }
32
33 pub fn remove(&mut self, b: bool) {
35 self.0 &= Self::from(!b).0;
36 }
37
38 pub fn contains(self, b: bool) -> bool {
40 self.0 & Self::from(b).0 != 0
41 }
42
43 pub fn is_subset(self, other: BoolSet) -> bool {
45 self.0 & other.0 == self.0
46 }
47
48 pub fn definite(self) -> Option<bool> {
50 match self {
51 FALSE => Some(false),
52 TRUE => Some(true),
53 _ => None,
54 }
55 }
56}
57
58impl From<bool> for BoolSet {
59 fn from(b: bool) -> Self {
60 if b {
61 TRUE
62 } else {
63 FALSE
64 }
65 }
66}
67
68#[derive(Clone, Copy, Debug)]
70pub struct BoolSetIter(BoolSet);
71
72impl Iterator for BoolSetIter {
73 type Item = bool;
74
75 fn next(&mut self) -> Option<bool> {
76 if self.0.contains(true) {
77 self.0.remove(true);
78 Some(true)
79 } else if self.0.contains(false) {
80 self.0.remove(false);
81 Some(false)
82 } else {
83 None
84 }
85 }
86}
87
88impl IntoIterator for BoolSet {
89 type Item = bool;
90 type IntoIter = BoolSetIter;
91
92 fn into_iter(self) -> Self::IntoIter {
93 BoolSetIter(self)
94 }
95}