use alloc::vec::Vec;
use core::fmt;
use core::ops::Index;
use crate::Domain;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Var(
u32,
);
impl Var {
#[must_use]
pub const fn new(index: u32) -> Self {
Self(index)
}
#[must_use]
pub const fn index(self) -> usize {
self.0 as usize
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Inconsistent;
impl fmt::Display for Inconsistent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("the constraints cannot be satisfied")
}
}
impl core::error::Error for Inconsistent {}
#[derive(Debug, Clone)]
pub struct Domains<D> {
current: Vec<D>,
trail: Vec<(Var, D)>,
levels: Vec<usize>,
modified: Vec<Var>,
pending: Vec<bool>,
}
impl<D: Domain> Domains<D> {
#[must_use]
pub const fn new() -> Self {
Self {
current: Vec::new(),
trail: Vec::new(),
levels: Vec::new(),
modified: Vec::new(),
pending: Vec::new(),
}
}
pub fn add(&mut self, domain: D) -> Var {
assert!(!domain.is_empty(), "a variable needs at least one value");
let var = Var(u32::try_from(self.current.len()).expect("fewer than u32::MAX variables"));
self.current.push(domain);
self.pending.push(false);
var
}
pub(crate) fn reset_to(&mut self, initial: &[D]) {
self.current.clear();
self.current.extend_from_slice(initial);
self.trail.clear();
self.levels.clear();
self.modified.clear();
self.pending.clear();
self.pending.resize(initial.len(), false);
}
#[must_use]
pub fn len(&self) -> usize {
self.current.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.current.is_empty()
}
pub fn vars(&self) -> impl ExactSizeIterator<Item = Var> + use<D> {
(0..u32::try_from(self.current.len()).expect("fewer than u32::MAX variables")).map(Var)
}
#[must_use]
pub fn value(&self, var: Var) -> Option<u32> {
self[var].value()
}
pub(crate) fn union_of(&self, vars: &[Var]) -> D {
vars.iter()
.fold(D::empty(), |union, &var| union.union(self[var]))
}
#[must_use]
pub fn is_solved(&self) -> bool {
self.current.iter().all(|domain| domain.len() == 1)
}
#[must_use]
pub fn solution(&self) -> Option<Vec<u32>> {
self.current.iter().map(Domain::value).collect()
}
pub fn restrict(&mut self, var: Var, allowed: D) -> Result<bool, Inconsistent> {
let current = self[var];
let narrowed = current.intersection(allowed);
if narrowed == current {
return Ok(false);
}
if narrowed.is_empty() {
return Err(Inconsistent);
}
self.replace(var, current, narrowed);
Ok(true)
}
pub fn assign(&mut self, var: Var, value: u32) -> Result<bool, Inconsistent> {
if !self[var].contains(value) {
return Err(Inconsistent);
}
self.restrict(var, D::singleton(value))
}
pub fn remove(&mut self, var: Var, value: u32) -> Result<bool, Inconsistent> {
let mut allowed = self[var];
allowed.remove(value);
self.restrict(var, allowed)
}
pub fn remove_all(&mut self, var: Var, values: D) -> Result<bool, Inconsistent> {
self.restrict(var, self[var].difference(values))
}
pub fn push_level(&mut self) {
self.levels.push(self.trail.len());
}
pub fn pop_level(&mut self) {
let mark = self.levels.pop().expect("pop_level without push_level");
for (var, domain) in self.trail.drain(mark..).rev() {
self.current[var.index()] = domain;
}
}
#[must_use]
pub fn level(&self) -> usize {
self.levels.len()
}
pub(crate) fn trail_len(&self) -> usize {
self.trail.len()
}
pub(crate) fn removed_since(&self, mark: usize) -> Vec<(Var, D)> {
let mut removed: Vec<(Var, D)> = Vec::new();
for &(var, before) in &self.trail[mark..] {
if removed.iter().all(|(seen, _)| *seen != var) {
removed.push((var, before.difference(self[var])));
}
}
removed
}
pub(crate) fn drain_modified(&mut self, mut wake: impl FnMut(Var)) {
for var in self.modified.drain(..) {
self.pending[var.index()] = false;
wake(var);
}
}
fn replace(&mut self, var: Var, old: D, new: D) {
self.trail.push((var, old));
self.current[var.index()] = new;
if !self.pending[var.index()] {
self.pending[var.index()] = true;
self.modified.push(var);
}
}
}
impl<D: Domain> Default for Domains<D> {
fn default() -> Self {
Self::new()
}
}
impl<D> Index<Var> for Domains<D> {
type Output = D;
fn index(&self, var: Var) -> &D {
&self.current[var.index()]
}
}
#[cfg(test)]
mod tests {
use alloc::vec;
use super::{Domains, Inconsistent, Var};
fn two_vars() -> (Domains<u16>, Var, Var) {
let mut domains = Domains::new();
let x = domains.add(0b111);
let y = domains.add(0b111);
(domains, x, y)
}
#[test]
fn levels_undo_in_order() {
let (mut domains, x, y) = two_vars();
domains.push_level();
domains.remove(x, 0).unwrap();
domains.push_level();
domains.assign(y, 2).unwrap();
domains.remove(x, 1).unwrap();
domains.pop_level();
assert_eq!((domains[x], domains[y]), (0b110, 0b111));
domains.pop_level();
assert_eq!((domains[x], domains[y]), (0b111, 0b111));
}
#[test]
fn emptying_fails_without_change() {
let (mut domains, x, _) = two_vars();
assert_eq!(domains.remove_all(x, 0b111), Err(Inconsistent));
assert_eq!(domains.assign(x, 7), Err(Inconsistent));
assert_eq!(domains[x], 0b111);
assert_eq!(domains.trail_len(), 0);
}
#[test]
fn removed_since_nets_changes() {
let (mut domains, x, y) = two_vars();
domains.remove(y, 0).unwrap();
let mark = domains.trail_len();
domains.remove(x, 0).unwrap();
domains.remove(y, 1).unwrap();
domains.remove(x, 1).unwrap();
assert_eq!(domains.removed_since(mark), vec![(x, 0b011), (y, 0b010)]);
}
#[test]
fn modified_lists_each_var_once() {
let (mut domains, x, _) = two_vars();
domains.remove(x, 0).unwrap();
domains.remove(x, 1).unwrap();
let mut woken = vec![];
domains.drain_modified(|var| woken.push(var));
assert_eq!(woken, vec![x]);
domains.drain_modified(|var| woken.push(var));
assert_eq!(woken, vec![x]);
}
#[test]
fn accessors() {
let mut domains = Domains::<u16>::default();
assert!(domains.is_empty());
domains.add(0b1);
domains.push_level();
assert_eq!((domains.len(), domains.level()), (1, 1));
assert_eq!(
alloc::format!("{Inconsistent}"),
"the constraints cannot be satisfied"
);
}
}