use core::fmt::Debug;
pub trait Domain: Copy + Eq + Debug + Send + Sync + 'static {
const CAPACITY: u32;
#[must_use]
fn empty() -> Self;
#[must_use]
fn range(n: u32) -> Self;
#[must_use]
fn singleton(value: u32) -> Self;
#[must_use]
fn contains(&self, value: u32) -> bool;
fn insert(&mut self, value: u32);
fn remove(&mut self, value: u32);
#[must_use]
fn len(&self) -> u32;
#[must_use]
fn union(self, other: Self) -> Self;
#[must_use]
fn intersection(self, other: Self) -> Self;
#[must_use]
fn difference(self, other: Self) -> Self;
#[must_use]
fn first(&self) -> Option<u32>;
#[must_use]
fn is_empty(&self) -> bool {
*self == Self::empty()
}
#[must_use]
fn is_subset(&self, other: Self) -> bool {
self.difference(other).is_empty()
}
#[must_use]
fn value(&self) -> Option<u32> {
if self.len() == 1 { self.first() } else { None }
}
#[must_use]
fn values(&self) -> Values<Self> {
Values(*self)
}
}
#[derive(Debug, Clone)]
pub struct Values<D>(
D,
);
impl<D: Domain> Iterator for Values<D> {
type Item = u32;
fn next(&mut self) -> Option<u32> {
let value = self.0.first()?;
self.0.remove(value);
Some(value)
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.0.len() as usize;
(len, Some(len))
}
}
impl<D: Domain> ExactSizeIterator for Values<D> {}
macro_rules! primitive_domain {
($($bits:ty),*) => {$(
impl Domain for $bits {
const CAPACITY: u32 = <$bits>::BITS;
fn empty() -> Self {
0
}
fn range(n: u32) -> Self {
assert!(n <= Self::CAPACITY, "{n} values exceed the domain capacity");
if n == Self::CAPACITY { <$bits>::MAX } else { (1 << n) - 1 }
}
fn singleton(value: u32) -> Self {
assert!(value < Self::CAPACITY, "value {value} exceeds the domain capacity");
1 << value
}
fn contains(&self, value: u32) -> bool {
value < Self::CAPACITY && (self >> value) & 1 == 1
}
fn insert(&mut self, value: u32) {
*self |= Self::singleton(value);
}
fn remove(&mut self, value: u32) {
if value < Self::CAPACITY {
*self &= !(1 << value);
}
}
fn len(&self) -> u32 {
self.count_ones()
}
fn union(self, other: Self) -> Self {
self | other
}
fn intersection(self, other: Self) -> Self {
self & other
}
fn difference(self, other: Self) -> Self {
self & !other
}
fn first(&self) -> Option<u32> {
(*self != 0).then(|| self.trailing_zeros())
}
}
)*};
}
primitive_domain!(u16, u32, u64, u128);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct BitSet<const W: usize>(
[u64; W],
);
impl<const W: usize> BitSet<W> {
fn locate(value: u32) -> (usize, u64) {
(value as usize / 64, 1 << (value % 64))
}
fn zip(self, other: Self, op: impl Fn(u64, u64) -> u64) -> Self {
let mut words = self.0;
for (word, other) in words.iter_mut().zip(other.0) {
*word = op(*word, other);
}
Self(words)
}
}
impl<const W: usize> Domain for BitSet<W> {
#[expect(
clippy::cast_possible_truncation,
reason = "a domain beyond u32::MAX values would not fit in memory as a bitset"
)]
const CAPACITY: u32 = (W * 64) as u32;
fn empty() -> Self {
Self([0; W])
}
fn range(n: u32) -> Self {
assert!(n <= Self::CAPACITY, "{n} values exceed the domain capacity");
let mut words = [0; W];
let (full, rest) = (n as usize / 64, n % 64);
words[..full].fill(u64::MAX);
if rest > 0 {
words[full] = (1 << rest) - 1;
}
Self(words)
}
fn singleton(value: u32) -> Self {
let mut domain = Self::empty();
domain.insert(value);
domain
}
fn contains(&self, value: u32) -> bool {
if value >= Self::CAPACITY {
return false;
}
let (word, mask) = Self::locate(value);
self.0[word] & mask != 0
}
fn insert(&mut self, value: u32) {
assert!(
value < Self::CAPACITY,
"value {value} exceeds the domain capacity"
);
let (word, mask) = Self::locate(value);
self.0[word] |= mask;
}
fn remove(&mut self, value: u32) {
if value < Self::CAPACITY {
let (word, mask) = Self::locate(value);
self.0[word] &= !mask;
}
}
fn len(&self) -> u32 {
self.0.iter().map(|word| word.count_ones()).sum()
}
fn union(self, other: Self) -> Self {
self.zip(other, |a, b| a | b)
}
fn intersection(self, other: Self) -> Self {
self.zip(other, |a, b| a & b)
}
fn difference(self, other: Self) -> Self {
self.zip(other, |a, b| a & !b)
}
fn first(&self) -> Option<u32> {
let (index, word) = self.0.iter().enumerate().find(|(_, word)| **word != 0)?;
let base = u32::try_from(index * 64).expect("the capacity fits in u32");
Some(base + word.trailing_zeros())
}
}
#[cfg(test)]
mod tests {
use super::{BitSet, Domain};
fn check_set_algebra<D: Domain>() {
let low = D::range(10);
let mut odd = D::empty();
for value in (1..64).step_by(2) {
odd.insert(value);
}
assert_eq!(low.len(), 10);
assert_eq!(low.intersection(odd).len(), 5);
assert_eq!(low.union(odd).len(), 37);
assert!(low.difference(odd).values().eq([0, 2, 4, 6, 8]));
assert!(D::singleton(63).is_subset(odd));
assert_eq!(D::singleton(63).value(), Some(63));
assert_eq!(low.value(), None);
assert!(D::empty().is_empty());
assert_eq!(D::empty().first(), None);
assert!(!low.contains(D::CAPACITY));
}
#[test]
fn set_algebra() {
check_set_algebra::<u64>();
check_set_algebra::<u128>();
check_set_algebra::<BitSet<2>>();
}
#[test]
fn full_range() {
assert_eq!(u16::range(16), u16::MAX);
assert_eq!(BitSet::<2>::range(128).len(), 128);
assert_eq!(BitSet::<2>::range(70).len(), 70);
}
#[test]
fn remove_out_of_range_is_noop() {
let mut domain = u16::range(3);
domain.remove(40);
assert_eq!(domain, 0b111);
let mut wide = BitSet::<1>::range(3);
wide.remove(64);
assert_eq!(wide.len(), 3);
}
#[test]
#[should_panic(expected = "exceeds the domain capacity")]
fn insert_out_of_range_panics() {
let mut domain = 0_u16;
domain.insert(16);
}
}