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