use alloc::boxed::Box;
use alloc::vec::Vec;
use crate::propagator::Erased;
use crate::{Domain, Propagator, Var};
pub struct Model<D> {
initial: Vec<D>,
propagators: Vec<Box<dyn Erased<D>>>,
watchers: Vec<Vec<usize>>,
}
impl<D: Domain> Model<D> {
#[must_use]
pub const fn new() -> Self {
Self {
initial: Vec::new(),
propagators: Vec::new(),
watchers: Vec::new(),
}
}
pub fn add_var(&mut self, domain: D) -> Var {
assert!(!domain.is_empty(), "a variable needs at least one value");
let var =
Var::new(u32::try_from(self.initial.len()).expect("fewer than u32::MAX variables"));
self.initial.push(domain);
self.watchers.push(Vec::new());
var
}
pub fn add_vars(&mut self, count: usize, domain: D) -> Vec<Var> {
(0..count).map(|_| self.add_var(domain)).collect()
}
pub fn add(&mut self, propagator: impl Propagator<D> + 'static) -> &mut Self {
let index = self.propagators.len();
for var in Propagator::scope(&propagator) {
let watchers = self
.watchers
.get_mut(var.index())
.expect("the propagator's scope only holds variables of this model");
if watchers.last() != Some(&index) {
watchers.push(index);
}
}
self.propagators.push(Box::new(propagator));
self
}
#[must_use]
pub fn num_vars(&self) -> usize {
self.initial.len()
}
#[must_use]
pub fn initial_domains(&self) -> &[D] {
&self.initial
}
#[must_use]
pub fn num_propagators(&self) -> usize {
self.propagators.len()
}
pub(crate) fn erased(&self) -> &[Box<dyn Erased<D>>] {
&self.propagators
}
pub(crate) fn watchers(&self, var: Var) -> &[usize] {
&self.watchers[var.index()]
}
}
impl<D: Domain> Default for Model<D> {
fn default() -> Self {
Self::new()
}
}
const _: () = {
const fn shareable<T: Send + Sync>() {}
shareable::<Model<u64>>();
};
#[cfg(test)]
mod tests {
use alloc::vec::Vec;
use super::Model;
use crate::{Domains, Inconsistent, Propagator, Var};
struct Twice([Var; 2]);
impl Propagator<u16> for Twice {
type Scratch = ();
fn scope(&self) -> &[Var] {
&self.0
}
fn propagate(&self, _: &mut Domains<u16>, (): &mut ()) -> Result<(), Inconsistent> {
Ok(())
}
}
#[test]
fn repeated_scope_var_is_watched_once() {
let mut model = Model::<u16>::default();
let x = model.add_var(0b11);
model.add(Twice([x, x]));
assert_eq!(model.watchers(x), [0]);
assert_eq!(model.num_vars(), 1);
assert_eq!(model.num_propagators(), 1);
assert_eq!(
Twice([x, x]).propagate(&mut Domains::new(), &mut ()),
Ok(())
);
}
#[test]
#[should_panic(expected = "only holds variables of this model")]
fn foreign_var_panics() {
let mut model = Model::<u16>::new();
let vars: Vec<Var> = model.add_vars(1, 0b1);
model.add(Twice([vars[0], Var::new(5)]));
}
}