vers3 0.2.0

Explicit-state model checking library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
// SPDX-License-Identifier: Apache-2.0
// Copyright (C) 2026, Marco Elver <me@marcoelver.com>

//! Core data structures for state representation and storage.
//!
//! The key primitive is [`ArraySet`]: a fixed-capacity, array-backed collection
//! with *symmetric hashing*. Its hash is invariant under permutation of elements,
//! enabling symmetry reduction — states that differ only in the labelling of
//! equivalent agents (e.g. which cache node is #0 vs #1) hash to the same bucket.

use std::fmt;
use std::hash::{Hash, Hasher};
use std::ops::{Index, IndexMut};

// --- StateHash ---------------------------------------------------------------

/// Opaque hash of a model state, used as a compact identifier in visited sets
/// and parent maps.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct StateHash(pub u64);

impl fmt::Display for StateHash {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:#018x}", self.0)
    }
}

// --- Hash utilities ----------------------------------------------------------

/// Combine two hash values.
///
/// Use this to build composite hashes from multiple fields.
#[inline]
pub fn combine_hash(seed: u64, value: u64) -> u64 {
    seed ^ value
        .wrapping_add(0x9e3779b97f4a7c15)
        .wrapping_add(seed << 6)
        .wrapping_add(seed >> 2)
}

/// Compute a standalone hash of `value` using a deterministic seed.
///
/// Deterministic across a single run (fixed seeds).
#[inline]
pub fn hash_of<T: Hash>(value: &T) -> u64 {
    ahash::RandomState::with_seeds(0, 0, 0, 0).hash_one(value)
}

// --- ArraySet ----------------------------------------------------------------

/// Fixed-capacity, array-backed collection with *symmetric hashing*.
///
/// Each slot `0..N` is independently occupied or empty. Semantics:
///
/// - **Equality** is permutation-based: two sets are equal iff their occupied
///   values form the same multiset (slot positions are ignored).
/// - **Hash** is symmetric: computed by adding element hashes, invariant under
///   permutation. Together with permutation equality this makes symmetry
///   reduction *sound*: states that differ only in the labelling of equivalent
///   agents are genuinely equal, and an exact search merges them without risking
///   accidental hash-collision merges.
///
/// # Example
///
/// ```
/// use vers3::ArraySet;
///
/// let mut s: ArraySet<u8, 4> = ArraySet::new();
/// s.insert(0, 10);
/// s.insert(2, 30);
/// assert_eq!(s.get(0), Some(&10));
/// assert_eq!(s.get(1), None);
/// assert_eq!(s.len(), 2);
/// ```
#[derive(Clone, Debug)]
pub struct ArraySet<T, const N: usize> {
    data: [Option<T>; N],
    len: usize,
}

impl<T: Clone, const N: usize> ArraySet<T, N> {
    /// Create an empty set with capacity `N`.
    pub fn new() -> Self {
        Self {
            data: std::array::from_fn(|_| None),
            len: 0,
        }
    }
}

impl<T, const N: usize> ArraySet<T, N> {
    /// Create a fully-populated set where slot `i` holds `f(i)`.
    ///
    /// Mirrors [`std::array::from_fn`]: `f` is called once per slot in order.
    /// All `N` slots are occupied; `len() == N`.
    ///
    /// Use this when every slot is meaningful by index, e.g. initialising a
    /// fixed set of named agents:
    ///
    /// ```
    /// use vers3::ArraySet;
    /// let s: ArraySet<u32, 3> = ArraySet::from_fn(|i| i as u32 * 10);
    /// assert_eq!(s[0], 0);
    /// assert_eq!(s[2], 20);
    /// assert_eq!(s.len(), 3);
    /// ```
    pub fn from_fn(mut f: impl FnMut(usize) -> T) -> Self {
        Self {
            data: std::array::from_fn(|i| Some(f(i))),
            len: N,
        }
    }

    /// Insert `value` at `index`, replacing any existing value.
    pub fn insert(&mut self, index: usize, value: T) {
        assert!(index < N, "index {index} out of bounds (capacity {N})");
        if self.data[index].is_none() {
            self.len += 1;
        }
        self.data[index] = Some(value);
    }

    /// Remove the value at `index`. No-op if the slot is empty.
    pub fn remove(&mut self, index: usize) {
        assert!(index < N);
        if self.data[index].take().is_some() {
            self.len -= 1;
        }
    }

    /// Get a reference to the value at `index`.
    pub fn get(&self, index: usize) -> Option<&T> {
        self.data.get(index)?.as_ref()
    }

