yansi/
set.rs

1use core::fmt;
2use core::marker::PhantomData;
3
4pub struct Set<T>(PhantomData<T>, pub(crate) u16);
5
6pub trait SetMember: Copy + fmt::Debug {
7    const MAX_VALUE: u8;
8
9    fn bit_mask(self) -> u16;
10    fn from_bit_mask(value: u16) -> Option<Self>;
11}
12
13impl<T: SetMember> Set<T> {
14    pub const EMPTY: Self = Set(PhantomData, 0);
15
16    pub fn contains(self, value: T) -> bool {
17        (value.bit_mask() & self.1) == value.bit_mask()
18    }
19
20    pub const fn iter(self) -> Iter<T> {
21        Iter { index: 0, set: self }
22    }
23}
24
25pub struct Iter<T> {
26    index: u8,
27    set: Set<T>,
28}
29
30impl<T: SetMember> Iterator for Iter<T> {
31    type Item = T;
32
33    fn next(&mut self) -> Option<Self::Item> {
34        while self.index <= T::MAX_VALUE {
35            let mask: u16 = 1 << self.index;
36
37            self.index += 1;
38            if let Some(v) = T::from_bit_mask(mask) {
39                if self.set.contains(v) {
40                    return Some(v);
41                }
42            }
43        }
44
45        None
46    }
47}
48
49impl<T: SetMember> Default for Set<T> {
50    fn default() -> Self {
51        Set::EMPTY
52    }
53}
54
55impl<T: SetMember> fmt::Debug for Set<T> {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        f.debug_set().entries(self.iter()).finish()
58    }
59}
60
61impl<T> Copy for Set<T> { }
62
63impl<T> Clone for Set<T> {
64    fn clone(&self) -> Self {
65        Self(self.0, self.1)
66    }
67}
68
69impl<T> PartialEq for Set<T> {
70    fn eq(&self, other: &Self) -> bool {
71        self.1 == other.1
72    }
73}
74
75impl<T> Eq for Set<T> { }
76
77impl<T> PartialOrd for Set<T> {
78    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
79        self.1.partial_cmp(&other.1)
80    }
81}
82
83impl<T> Ord for Set<T> {
84    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
85        self.1.cmp(&other.1)
86    }
87}
88
89impl<T> core::hash::Hash for Set<T> {
90    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
91        self.1.hash(state);
92    }
93}