1use alloc::vec::Vec;
4use core::fmt;
5use core::ops::Index;
6
7use crate::Domain;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub struct Var(
15 u32,
17);
18
19impl Var {
20 #[must_use]
22 pub const fn new(index: u32) -> Self {
23 Self(index)
24 }
25
26 #[must_use]
28 pub const fn index(self) -> usize {
29 self.0 as usize
30 }
31}
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
35pub struct Inconsistent;
36
37impl fmt::Display for Inconsistent {
38 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39 f.write_str("the constraints cannot be satisfied")
40 }
41}
42
43impl core::error::Error for Inconsistent {}
44
45#[derive(Debug, Clone)]
69pub struct Domains<D> {
70 current: Vec<D>,
72 trail: Vec<(Var, D)>,
74 levels: Vec<usize>,
76 modified: Vec<Var>,
78 pending: Vec<bool>,
80}
81
82impl<D: Domain> Domains<D> {
83 #[must_use]
85 pub const fn new() -> Self {
86 Self {
87 current: Vec::new(),
88 trail: Vec::new(),
89 levels: Vec::new(),
90 modified: Vec::new(),
91 pending: Vec::new(),
92 }
93 }
94
95 pub fn add(&mut self, domain: D) -> Var {
101 assert!(!domain.is_empty(), "a variable needs at least one value");
102
103 let var = Var(u32::try_from(self.current.len()).expect("fewer than u32::MAX variables"));
104 self.current.push(domain);
105 self.pending.push(false);
106
107 var
108 }
109
110 pub(crate) fn reset_to(&mut self, initial: &[D]) {
112 self.current.clear();
113 self.current.extend_from_slice(initial);
114 self.trail.clear();
115 self.levels.clear();
116 self.modified.clear();
117 self.pending.clear();
118 self.pending.resize(initial.len(), false);
119 }
120
121 #[must_use]
123 pub fn len(&self) -> usize {
124 self.current.len()
125 }
126
127 #[must_use]
129 pub fn is_empty(&self) -> bool {
130 self.current.is_empty()
131 }
132
133 pub fn vars(&self) -> impl ExactSizeIterator<Item = Var> + use<D> {
139 (0..u32::try_from(self.current.len()).expect("fewer than u32::MAX variables")).map(Var)
140 }
141
142 #[must_use]
144 pub fn value(&self, var: Var) -> Option<u32> {
145 self[var].value()
146 }
147
148 pub(crate) fn union_of(&self, vars: &[Var]) -> D {
150 vars.iter()
151 .fold(D::empty(), |union, &var| union.union(self[var]))
152 }
153
154 #[must_use]
156 pub fn is_solved(&self) -> bool {
157 self.current.iter().all(|domain| domain.len() == 1)
158 }
159
160 #[must_use]
162 pub fn solution(&self) -> Option<Vec<u32>> {
163 self.current.iter().map(Domain::value).collect()
164 }
165
166 pub fn restrict(&mut self, var: Var, allowed: D) -> Result<bool, Inconsistent> {
173 let current = self[var];
174 let narrowed = current.intersection(allowed);
175 if narrowed == current {
176 return Ok(false);
177 }
178
179 if narrowed.is_empty() {
180 return Err(Inconsistent);
181 }
182
183 self.replace(var, current, narrowed);
184 Ok(true)
185 }
186
187 pub fn assign(&mut self, var: Var, value: u32) -> Result<bool, Inconsistent> {
193 if !self[var].contains(value) {
194 return Err(Inconsistent);
195 }
196
197 self.restrict(var, D::singleton(value))
198 }
199
200 pub fn remove(&mut self, var: Var, value: u32) -> Result<bool, Inconsistent> {
206 let mut allowed = self[var];
207 allowed.remove(value);
208
209 self.restrict(var, allowed)
210 }
211
212 pub fn remove_all(&mut self, var: Var, values: D) -> Result<bool, Inconsistent> {
218 self.restrict(var, self[var].difference(values))
219 }
220
221 pub fn push_level(&mut self) {
223 self.levels.push(self.trail.len());
224 }
225
226 pub fn pop_level(&mut self) {
232 let mark = self.levels.pop().expect("pop_level without push_level");
233 for (var, domain) in self.trail.drain(mark..).rev() {
234 self.current[var.index()] = domain;
235 }
236 }
237
238 #[must_use]
240 pub fn level(&self) -> usize {
241 self.levels.len()
242 }
243
244 pub(crate) fn trail_len(&self) -> usize {
246 self.trail.len()
247 }
248
249 pub(crate) fn removed_since(&self, mark: usize) -> Vec<(Var, D)> {
252 let mut removed: Vec<(Var, D)> = Vec::new();
253 for &(var, before) in &self.trail[mark..] {
254 if removed.iter().all(|(seen, _)| *seen != var) {
255 removed.push((var, before.difference(self[var])));
256 }
257 }
258
259 removed
260 }
261
262 pub(crate) fn drain_modified(&mut self, mut wake: impl FnMut(Var)) {
264 for var in self.modified.drain(..) {
265 self.pending[var.index()] = false;
266 wake(var);
267 }
268 }
269
270 fn replace(&mut self, var: Var, old: D, new: D) {
272 self.trail.push((var, old));
273 self.current[var.index()] = new;
274
275 if !self.pending[var.index()] {
276 self.pending[var.index()] = true;
277 self.modified.push(var);
278 }
279 }
280}
281
282impl<D: Domain> Default for Domains<D> {
283 fn default() -> Self {
284 Self::new()
285 }
286}
287
288impl<D> Index<Var> for Domains<D> {
289 type Output = D;
290
291 fn index(&self, var: Var) -> &D {
292 &self.current[var.index()]
293 }
294}
295
296#[cfg(test)]
298mod tests {
299 use alloc::vec;
300
301 use super::{Domains, Inconsistent, Var};
302
303 fn two_vars() -> (Domains<u16>, Var, Var) {
305 let mut domains = Domains::new();
306 let x = domains.add(0b111);
307 let y = domains.add(0b111);
308
309 (domains, x, y)
310 }
311
312 #[test]
314 fn levels_undo_in_order() {
315 let (mut domains, x, y) = two_vars();
316
317 domains.push_level();
318 domains.remove(x, 0).unwrap();
319 domains.push_level();
320 domains.assign(y, 2).unwrap();
321 domains.remove(x, 1).unwrap();
322
323 domains.pop_level();
324 assert_eq!((domains[x], domains[y]), (0b110, 0b111));
325 domains.pop_level();
326 assert_eq!((domains[x], domains[y]), (0b111, 0b111));
327 }
328
329 #[test]
331 fn emptying_fails_without_change() {
332 let (mut domains, x, _) = two_vars();
333
334 assert_eq!(domains.remove_all(x, 0b111), Err(Inconsistent));
335 assert_eq!(domains.assign(x, 7), Err(Inconsistent));
336 assert_eq!(domains[x], 0b111);
337 assert_eq!(domains.trail_len(), 0);
338 }
339
340 #[test]
342 fn removed_since_nets_changes() {
343 let (mut domains, x, y) = two_vars();
344 domains.remove(y, 0).unwrap();
345
346 let mark = domains.trail_len();
347 domains.remove(x, 0).unwrap();
348 domains.remove(y, 1).unwrap();
349 domains.remove(x, 1).unwrap();
350
351 assert_eq!(domains.removed_since(mark), vec![(x, 0b011), (y, 0b010)]);
352 }
353
354 #[test]
356 fn modified_lists_each_var_once() {
357 let (mut domains, x, _) = two_vars();
358 domains.remove(x, 0).unwrap();
359 domains.remove(x, 1).unwrap();
360
361 let mut woken = vec![];
362 domains.drain_modified(|var| woken.push(var));
363 assert_eq!(woken, vec![x]);
364
365 domains.drain_modified(|var| woken.push(var));
366 assert_eq!(woken, vec![x]);
367 }
368
369 #[test]
371 fn accessors() {
372 let mut domains = Domains::<u16>::default();
373 assert!(domains.is_empty());
374
375 domains.add(0b1);
376 domains.push_level();
377 assert_eq!((domains.len(), domains.level()), (1, 1));
378 assert_eq!(
379 alloc::format!("{Inconsistent}"),
380 "the constraints cannot be satisfied"
381 );
382 }
383}