Skip to main content

constraint_search/
domain.rs

1//! The [`Domain`] trait: the set of values a variable may still take, as a bitset.
2//!
3//! Values are small non-negative integers `0..CAPACITY`. The unsigned primitives `u16`, `u32`,
4//! `u64` and `u128` are domains of their bit width, and [`BitSet`] covers wider domains in
5//! multiples of 64 values. Pick the smallest type that holds every value: a 9×9 Sudoku fits a
6//! `u16`, a 25×25 one a `u32`.
7
8use core::fmt::Debug;
9
10/// The set of values a variable may still take, as a bitset over `0..CAPACITY`.
11///
12/// Domains are small plain values (`Copy`, `Send + Sync + 'static`): the store and the trail
13/// copy them by value. All operations are set operations; none of them allocates.
14///
15/// # Examples
16///
17/// ```
18/// use constraint_search::Domain;
19///
20/// let mut digits = u16::range(9);
21/// digits.remove(4);
22/// assert_eq!(digits.len(), 8);
23/// assert_eq!(digits.first(), Some(0));
24/// assert!(digits.values().eq([0, 1, 2, 3, 5, 6, 7, 8]));
25/// ```
26pub trait Domain: Copy + Eq + Debug + Send + Sync + 'static {
27    /// The number of values the domain can hold; every value is below it.
28    const CAPACITY: u32;
29
30    /// The domain without any value.
31    #[must_use]
32    fn empty() -> Self;
33
34    /// The domain of the values `0..n`.
35    ///
36    /// # Panics
37    ///
38    /// Panics if `n` exceeds [`Domain::CAPACITY`].
39    #[must_use]
40    fn range(n: u32) -> Self;
41
42    /// The domain holding only `value`.
43    ///
44    /// # Panics
45    ///
46    /// Panics if `value` is not below [`Domain::CAPACITY`].
47    #[must_use]
48    fn singleton(value: u32) -> Self;
49
50    /// Returns `true` if `value` is in the domain. Values at or above the capacity never are.
51    #[must_use]
52    fn contains(&self, value: u32) -> bool;
53
54    /// Puts `value` into the domain.
55    ///
56    /// # Panics
57    ///
58    /// Panics if `value` is not below [`Domain::CAPACITY`].
59    fn insert(&mut self, value: u32);
60
61    /// Takes `value` out of the domain. Removing an absent value does nothing.
62    fn remove(&mut self, value: u32);
63
64    /// The number of values in the domain.
65    #[must_use]
66    fn len(&self) -> u32;
67
68    /// The values in `self`, in `other` or in both.
69    #[must_use]
70    fn union(self, other: Self) -> Self;
71
72    /// The values in both `self` and `other`.
73    #[must_use]
74    fn intersection(self, other: Self) -> Self;
75
76    /// The values in `self` but not in `other`.
77    #[must_use]
78    fn difference(self, other: Self) -> Self;
79
80    /// The smallest value, or `None` for the empty domain.
81    #[must_use]
82    fn first(&self) -> Option<u32>;
83
84    /// Returns `true` if the domain holds no value.
85    #[must_use]
86    fn is_empty(&self) -> bool {
87        *self == Self::empty()
88    }
89
90    /// Returns `true` if every value of `self` is also in `other`.
91    #[must_use]
92    fn is_subset(&self, other: Self) -> bool {
93        self.difference(other).is_empty()
94    }
95
96    /// The only value, if the domain holds exactly one.
97    #[must_use]
98    fn value(&self) -> Option<u32> {
99        if self.len() == 1 { self.first() } else { None }
100    }
101
102    /// The values in ascending order.
103    #[must_use]
104    fn values(&self) -> Values<Self> {
105        Values(*self)
106    }
107}
108
109/// The values of a domain in ascending order, returned by [`Domain::values`].
110#[derive(Debug, Clone)]
111pub struct Values<D>(
112    /// The values not yet yielded.
113    D,
114);
115
116impl<D: Domain> Iterator for Values<D> {
117    type Item = u32;
118
119    fn next(&mut self) -> Option<u32> {
120        let value = self.0.first()?;
121        self.0.remove(value);
122
123        Some(value)
124    }
125
126    fn size_hint(&self) -> (usize, Option<usize>) {
127        let len = self.0.len() as usize;
128        (len, Some(len))
129    }
130}
131
132impl<D: Domain> ExactSizeIterator for Values<D> {}
133
134/// Implements [`Domain`] for unsigned primitives, one bit per value.
135macro_rules! primitive_domain {
136    ($($bits:ty),*) => {$(
137        impl Domain for $bits {
138            const CAPACITY: u32 = <$bits>::BITS;
139
140            fn empty() -> Self {
141                0
142            }
143
144            fn range(n: u32) -> Self {
145                assert!(n <= Self::CAPACITY, "{n} values exceed the domain capacity");
146                if n == Self::CAPACITY { <$bits>::MAX } else { (1 << n) - 1 }
147            }
148
149            fn singleton(value: u32) -> Self {
150                assert!(value < Self::CAPACITY, "value {value} exceeds the domain capacity");
151                1 << value
152            }
153
154            fn contains(&self, value: u32) -> bool {
155                value < Self::CAPACITY && (self >> value) & 1 == 1
156            }
157
158            fn insert(&mut self, value: u32) {
159                *self |= Self::singleton(value);
160            }
161
162            fn remove(&mut self, value: u32) {
163                if value < Self::CAPACITY {
164                    *self &= !(1 << value);
165                }
166            }
167
168            fn len(&self) -> u32 {
169                self.count_ones()
170            }
171
172            fn union(self, other: Self) -> Self {
173                self | other
174            }
175
176            fn intersection(self, other: Self) -> Self {
177                self & other
178            }
179
180            fn difference(self, other: Self) -> Self {
181                self & !other
182            }
183
184            fn first(&self) -> Option<u32> {
185                (*self != 0).then(|| self.trailing_zeros())
186            }
187        }
188    )*};
189}
190
191primitive_domain!(u16, u32, u64, u128);
192
193/// A domain of `64 * W` values, for variables with more values than a `u128` holds.
194///
195/// # Examples
196///
197/// ```
198/// use constraint_search::{BitSet, Domain};
199///
200/// let mut slots = BitSet::<4>::range(200);
201/// slots.remove(150);
202/// assert_eq!(slots.len(), 199);
203/// assert!(!slots.contains(150));
204/// ```
205#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
206pub struct BitSet<const W: usize>(
207    /// Bit `v % 64` of word `v / 64` is set while the value `v` is in the domain.
208    [u64; W],
209);
210
211impl<const W: usize> BitSet<W> {
212    /// The word index and bit mask of `value`, which must be below the capacity.
213    fn locate(value: u32) -> (usize, u64) {
214        (value as usize / 64, 1 << (value % 64))
215    }
216
217    /// Combines the words of `self` and `other` pairwise with `op`.
218    fn zip(self, other: Self, op: impl Fn(u64, u64) -> u64) -> Self {
219        let mut words = self.0;
220        for (word, other) in words.iter_mut().zip(other.0) {
221            *word = op(*word, other);
222        }
223
224        Self(words)
225    }
226}
227
228impl<const W: usize> Domain for BitSet<W> {
229    #[expect(
230        clippy::cast_possible_truncation,
231        reason = "a domain beyond u32::MAX values would not fit in memory as a bitset"
232    )]
233    const CAPACITY: u32 = (W * 64) as u32;
234
235    fn empty() -> Self {
236        Self([0; W])
237    }
238
239    fn range(n: u32) -> Self {
240        assert!(n <= Self::CAPACITY, "{n} values exceed the domain capacity");
241
242        let mut words = [0; W];
243        let (full, rest) = (n as usize / 64, n % 64);
244        words[..full].fill(u64::MAX);
245        if rest > 0 {
246            words[full] = (1 << rest) - 1;
247        }
248
249        Self(words)
250    }
251
252    fn singleton(value: u32) -> Self {
253        let mut domain = Self::empty();
254        domain.insert(value);
255
256        domain
257    }
258
259    fn contains(&self, value: u32) -> bool {
260        if value >= Self::CAPACITY {
261            return false;
262        }
263
264        let (word, mask) = Self::locate(value);
265        self.0[word] & mask != 0
266    }
267
268    fn insert(&mut self, value: u32) {
269        assert!(
270            value < Self::CAPACITY,
271            "value {value} exceeds the domain capacity"
272        );
273
274        let (word, mask) = Self::locate(value);
275        self.0[word] |= mask;
276    }
277
278    fn remove(&mut self, value: u32) {
279        if value < Self::CAPACITY {
280            let (word, mask) = Self::locate(value);
281            self.0[word] &= !mask;
282        }
283    }
284
285    fn len(&self) -> u32 {
286        self.0.iter().map(|word| word.count_ones()).sum()
287    }
288
289    fn union(self, other: Self) -> Self {
290        self.zip(other, |a, b| a | b)
291    }
292
293    fn intersection(self, other: Self) -> Self {
294        self.zip(other, |a, b| a & b)
295    }
296
297    fn difference(self, other: Self) -> Self {
298        self.zip(other, |a, b| a & !b)
299    }
300
301    fn first(&self) -> Option<u32> {
302        let (index, word) = self.0.iter().enumerate().find(|(_, word)| **word != 0)?;
303        let base = u32::try_from(index * 64).expect("the capacity fits in u32");
304
305        Some(base + word.trailing_zeros())
306    }
307}
308
309/// Unit tests for the primitive domains and [`BitSet`].
310#[cfg(test)]
311mod tests {
312    use super::{BitSet, Domain};
313
314    /// Runs the shared checks on one domain type with at least 64 values.
315    fn check_set_algebra<D: Domain>() {
316        let low = D::range(10);
317        let mut odd = D::empty();
318        for value in (1..64).step_by(2) {
319            odd.insert(value);
320        }
321
322        assert_eq!(low.len(), 10);
323        assert_eq!(low.intersection(odd).len(), 5);
324        assert_eq!(low.union(odd).len(), 37);
325        assert!(low.difference(odd).values().eq([0, 2, 4, 6, 8]));
326        assert!(D::singleton(63).is_subset(odd));
327        assert_eq!(D::singleton(63).value(), Some(63));
328        assert_eq!(low.value(), None);
329        assert!(D::empty().is_empty());
330        assert_eq!(D::empty().first(), None);
331        assert!(!low.contains(D::CAPACITY));
332    }
333
334    /// Every primitive wide enough and a two-word [`BitSet`] obey the same set algebra.
335    #[test]
336    fn set_algebra() {
337        check_set_algebra::<u64>();
338        check_set_algebra::<u128>();
339        check_set_algebra::<BitSet<2>>();
340    }
341
342    /// A full-capacity range sets every bit instead of overflowing the shift.
343    #[test]
344    fn full_range() {
345        assert_eq!(u16::range(16), u16::MAX);
346        assert_eq!(BitSet::<2>::range(128).len(), 128);
347        assert_eq!(BitSet::<2>::range(70).len(), 70);
348    }
349
350    /// Removing a value beyond the capacity is a no-op, matching [`Domain::contains`].
351    #[test]
352    fn remove_out_of_range_is_noop() {
353        let mut domain = u16::range(3);
354        domain.remove(40);
355        assert_eq!(domain, 0b111);
356
357        let mut wide = BitSet::<1>::range(3);
358        wide.remove(64);
359        assert_eq!(wide.len(), 3);
360    }
361
362    /// Inserting a value beyond the capacity panics rather than wrapping the shift.
363    #[test]
364    #[should_panic(expected = "exceeds the domain capacity")]
365    fn insert_out_of_range_panics() {
366        let mut domain = 0_u16;
367        domain.insert(16);
368    }
369}