    /// Get a mutable reference to the value at `index`.
    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
        self.data.get_mut(index)?.as_mut()
    }

    /// Returns `true` if the slot at `index` is occupied.
    pub fn contains(&self, index: usize) -> bool {
        index < N && self.data[index].is_some()
    }

    /// Number of occupied slots.
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns `true` if no slots are occupied.
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Iterate over `(index, &value)` for occupied slots.
    pub fn iter(&self) -> impl Iterator<Item = (usize, &T)> {
        self.data
            .iter()
            .enumerate()
            .filter_map(|(i, slot)| slot.as_ref().map(|v| (i, v)))
    }

    /// Insert `value` into the first empty slot, returning the slot index.
    ///
    /// Returns `None` if the set is full.
    pub fn push(&mut self, value: T) -> Option<usize> {
        for i in 0..N {
            if self.data[i].is_none() {
                self.data[i] = Some(value);
                self.len += 1;
                return Some(i);
            }
        }
        None
    }

    /// Iterate mutably over `(index, &mut value)` for occupied slots.
    pub fn iter_mut(&mut self) -> impl Iterator<Item = (usize, &mut T)> {
        self.data
            .iter_mut()
            .enumerate()
            .filter_map(|(i, slot)| slot.as_mut().map(|v| (i, v)))
    }

    /// Remove all elements.
    pub fn clear(&mut self) {
        for slot in &mut self.data {
            slot.take();
        }
        self.len = 0;
    }
}

impl<T: PartialEq, const N: usize> ArraySet<T, N> {
    /// Returns `true` if `value` is present in any occupied slot.
    pub fn contains_value(&self, value: &T) -> bool {
        self.data.iter().any(|slot| slot.as_ref() == Some(value))
    }

    /// Remove the first occupied slot whose value equals `value`.
    ///
    /// Returns `true` if an element was removed.
    pub fn remove_value(&mut self, value: &T) -> bool {
        for slot in &mut self.data {
            if slot.as_ref() == Some(value) {
                slot.take();
                self.len -= 1;
                return true;
            }
        }
        false
    }
}

/// Index by slot number. Panics if the slot is empty.
impl<T, const N: usize> Index<usize> for ArraySet<T, N> {
    type Output = T;
    fn index(&self, index: usize) -> &T {
        self.data[index].as_ref().expect("slot is empty")
    }
}

/// Mutable index by slot number. Panics if the slot is empty.
impl<T, const N: usize> IndexMut<usize> for ArraySet<T, N> {
    fn index_mut(&mut self, index: usize) -> &mut T {
        self.data[index].as_mut().expect("slot is empty")
    }
}

impl<T: Clone, const N: usize> Default for ArraySet<T, N> {
    fn default() -> Self {
        Self::new()
    }
}

/// Permutation (multiset) equality: slot positions are ignored; two sets are
/// equal iff every value occurs the same number of times in both.
impl<T: PartialEq, const N: usize> PartialEq for ArraySet<T, N> {
    fn eq(&self, other: &Self) -> bool {
        if self.len != other.len {
            return false;
        }
        // Fast path: identical slot layout is trivially a permutation.
        if self.data == other.data {
            return true;
        }
        // Otherwise greedily match each occupied value to a distinct slot of
        // `other`. O(N²), with N a small compile-time capacity.
        let mut matched = [false; N];
        'next: for v in self.data.iter().flatten() {
            for (j, w) in other.data.iter().enumerate() {
                if !matched[j] && w.as_ref() == Some(v) {
                    matched[j] = true;
                    continue 'next;
                }
            }
            return false;
        }
        true
    }
}

impl<T: Eq, const N: usize> Eq for ArraySet<T, N> {}

/// Symmetric (order-independent) hash: additive accumulation of element hashes.
///
/// Starts from seed 42 (matching VerC3's convention) to give non-zero hashes for
/// sparse sets and avoid cancellation of duplicate values that XOR would cause.
impl<T: Hash, const N: usize> Hash for ArraySet<T, N> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        let mut sym: u64 = 42;
        for (_, elem) in self.iter() {
            sym = sym.wrapping_add(hash_of(elem));
        }
        state.write_u64(sym);
    }
}

/// Renders as `[v1,v2,v3]` — elements in slot order, comma-separated.
///
/// The slot indices are not shown; use `{:?}` for the full internal representation.
impl<T: fmt::Display, const N: usize> fmt::Display for ArraySet<T, N> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[")?;
        let mut first = true;
        for (_, v) in self.iter() {
            if !first {
                write!(f, ",")?;
            }
            write!(f, "{v}")?;
            first = false;
        }
        write!(f, "]")
    }
}

