use std::{marker, num::NonZero};
use crate::depot::array;
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Set<I: array::raw::BitIndex<N>, const N: usize> {
bits: u16,
index: marker::PhantomData<fn() -> I>,
}
impl<I: array::raw::BitIndex<N>, const N: usize> Set<I, N> {
pub const EMPTY: Self = {
assert!(N <= u16::BITS as usize);
Self {
bits: 0,
index: marker::PhantomData,
}
};
pub fn insert(&mut self, index: I) {
self.bits |= 1 << index.index();
}
pub fn remove(&mut self, index: I) {
self.bits &= !(1 << index.index());
}
pub fn contains(self, index: I) -> bool {
self.bits & (1 << index.index()) != 0
}
pub const fn union(mut self, other: Self) -> Self {
self.bits |= other.bits;
self
}
pub const fn intersect(mut self, other: Self) -> Self {
self.bits &= other.bits;
self
}
pub const fn without(mut self, other: Self) -> Self {
self.bits &= !other.bits;
self
}
pub const fn complement(mut self) -> Self {
self.bits = !self.bits & ((1_u32 << N) - 1) as u16;
self
}
pub const fn is_empty(self) -> bool {
self.bits == 0
}
pub const fn len(self) -> array::Len<N> {
array::Len(self.bits.count_ones())
}
pub fn first(self) -> Option<I> {
let first = self.bits.lowest_one()?;
let slot = array::Vacancy::<N>(NonZero::<u32>::MIN.saturating_add(first));
Some(array::raw::bit_at(slot))
}
}