constraint_search/
domain.rs1use core::fmt::Debug;
9
10pub trait Domain: Copy + Eq + Debug + Send + Sync + 'static {
27 const CAPACITY: u32;
29
30 #[must_use]
32 fn empty() -> Self;
33
34 #[must_use]
40 fn range(n: u32) -> Self;
41
42 #[must_use]
48 fn singleton(value: u32) -> Self;
49
50 #[must_use]
52 fn contains(&self, value: u32) -> bool;
53
54 fn insert(&mut self, value: u32);
60
61 fn remove(&mut self, value: u32);
63
64 #[must_use]
66 fn len(&self) -> u32;
67
68 #[must_use]
70 fn union(self, other: Self) -> Self;
71
72 #[must_use]
74 fn intersection(self, other: Self) -> Self;
75
76 #[must_use]
78 fn difference(self, other: Self) -> Self;
79
80 #[must_use]
82 fn first(&self) -> Option<u32>;
83
84 #[must_use]
86 fn is_empty(&self) -> bool {
87 *self == Self::empty()
88 }
89
90 #[must_use]
92 fn is_subset(&self, other: Self) -> bool {
93 self.difference(other).is_empty()
94 }
95
96 #[must_use]
98 fn value(&self) -> Option<u32> {
99 if self.len() == 1 { self.first() } else { None }
100 }
101
102 #[must_use]
104 fn values(&self) -> Values<Self> {
105 Values(*self)
106 }
107}
108
109#[derive(Debug, Clone)]
111pub struct Values<D>(
112 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
134macro_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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
206pub struct BitSet<const W: usize>(
207 [u64; W],
209);
210
211impl<const W: usize> BitSet<W> {
212 fn locate(value: u32) -> (usize, u64) {
214 (value as usize / 64, 1 << (value % 64))
215 }
216
217 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#[cfg(test)]
311mod tests {
312 use super::{BitSet, Domain};
313
314 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 #[test]
336 fn set_algebra() {
337 check_set_algebra::<u64>();
338 check_set_algebra::<u128>();
339 check_set_algebra::<BitSet<2>>();
340 }
341
342 #[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 #[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 #[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}