facet_reflect/wip/
iset.rs

1use facet_core::Field;
2
3/// Keeps track of which fields were initialized, up to 64 fields
4#[derive(Clone, Copy, Default, Debug)]
5pub struct ISet {
6    flags: u64,
7}
8
9impl ISet {
10    /// The maximum index that can be tracked.
11    pub const MAX_INDEX: usize = 63;
12
13    /// Creates a new ISet with all (given) fields set.
14    pub fn all(fields: &[Field]) -> Self {
15        let mut iset = ISet::default();
16        for (i, _field) in fields.iter().enumerate() {
17            iset.set(i);
18        }
19        iset
20    }
21
22    /// Sets the bit at the given index.
23    pub fn set(&mut self, index: usize) {
24        if index >= 64 {
25            panic!("ISet can only track up to 64 fields. Index {index} is out of bounds.");
26        }
27        self.flags |= 1 << index;
28    }
29
30    /// Unsets the bit at the given index.
31    pub fn unset(&mut self, index: usize) {
32        if index >= 64 {
33            panic!("ISet can only track up to 64 fields. Index {index} is out of bounds.");
34        }
35        self.flags &= !(1 << index);
36    }
37
38    /// Checks if the bit at the given index is set.
39    pub fn has(&self, index: usize) -> bool {
40        if index >= 64 {
41            panic!("ISet can only track up to 64 fields. Index {index} is out of bounds.");
42        }
43        (self.flags & (1 << index)) != 0
44    }
45
46    /// Checks if all bits up to the given count are set.
47    pub fn are_all_set(&self, count: usize) -> bool {
48        if count > 64 {
49            panic!("ISet can only track up to 64 fields. Count {count} is out of bounds.");
50        }
51        let mask = (1 << count) - 1;
52        self.flags & mask == mask
53    }
54
55    /// Checks if any bit in the ISet is set.
56    pub fn is_any_set(&self) -> bool {
57        self.flags != 0
58    }
59
60    /// Clears all bits in the ISet.
61    pub fn clear(&mut self) {
62        self.flags = 0;
63    }
64}