use crate::error::Error;
use serde::ser::{Serialize, SerializeSeq, Serializer};
use std::collections::BTreeSet;
use std::fmt;
use std::sync::Arc;
#[derive(Clone)]
pub struct Universe(Arc<Atoms>);
#[derive(PartialEq, Eq)]
struct Atoms {
names: Vec<String>,
bitwidth: u32,
ints: Vec<Option<i64>>,
}
pub const DEFAULT_BITWIDTH: u32 = 4;
impl PartialEq for Universe {
fn eq(&self, other: &Universe) -> bool {
Arc::ptr_eq(&self.0, &other.0) || self.0 == other.0
}
}
impl Eq for Universe {}
impl fmt::Debug for Universe {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.0.names.iter()).finish()
}
}
impl Serialize for Universe {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
self.0.names.serialize(s)
}
}
pub(crate) fn capacity(n: usize, k: usize) -> Option<u64> {
let k = u32::try_from(k).ok()?;
(n as u64).checked_pow(k)
}
pub(crate) fn capacity_error(n: usize, k: usize) -> Error {
Error::new(
"universe.capacity",
format!("{n} atoms and arity {k} give more than 2^64 - 1 tuples"),
)
}
impl Universe {
pub fn new<I, S>(atoms: I) -> Result<Universe, Error>
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
let atoms: Vec<String> = atoms.into_iter().map(Into::into).collect();
if atoms.is_empty() {
return Err(Error::new("universe.empty", "the universe has no atoms"));
}
let mut seen = BTreeSet::new();
for a in &atoms {
if !seen.insert(a.as_str()) {
return Err(Error::new(
"universe.duplicate_atom",
format!("the atom `{a}` appears twice"),
));
}
}
let ints = vec![None; atoms.len()];
Ok(Universe(Arc::new(Atoms {
names: atoms,
bitwidth: DEFAULT_BITWIDTH,
ints,
})))
}
pub fn with_ints(&self, bitwidth: u32, ints: &[(&str, i64)]) -> Result<Universe, Error> {
if !(1..=32).contains(&bitwidth) {
return Err(Error::new(
"universe.bitwidth",
format!("a bitwidth of {bitwidth}, outside 1 to 32"),
));
}
let (lo, hi) = (-(1i64 << (bitwidth - 1)), (1i64 << (bitwidth - 1)) - 1);
let mut out = vec![None; self.size()];
let mut seen = BTreeSet::new();
for &(name, value) in ints {
let Some(atom) = self.index_of(name) else {
return Err(Error::new(
"universe.unknown_atom",
format!("no atom named `{name}` in the universe"),
));
};
if !(lo..=hi).contains(&value) {
return Err(Error::new(
"universe.int",
format!(
"the integer {value} of `{name}` is outside {lo} to {hi}, at bitwidth {bitwidth}"
),
));
}
if out[atom].is_some() {
return Err(Error::new(
"universe.int",
format!("the atom `{name}` is given two integers"),
));
}
if !seen.insert(value) {
return Err(Error::new(
"universe.int",
format!("the integer {value} is given to two atoms"),
));
}
out[atom] = Some(value);
}
Ok(Universe(Arc::new(Atoms {
names: self.0.names.clone(),
bitwidth,
ints: out,
})))
}
pub fn bitwidth(&self) -> u32 {
self.0.bitwidth
}
pub fn int_of(&self, index: usize) -> Option<i64> {
self.0.ints.get(index).copied().flatten()
}
pub fn atom_of_int(&self, value: i64) -> Option<usize> {
self.0.ints.iter().position(|&i| i == Some(value))
}
pub fn int_atoms(&self) -> impl Iterator<Item = (usize, i64)> + '_ {
self.0
.ints
.iter()
.enumerate()
.filter_map(|(a, i)| i.map(|v| (a, v)))
}
pub fn wrap(&self, value: i64) -> i64 {
wrap_bits(value, self.0.bitwidth)
}
pub fn size(&self) -> usize {
self.0.names.len()
}
pub fn atom(&self, index: usize) -> Option<&str> {
self.0.names.get(index).map(String::as_str)
}
pub fn index_of(&self, name: &str) -> Option<usize> {
self.0.names.iter().position(|a| a == name)
}
pub fn atoms(&self) -> impl Iterator<Item = &str> {
self.0.names.iter().map(String::as_str)
}
pub fn tuple(&self, names: &[&str]) -> Result<Tuple, Error> {
if names.is_empty() {
return Err(Error::new("arity.zero", "a tuple of no atoms"));
}
let mut atoms = Vec::with_capacity(names.len());
for name in names {
match self.index_of(name) {
Some(i) => atoms.push(i),
None => {
return Err(Error::new(
"universe.unknown_atom",
format!("the universe has no atom `{name}`"),
));
}
}
}
Ok(Tuple {
universe: self.clone(),
atoms,
})
}
pub fn tuple_set(&self, arity: usize, tuples: &[&[&str]]) -> Result<TupleSet, Error> {
let mut set = TupleSet::empty(self, arity)?;
for names in tuples {
set.insert(&self.tuple(names)?)?;
}
Ok(set)
}
pub fn all(&self, arity: usize) -> Result<TupleSet, Error> {
let mut set = TupleSet::empty(self, arity)?;
let cap = capacity(self.size(), arity).expect("checked by TupleSet::empty");
set.indices = (0..cap).collect();
Ok(set)
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct Tuple {
universe: Universe,
atoms: Vec<usize>,
}
impl Tuple {
pub fn atoms(&self) -> &[usize] {
&self.atoms
}
pub fn arity(&self) -> usize {
self.atoms.len()
}
pub fn universe(&self) -> &Universe {
&self.universe
}
pub fn names(&self) -> Vec<&str> {
self.atoms
.iter()
.map(|&a| self.universe.0.names[a].as_str())
.collect()
}
}
impl fmt::Debug for Tuple {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self}")
}
}
impl fmt::Display for Tuple {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let names = self.names();
if names.len() == 1 {
write!(f, "{}", names[0])
} else {
write!(f, "({})", names.join(", "))
}
}
}
pub(crate) fn index_of_atoms(n: usize, atoms: &[usize]) -> u64 {
atoms.iter().fold(0u64, |acc, &a| acc * n as u64 + a as u64)
}
pub(crate) fn atoms_of_index(n: usize, arity: usize, mut index: u64) -> Vec<usize> {
let mut atoms = vec![0; arity];
for slot in atoms.iter_mut().rev() {
*slot = (index % n as u64) as usize;
index /= n as u64;
}
atoms
}
#[derive(Clone, PartialEq, Eq)]
pub struct TupleSet {
universe: Universe,
arity: usize,
pub(crate) indices: BTreeSet<u64>,
}
impl TupleSet {
pub fn empty(universe: &Universe, arity: usize) -> Result<TupleSet, Error> {
if arity == 0 {
return Err(Error::new("arity.zero", "a tuple set of arity 0"));
}
if capacity(universe.size(), arity).is_none() {
return Err(capacity_error(universe.size(), arity));
}
Ok(TupleSet {
universe: universe.clone(),
arity,
indices: BTreeSet::new(),
})
}
pub(crate) fn from_indices(
universe: &Universe,
arity: usize,
indices: BTreeSet<u64>,
) -> TupleSet {
TupleSet {
universe: universe.clone(),
arity,
indices,
}
}
pub fn insert(&mut self, tuple: &Tuple) -> Result<bool, Error> {
if tuple.arity() != self.arity {
return Err(Error::new(
"tuples.arity",
format!(
"a tuple of arity {} given to a tuple set of arity {}",
tuple.arity(),
self.arity
),
));
}
if tuple.universe != self.universe {
return Err(Error::new(
"tuples.other_universe",
"the tuple is over a different universe",
));
}
Ok(self
.indices
.insert(index_of_atoms(self.universe.size(), &tuple.atoms)))
}
pub fn insert_index(&mut self, index: u64) -> Result<bool, Error> {
let cap = capacity(self.universe.size(), self.arity).expect("checked by TupleSet::empty");
if index >= cap {
return Err(Error::new(
"tuples.index",
format!(
"index {index} is past the last of the {cap} tuples of arity {}",
self.arity
),
));
}
Ok(self.indices.insert(index))
}
pub fn contains_index(&self, index: u64) -> bool {
self.indices.contains(&index)
}
pub fn contains(&self, tuple: &Tuple) -> bool {
tuple.universe == self.universe
&& tuple.arity() == self.arity
&& self
.indices
.contains(&index_of_atoms(self.universe.size(), &tuple.atoms))
}
pub fn is_subset(&self, other: &TupleSet) -> bool {
self.arity == other.arity
&& self.universe == other.universe
&& self.indices.is_subset(&other.indices)
}
pub fn arity(&self) -> usize {
self.arity
}
pub fn universe(&self) -> &Universe {
&self.universe
}
pub fn len(&self) -> usize {
self.indices.len()
}
pub fn is_empty(&self) -> bool {
self.indices.is_empty()
}
pub fn iter(&self) -> impl Iterator<Item = Tuple> + '_ {
self.indices.iter().map(|&i| Tuple {
universe: self.universe.clone(),
atoms: atoms_of_index(self.universe.size(), self.arity, i),
})
}
pub fn indices(&self) -> impl Iterator<Item = u64> + '_ {
self.indices.iter().copied()
}
}
impl fmt::Display for TupleSet {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{{")?;
for (i, t) in self.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{t}")?;
}
write!(f, "}}")
}
}
impl fmt::Debug for TupleSet {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self}")
}
}
impl Serialize for TupleSet {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
let mut seq = s.serialize_seq(Some(self.len()))?;
for t in self.iter() {
seq.serialize_element(&t.names())?;
}
seq.end()
}
}
pub(crate) fn wrap_bits(value: i64, bitwidth: u32) -> i64 {
let shift = 64 - bitwidth;
value.wrapping_shl(shift).wrapping_shr(shift)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tuple_atoms_returns_exact_indices() {
let u = Universe::new(["A", "B", "C"]).expect("valid universe");
let t = u.tuple(&["B", "C"]).expect("valid tuple");
assert_eq!(t.atoms(), &[1, 2]);
assert_eq!(t.names(), vec!["B", "C"]);
}
}
#[cfg(kani)]
mod kani_proofs {
use super::*;
#[kani::proof]
fn kani_tuple_index_roundtrip() {
let n: usize = kani::any();
kani::assume(n >= 1 && n <= 8);
let a0: usize = kani::any();
let a1: usize = kani::any();
kani::assume(a0 < n && a1 < n);
let idx = (a0 as u64) * (n as u64) + (a1 as u64);
let decoded = atoms_of_index(n, 2, idx);
assert_eq!(decoded.len(), 2);
assert_eq!(decoded[0], a0);
assert_eq!(decoded[1], a1);
}
}