Skip to main content

constraint_search/
store.rs

1//! The variable store: [`Domains`] with a trail, so that search can undo changes on backtrack.
2
3use alloc::vec::Vec;
4use core::fmt;
5use core::ops::Index;
6
7use crate::Domain;
8
9/// A variable: a dense index into [`Domains`] and [`Model`](crate::Model).
10///
11/// Variables are numbered from zero in the order they were added, so a caller can keep its
12/// own layout (cell `i` of a grid is `Var::new(i)`).
13#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub struct Var(
15    /// The position in the store.
16    u32,
17);
18
19impl Var {
20    /// The variable with the given index.
21    #[must_use]
22    pub const fn new(index: u32) -> Self {
23        Self(index)
24    }
25
26    /// The position of the variable in the store.
27    #[must_use]
28    pub const fn index(self) -> usize {
29        self.0 as usize
30    }
31}
32
33/// A constraint cannot be satisfied any more: some domain would become empty.
34#[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/// The current domain of every variable, with a trail of earlier domains.
46///
47/// Every change records the domain it replaced. [`Domains::push_level`] marks the trail and
48/// [`Domains::pop_level`] restores every domain changed since the mark, which is how search
49/// backtracks. Domains never become empty: a change that would empty one fails with
50/// [`Inconsistent`] and leaves the domain as it was.
51///
52/// # Examples
53///
54/// ```
55/// use constraint_search::{Domains, Var};
56///
57/// let mut domains = Domains::<u16>::new();
58/// let x = domains.add(0b111);
59///
60/// domains.push_level();
61/// domains.assign(x, 2)?;
62/// assert_eq!(domains.value(x), Some(2));
63///
64/// domains.pop_level();
65/// assert_eq!(domains[x], 0b111);
66/// # Ok::<(), constraint_search::Inconsistent>(())
67/// ```
68#[derive(Debug, Clone)]
69pub struct Domains<D> {
70    /// The current domain of each variable, indexed by [`Var::index`]. Never empty.
71    current: Vec<D>,
72    /// The domains replaced by changes, oldest first.
73    trail: Vec<(Var, D)>,
74    /// The trail length at each [`Domains::push_level`], innermost last.
75    levels: Vec<usize>,
76    /// Variables changed since propagation last looked, each listed once.
77    modified: Vec<Var>,
78    /// `pending[i]` is `true` while variable `i` is in [`Domains::modified`].
79    pending: Vec<bool>,
80}
81
82impl<D: Domain> Domains<D> {
83    /// An empty store.
84    #[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    /// Adds a variable with the given initial domain.
96    ///
97    /// # Panics
98    ///
99    /// Panics if `domain` is empty or if the store already holds `u32::MAX` variables.
100    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    /// Replaces the contents with `initial`, keeping the allocations for reuse.
111    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    /// The number of variables.
122    #[must_use]
123    pub fn len(&self) -> usize {
124        self.current.len()
125    }
126
127    /// Returns `true` if the store holds no variable.
128    #[must_use]
129    pub fn is_empty(&self) -> bool {
130        self.current.is_empty()
131    }
132
133    /// All variables, in index order.
134    ///
135    /// # Panics
136    ///
137    /// Never: [`Domains::add`] keeps the count below `u32::MAX`.
138    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    /// The only value left for `var`, if its domain holds exactly one.
143    #[must_use]
144    pub fn value(&self, var: Var) -> Option<u32> {
145        self[var].value()
146    }
147
148    /// The values that at least one of `vars` can still take.
149    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    /// Returns `true` if every variable has exactly one value left.
155    #[must_use]
156    pub fn is_solved(&self) -> bool {
157        self.current.iter().all(|domain| domain.len() == 1)
158    }
159
160    /// The value of every variable in index order, if every domain holds exactly one.
161    #[must_use]
162    pub fn solution(&self) -> Option<Vec<u32>> {
163        self.current.iter().map(Domain::value).collect()
164    }
165
166    /// Restricts `var` to the values in `allowed`; returns `true` if its domain shrank.
167    ///
168    /// # Errors
169    ///
170    /// Returns [`Inconsistent`] if no value of the domain is in `allowed`. The domain is then
171    /// left unchanged.
172    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    /// Fixes `var` to `value`; returns `true` if its domain shrank.
188    ///
189    /// # Errors
190    ///
191    /// Returns [`Inconsistent`] if `value` is not in the domain of `var`.
192    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    /// Removes `value` from `var`; returns `true` if the value was there.
201    ///
202    /// # Errors
203    ///
204    /// Returns [`Inconsistent`] if `value` is the last value of `var`.
205    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    /// Removes every value in `values` from `var`; returns `true` if its domain shrank.
213    ///
214    /// # Errors
215    ///
216    /// Returns [`Inconsistent`] if that would leave `var` without a value.
217    pub fn remove_all(&mut self, var: Var, values: D) -> Result<bool, Inconsistent> {
218        self.restrict(var, self[var].difference(values))
219    }
220
221    /// Marks the trail, so that [`Domains::pop_level`] can return to the current domains.
222    pub fn push_level(&mut self) {
223        self.levels.push(self.trail.len());
224    }
225
226    /// Restores every domain changed since the matching [`Domains::push_level`].
227    ///
228    /// # Panics
229    ///
230    /// Panics if no level was pushed.
231    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    /// The number of levels pushed and not yet popped.
239    #[must_use]
240    pub fn level(&self) -> usize {
241        self.levels.len()
242    }
243
244    /// The current trail length, to compare with [`Domains::removed_since`] later.
245    pub(crate) fn trail_len(&self) -> usize {
246        self.trail.len()
247    }
248
249    /// The values removed from each variable since the trail had length `mark`, in the order
250    /// the variables were first changed.
251    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    /// Hands the variables changed since the last call to `wake`, and forgets them.
263    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    /// Sets `var` from `old` to `new`, recording the change on the trail.
271    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/// Unit tests for [`Domains`].
297#[cfg(test)]
298mod tests {
299    use alloc::vec;
300
301    use super::{Domains, Inconsistent, Var};
302
303    /// A store with two variables over `{0, 1, 2}`.
304    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    /// Nested levels undo exactly their own changes.
313    #[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    /// Emptying a domain fails and leaves it, and the trail, untouched.
330    #[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    /// The removal log nets out repeated changes to one variable.
341    #[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    /// Each changed variable is reported once until drained.
355    #[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    /// Sizes, levels and the error message.
370    #[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}