use core::fmt; use core::marker::PhantomData; pub struct Set(PhantomData, pub(crate) u16); pub trait SetMember: Copy + fmt::Debug { const MAX_VALUE: u8; fn bit_mask(self) -> u16; fn from_bit_mask(value: u16) -> Option; } impl Set { pub const EMPTY: Self = Set(PhantomData, 0); pub fn contains(self, value: T) -> bool { (value.bit_mask() & self.1) == value.bit_mask() } pub const fn iter(self) -> Iter { Iter { index: 0, set: self } } } pub struct Iter { index: u8, set: Set, } impl Iterator for Iter { type Item = T; fn next(&mut self) -> Option { while self.index <= T::MAX_VALUE { let mask: u16 = 1 << self.index; self.index += 1; if let Some(v) = T::from_bit_mask(mask) { if self.set.contains(v) { return Some(v); } } } None } } impl Default for Set { fn default() -> Self { Set::EMPTY } } impl fmt::Debug for Set { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_set().entries(self.iter()).finish() } } impl Copy for Set { } impl Clone for Set { fn clone(&self) -> Self { Self(self.0, self.1) } } impl PartialEq for Set { fn eq(&self, other: &Self) -> bool { self.1 == other.1 } } impl Eq for Set { } impl PartialOrd for Set { fn partial_cmp(&self, other: &Self) -> Option { self.1.partial_cmp(&other.1) } } impl Ord for Set { fn cmp(&self, other: &Self) -> core::cmp::Ordering { self.1.cmp(&other.1) } } impl core::hash::Hash for Set { fn hash(&self, state: &mut H) { self.1.hash(state); } }