// -----------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::hash_map::DefaultHasher;

    fn compute_hash<T: Hash>(v: &T) -> u64 {
        let mut h = DefaultHasher::new();
        v.hash(&mut h);
        h.finish()
    }

    #[test]
    fn array_set_from_fn() {
        let s: ArraySet<u32, 3> = ArraySet::from_fn(|i| (i * 10) as u32);
        assert_eq!(s.len(), 3);
        assert!(s.contains(0) && s.contains(1) && s.contains(2));
        assert_eq!(s[0], 0);
        assert_eq!(s[1], 10);
        assert_eq!(s[2], 20);
    }

    #[test]
    fn array_set_insert_get() {
        let mut s: ArraySet<u32, 4> = ArraySet::new();
        assert!(s.is_empty());
        s.insert(0, 10);
        s.insert(2, 30);
        assert_eq!(s.len(), 2);
        assert_eq!(s.get(0), Some(&10));
        assert_eq!(s.get(1), None);
        assert_eq!(s.get(2), Some(&30));
        assert_eq!(s.get(3), None);
    }

    #[test]
    fn array_set_remove() {
        let mut s: ArraySet<u32, 3> = ArraySet::new();
        s.insert(1, 42);
        assert!(s.contains(1));
        s.remove(1);
        assert!(!s.contains(1));
        assert_eq!(s.len(), 0);
    }

    #[test]
    fn array_set_iter() {
        let mut s: ArraySet<u32, 4> = ArraySet::new();
        s.insert(0, 1);
        s.insert(3, 9);
        let pairs: Vec<_> = s.iter().collect();
        assert_eq!(pairs, vec![(0, &1u32), (3, &9u32)]);
    }

    #[test]
    fn array_set_permutation_equality() {
        let mut a: ArraySet<u32, 4> = ArraySet::new();
        a.insert(0, 1);
        a.insert(1, 2);

        // Same slots, same values.
        let mut b: ArraySet<u32, 4> = ArraySet::new();
        b.insert(0, 1);
        b.insert(1, 2);
        assert_eq!(a, b);
        assert_eq!(compute_hash(&a), compute_hash(&b));

        // Same values, different slots — equal (permutation equality).
        let mut c: ArraySet<u32, 4> = ArraySet::new();
        c.insert(2, 2);
        c.insert(3, 1);
        assert_eq!(a, c);
        assert_eq!(compute_hash(&a), compute_hash(&c));

        // Different multiset — not equal.
        let mut d: ArraySet<u32, 4> = ArraySet::new();
        d.insert(0, 1);
        d.insert(1, 1);
        assert_ne!(a, d);

        // Different occupancy count — not equal.
        let mut e: ArraySet<u32, 4> = ArraySet::new();
        e.insert(0, 1);
        assert_ne!(a, e);
    }

    #[test]
    fn array_set_symmetric_hash() {
        // Same elements, different slots → same hash (symmetry reduction).
        // Equality semantics are covered by `array_set_permutation_equality`.
        let mut a: ArraySet<u32, 4> = ArraySet::new();
        a.insert(0, 1);
        a.insert(1, 2);

        let mut b: ArraySet<u32, 4> = ArraySet::new();
        b.insert(0, 2);
        b.insert(1, 1);

        assert_eq!(compute_hash(&a), compute_hash(&b));
    }

    #[test]
    fn array_set_push() {
        let mut s: ArraySet<u32, 3> = ArraySet::new();
        assert_eq!(s.push(10), Some(0));
        assert_eq!(s.push(20), Some(1));
        assert_eq!(s.push(30), Some(2));
        assert_eq!(s.push(40), None); // full
        assert_eq!(s.len(), 3);
    }

    #[test]
    fn array_set_clear() {
        let mut s: ArraySet<u32, 3> = ArraySet::new();
        s.insert(0, 1);
        s.insert(2, 3);
        s.clear();
        assert!(s.is_empty());
        assert_eq!(s.len(), 0);
        assert!(!s.contains(0));
    }

    #[test]
    fn array_set_contains_remove_value() {
        let mut s: ArraySet<u32, 4> = ArraySet::new();
        s.push(10);
        s.push(20);
        s.push(30);
        assert!(s.contains_value(&20));
        assert!(!s.contains_value(&99));
        assert!(s.remove_value(&20));
        assert!(!s.contains_value(&20));
        assert_eq!(s.len(), 2);
        assert!(!s.remove_value(&99)); // not present
    }

    #[test]
    fn array_set_index() {
        let mut s: ArraySet<u32, 3> = ArraySet::new();
        s.insert(1, 42);
        assert_eq!(s[1], 42);
    }

    #[test]
    fn array_set_index_mut() {
        let mut s: ArraySet<u32, 3> = ArraySet::new();
        s.insert(0, 10);
        s[0] = 99;
        assert_eq!(s[0], 99);
    }

    #[test]
    fn array_set_display() {
        let mut s: ArraySet<u32, 4> = ArraySet::new();
        assert_eq!(format!("{s}"), "[]");
        s.insert(0, 10);
        s.insert(2, 30);
        assert_eq!(format!("{s}"), "[10,30]");
    }

    #[test]
    fn combine_hash_varies() {
        assert_ne!(combine_hash(0, 42), combine_hash(0, 43));
        assert_ne!(combine_hash(1, 42), combine_hash(2, 42));
    }
}