atmos/os_lib/web_engine/
fq_owners.rs1extern crate alloc;
18
19use alloc::collections::BTreeMap;
20use alloc::string::String;
21use alloc::vec::Vec;
22
23#[derive(Clone, Copy, PartialEq, Eq, Debug)]
25pub enum State {
26 Pending,
28 InFlight,
30 Done,
32}
33
34struct Entry {
35 owners: u32,
37 state: State,
38}
39
40fn bit(g: u8) -> u32 {
42 if g < 32 { 1u32 << g } else { 1 }
43}
44
45#[derive(Default, Debug, PartialEq, Eq)]
47pub struct Closed {
48 pub dropped: Vec<String>,
50 pub in_flight: usize,
52 pub done: usize,
54}
55
56pub struct OwnerTable {
58 map: BTreeMap<String, Entry>,
59}
60
61impl Default for OwnerTable {
62 fn default() -> Self {
63 Self::new()
64 }
65}
66
67impl OwnerTable {
68 pub const fn new() -> Self {
69 Self { map: BTreeMap::new() }
70 }
71
72 pub fn len(&self) -> usize {
74 self.map.len()
75 }
76
77 pub fn is_empty(&self) -> bool {
78 self.map.is_empty()
79 }
80
81 pub fn request(&mut self, key: &str, g: u8) -> bool {
84 if let Some(e) = self.map.get_mut(key) {
85 e.owners |= bit(g);
86 return false;
87 }
88 self.map.insert(String::from(key), Entry { owners: bit(g), state: State::Pending });
89 true
90 }
91
92 pub fn state(&self, key: &str) -> Option<State> {
94 self.map.get(key).map(|e| e.state)
95 }
96
97 pub fn is_live(&self, key: &str) -> bool {
99 self.map.get(key).is_some_and(|e| e.owners != 0)
100 }
101
102 pub fn start(&mut self, key: &str) {
104 if let Some(e) = self.map.get_mut(key) {
105 e.state = State::InFlight;
106 }
107 }
108
109 pub fn finish(&mut self, key: &str) -> bool {
112 match self.map.get_mut(key) {
113 Some(e) if e.owners != 0 => {
114 e.state = State::Done;
115 true
116 }
117 Some(_) => {
118 self.map.remove(key);
119 false
120 }
121 None => false,
122 }
123 }
124
125 pub fn requeue(&mut self, key: &str) -> bool {
127 match self.map.get_mut(key) {
128 Some(e) if e.owners != 0 => {
129 e.state = State::Pending;
130 true
131 }
132 Some(_) => {
133 self.map.remove(key);
134 false
135 }
136 None => false,
137 }
138 }
139
140 pub fn sole_owner<'a>(&self, keys: impl IntoIterator<Item = &'a str>) -> u8 {
143 let mut union = 0u32;
144 for k in keys {
145 match self.map.get(k) {
146 Some(e) => union |= e.owners,
147 None => return 0,
148 }
149 }
150 if union.count_ones() != 1 || union & 1 != 0 {
151 return 0;
152 }
153 union.trailing_zeros() as u8
154 }
155
156 pub fn close_group(&mut self, g: u8) -> Closed {
158 let mut out = Closed::default();
159 if g == 0 || g >= 32 {
160 return out;
161 }
162 let b = bit(g);
163 let mut gone: Vec<String> = Vec::new();
164 for (k, e) in self.map.iter_mut() {
165 if e.owners & b == 0 {
166 continue;
167 }
168 e.owners &= !b;
169 if e.owners != 0 {
170 continue;
171 }
172 match e.state {
173 State::Pending => {
174 out.dropped.push(k.clone());
175 gone.push(k.clone());
176 }
177 State::InFlight => out.in_flight += 1,
178 State::Done => {
179 out.done += 1;
180 gone.push(k.clone());
181 }
182 }
183 }
184 for k in gone {
185 self.map.remove(&k);
186 }
187 out
188 }
189}