forma/
small_bit_set.rs

1// Copyright 2022 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use std::mem;
6
7type Container = u32;
8
9#[derive(Clone, Debug, Default)]
10pub struct SmallBitSet {
11    bit_set: Container,
12}
13
14impl SmallBitSet {
15    pub fn clear(&mut self) {
16        self.bit_set = 0;
17    }
18
19    pub const fn contains(&self, val: &u8) -> bool {
20        (self.bit_set >> *val as Container) & 0b1 != 0
21    }
22
23    pub fn insert(&mut self, val: u8) -> bool {
24        if val as usize >= mem::size_of_val(&self.bit_set) * 8 {
25            return false;
26        }
27
28        self.bit_set |= 0b1 << u32::from(val);
29
30        true
31    }
32
33    pub fn remove(&mut self, val: u8) -> bool {
34        if val as usize >= mem::size_of_val(&self.bit_set) * 8 {
35            return false;
36        }
37
38        self.bit_set &= !(0b1 << u32::from(val));
39
40        true
41    }
42
43    pub fn first_empty_slot(&mut self) -> Option<u8> {
44        let slot = self.bit_set.trailing_ones() as u8;
45
46        self.insert(slot).then_some(slot)
47    }
48}