1use core::fmt;
8use core::hash::Hash;
9
10use crate::containers::IndexLike;
11use crate::containers::Tagged;
12use crate::containers::{AppendOnlyVec, ShrinkPolicy, VecI, VecToken};
13
14#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
21#[repr(transparent)]
22pub struct PortArity(pub u8);
23
24impl PortArity {
25 pub const ZERO: Self = PortArity(0);
26 pub const ONE: Self = PortArity(1);
27 pub const MAX: Self = PortArity(u8::MAX);
28
29 #[inline]
30 pub fn new(n: u8) -> Self {
31 PortArity(n)
32 }
33
34 #[inline]
36 pub fn checked_add(self, d: PortArity) -> Self {
37 PortArity(self.0.checked_add(d.0).expect("arity overflow (max 255)"))
38 }
39
40 #[inline]
42 pub fn max(self, other: Self) -> Self {
43 PortArity(self.0.max(other.0))
44 }
45
46 #[inline]
48 pub fn product(self, other: Self) -> u32 {
49 (self.0 as u32) * (other.0 as u32)
50 }
51}
52
53impl From<PortArity> for u8 {
54 #[inline]
55 fn from(a: PortArity) -> u8 {
56 a.0
57 }
58}
59
60impl From<u8> for PortArity {
61 #[inline]
62 fn from(n: u8) -> PortArity {
63 PortArity(n)
64 }
65}
66
67impl From<PortArity> for u32 {
68 #[inline]
69 fn from(a: PortArity) -> u32 {
70 a.0 as u32
71 }
72}
73
74impl From<PortArity> for usize {
75 #[inline]
76 fn from(a: PortArity) -> usize {
77 a.0 as usize
78 }
79}
80
81impl fmt::Debug for PortArity {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 write!(f, "{}", self.0)
84 }
85}
86
87impl fmt::Display for PortArity {
88 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89 write!(f, "{}", self.0)
90 }
91}
92
93pub trait DirectorBits: Copy + Eq + Hash + Ord + fmt::Debug + 'static {
103 const BITS: u32;
104 const SPILL_TAG: Self;
105 fn from_u64(v: u64) -> Self;
106 fn to_u64(self) -> u64;
107}
108
109impl DirectorBits for () {
112 const BITS: u32 = 0;
113 const SPILL_TAG: Self = ();
114 #[inline(always)]
115 fn from_u64(_: u64) -> Self {}
116 #[inline(always)]
117 fn to_u64(self) -> u64 {
118 0
119 }
120}
121
122impl DirectorBits for u16 {
125 const BITS: u32 = 16;
126 const SPILL_TAG: Self = 0x8000;
127 #[inline(always)]
128 fn from_u64(v: u64) -> Self {
129 v as u16
130 }
131 #[inline(always)]
132 fn to_u64(self) -> u64 {
133 self as u64
134 }
135}
136
137impl DirectorBits for u32 {
140 const BITS: u32 = 32;
141 const SPILL_TAG: Self = 0x8000_0000;
142 #[inline(always)]
143 fn from_u64(v: u64) -> Self {
144 v as u32
145 }
146 #[inline(always)]
147 fn to_u64(self) -> u64 {
148 self as u64
149 }
150}
151
152impl DirectorBits for u64 {
155 const BITS: u32 = 64;
156 const SPILL_TAG: Self = 0x8000_0000_0000_0000;
157 #[inline(always)]
158 fn from_u64(v: u64) -> Self {
159 v
160 }
161 #[inline(always)]
162 fn to_u64(self) -> u64 {
163 self
164 }
165}
166
167#[inline]
182fn matrix_bits(k: u8, n: u8) -> u32 {
183 let bits = (k as u32) * (n as u32);
184 assert!(
185 bits <= 64,
186 "director matrix {k}×{n} needs {bits} bits; the matrix ops pack a matrix into a \
187 single u64 and cannot exceed 64"
188 );
189 bits
190}
191
192#[inline]
198fn pool_start<I: IndexLike>(pool_index: usize) -> I {
199 <I as IndexLike>::try_from_usize(pool_index)
200 .expect("director spill index exceeds the pool's index word")
201}
202
203#[derive(Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
208pub struct Director<W: DirectorBits>(pub(crate) W);
209
210impl<W: DirectorBits> fmt::Debug for Director<W> {
211 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212 if W::BITS == 0 {
213 write!(f, "Dir(∅)")
214 } else if self.is_inline() {
215 write!(f, "Dir(0x{:x})", self.0.to_u64())
216 } else {
217 write!(f, "Dir(spill@{})", self.pool_index())
218 }
219 }
220}
221
222impl<W: DirectorBits> Director<W> {
223 #[inline]
225 pub fn zero() -> Self {
226 Director(W::from_u64(0))
227 }
228
229 #[inline]
231 pub fn new_inline(bits: u64) -> Self {
232 if W::BITS > 0 {
233 assert!(
238 bits < W::SPILL_TAG.to_u64(),
239 "inline bits overflow the director word's payload"
240 );
241 }
242 Director(W::from_u64(bits))
243 }
244
245 #[inline]
256 pub fn new_spilled(pool_index: usize) -> Self {
257 assert!(W::BITS > 0, "cannot spill with DIRECTOR_BITS=0");
258 let idx = pool_index as u64;
259 let capacity = 1u64 << (W::BITS - 1);
260 assert!(
261 idx < capacity,
262 "director spill index {idx} does not fit the {} bits available beside the \
263 spill tag; configure a wider DirectorBits word",
264 W::BITS - 1
265 );
266 Director(W::from_u64(idx | W::SPILL_TAG.to_u64()))
267 }
268
269 #[inline]
271 pub fn is_inline(&self) -> bool {
272 W::BITS == 0 || (self.0.to_u64() & W::SPILL_TAG.to_u64()) == 0
273 }
274
275 #[inline]
282 pub fn inline_bits(&self) -> u64 {
283 assert!(self.is_inline(), "called inline_bits on spilled matrix");
284 self.0.to_u64()
285 }
286
287 #[inline]
292 pub fn pool_index(&self) -> usize {
293 assert!(!self.is_inline(), "called pool_index on inline matrix");
294 (self.0.to_u64() & !W::SPILL_TAG.to_u64()) as usize
295 }
296
297 #[inline]
299 pub fn raw(&self) -> W {
300 self.0
301 }
302
303 fn resolve<I: IndexLike, const TRACK: bool, const PROOFS: bool>(
310 &self,
311 pool: &DirectorPool<I, TRACK, PROOFS>,
312 ) -> u64 {
313 if W::BITS == 0 {
314 return 0;
315 }
316 if self.is_inline() {
317 self.0.to_u64()
320 } else {
321 let spilled = (self.0.to_u64() & !W::SPILL_TAG.to_u64()) as usize;
322 let (bit_length, data) = pool.read(pool_start::<I>(spilled));
323 assert!(bit_length <= 64, "spilled matrix too large for resolve()");
324 let mut bits = 0u64;
328 for (i, w) in data.iter().enumerate() {
329 let shift = (i as u32) * PoolDirector::USABLE_BITS;
330 bits |= w
331 .bits()
332 .checked_shl(shift)
333 .expect("spilled matrix wider than 64 bits reached resolve()");
334 }
335 bits
336 }
337 }
338
339 fn pack<I: IndexLike, const TRACK: bool, const PROOFS: bool>(
342 bits: u64,
343 total_bits: u32,
344 pool: &mut DirectorPool<I, TRACK, PROOFS>,
345 ) -> Self {
346 if W::BITS == 0 {
347 return Self::zero();
348 }
349 let inline_cap = W::BITS - 1;
350 if total_bits <= inline_cap && (bits & W::SPILL_TAG.to_u64()) == 0 {
351 Self::new_inline(bits)
352 } else {
353 let mut data = std::vec::Vec::with_capacity(2);
359 let mut rest = bits;
360 let mut remaining = total_bits;
361 loop {
362 data.push(PoolDirector::new(rest & PoolDirector::DATA_MASK));
363 if remaining <= PoolDirector::USABLE_BITS {
364 break;
365 }
366 rest >>= PoolDirector::USABLE_BITS;
367 remaining -= PoolDirector::USABLE_BITS;
368 }
369 let start = pool.append(total_bits, &data);
370 Self::new_spilled(start.as_usize())
371 }
372 }
373
374 pub fn row_extract<I: IndexLike, const TRACK: bool, const PROOFS: bool>(
380 &self,
381 i: u8,
382 n: u8,
383 pool: &DirectorPool<I, TRACK, PROOFS>,
384 ) -> u64 {
385 matrix_bits(i.checked_add(1).expect("row index 255 has no successor"), n);
388 ops::row_extract(self.resolve(pool), i, n)
389 }
390
391 pub fn col_present<I: IndexLike, const TRACK: bool, const PROOFS: bool>(
393 &self,
394 j: u8,
395 k: u8,
396 n: u8,
397 pool: &DirectorPool<I, TRACK, PROOFS>,
398 ) -> bool {
399 matrix_bits(k, n);
400 assert!(j < n, "column {j} out of range for a matrix of width {n}");
401 ops::col_present(self.resolve(pool), j, k, n)
402 }
403
404 pub fn embed_bitset<I: IndexLike, const TRACK: bool, const PROOFS: bool>(
406 &self,
407 k: u8,
408 n: u8,
409 pool: &DirectorPool<I, TRACK, PROOFS>,
410 ) -> u64 {
411 matrix_bits(k, n);
412 ops::embed_bitset(self.resolve(pool), k, n)
413 }
414
415 pub fn compose<I: IndexLike, const TRACK: bool, const PROOFS: bool>(
420 outer: &Self,
421 inner: &Self,
422 k_inner: u8,
423 k_mid: u8,
424 n_outer: u8,
425 pool: &mut DirectorPool<I, TRACK, PROOFS>,
426 ) -> Self {
427 matrix_bits(k_inner, k_mid);
429 matrix_bits(k_mid, n_outer);
430 let total = matrix_bits(k_inner, n_outer);
431 let ob = outer.resolve(pool);
432 let ib = inner.resolve(pool);
433 let result = ops::compose(ob, ib, k_inner, k_mid, n_outer);
434 Self::pack(result, total, pool)
435 }
436
437 pub fn widen_columns<I: IndexLike, const TRACK: bool, const PROOFS: bool>(
439 &self,
440 k: u8,
441 old_n: u8,
442 new_n: u8,
443 pool: &mut DirectorPool<I, TRACK, PROOFS>,
444 ) -> Self {
445 let total = matrix_bits(k, new_n);
447 let bits = self.resolve(pool);
448 let result = ops::widen_columns(bits, k, old_n, new_n);
449 Self::pack(result, total, pool)
450 }
451
452 pub fn add_zero_rows<I: IndexLike, const TRACK: bool, const PROOFS: bool>(
454 &self,
455 old_k: u8,
456 new_k: u8,
457 n: u8,
458 pool: &mut DirectorPool<I, TRACK, PROOFS>,
459 ) -> Self {
460 let total = matrix_bits(new_k, n);
462 let bits = self.resolve(pool);
463 let result = ops::add_zero_rows(bits, old_k, new_k, n);
464 Self::pack(result, total, pool)
465 }
466
467 pub fn permute_rows<I: IndexLike, const TRACK: bool, const PROOFS: bool>(
469 &self,
470 perm: &[u8],
471 k: u8,
472 n: u8,
473 pool: &mut DirectorPool<I, TRACK, PROOFS>,
474 ) -> Self {
475 let total = matrix_bits(k, n);
476 let bits = self.resolve(pool);
477 let result = ops::permute_rows(bits, perm, k, n);
478 Self::pack(result, total, pool)
479 }
480
481 pub fn shift<I: IndexLike, const TRACK: bool, const PROOFS: bool>(
483 &self,
484 k: u8,
485 n: u8,
486 d: u8,
487 pool: &mut DirectorPool<I, TRACK, PROOFS>,
488 ) -> Self {
489 let new_k = k.checked_add(d).expect("child arity overflow (max 255)");
493 let new_n = n.checked_add(d).expect("parent arity overflow (max 255)");
494 let total = matrix_bits(new_k, new_n);
495 let bits = self.resolve(pool);
496 let result = ops::shift(bits, k, n, d);
497 Self::pack(result, total, pool)
498 }
499
500 pub fn delete_column<I: IndexLike, const TRACK: bool, const PROOFS: bool>(
502 &self,
503 j: u8,
504 k: u8,
505 n: u8,
506 pool: &mut DirectorPool<I, TRACK, PROOFS>,
507 ) -> Self {
508 let new_n = n
511 .checked_sub(1)
512 .expect("delete_column on a matrix with no columns");
513 assert!(j < n, "column {j} out of range for a matrix of width {n}");
514 matrix_bits(k, n);
516 let total = matrix_bits(k, new_n);
517 let bits = self.resolve(pool);
518 let result = ops::delete_column(bits, j, k, n);
519 Self::pack(result, total, pool)
520 }
521
522 pub fn identity<I: IndexLike, const TRACK: bool, const PROOFS: bool>(
526 k: u8,
527 n: u8,
528 pool: &mut DirectorPool<I, TRACK, PROOFS>,
529 ) -> Self {
530 let total = matrix_bits(k, n);
531 let bits = ops::identity(k, n);
532 Self::pack(bits, total, pool)
533 }
534}
535
536#[derive(Clone, Copy, PartialEq, Eq, Hash)]
545pub struct Edge<G, W: DirectorBits> {
546 pub class: G,
547 pub director: Director<W>,
548}
549
550impl<G: fmt::Debug, W: DirectorBits> fmt::Debug for Edge<G, W> {
551 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
552 if W::BITS == 0 {
553 write!(f, "{:?}", self.class)
554 } else {
555 write!(f, "({:?}, {:?})", self.class, self.director)
556 }
557 }
558}
559
560impl<G, W: DirectorBits> Edge<G, W> {
561 #[inline]
562 pub fn new(class: G, director: Director<W>) -> Self {
563 Self { class, director }
564 }
565
566 #[inline]
568 pub fn ground(class: G) -> Self {
569 Self {
570 class,
571 director: Director::zero(),
572 }
573 }
574}
575
576#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
584pub struct PoolDirector(u64);
585
586impl Default for PoolDirector {
589 fn default() -> Self {
590 PoolDirector::new(0)
591 }
592}
593
594impl PoolDirector {
595 pub const USABLE_BITS: u32 = 63;
597 pub const DATA_MASK: u64 = !Self::TAG_BIT;
599 const TAG_BIT: u64 = 1 << 63;
600
601 #[inline]
602 pub fn new(bits: u64) -> Self {
603 debug_assert!(
604 bits & Self::TAG_BIT == 0,
605 "pool word overflow: bit 63 reserved"
606 );
607 PoolDirector(bits)
608 }
609
610 #[inline]
611 pub fn bits(self) -> u64 {
612 self.0 & !Self::TAG_BIT
613 }
614}
615
616impl Tagged for PoolDirector {
617 type Repr = Self;
618
619 #[inline]
620 fn into_repr(self) -> Self {
621 self
622 }
623
624 #[inline]
625 fn from_repr(r: &Self) -> Self {
626 PoolDirector(r.0 & !Self::TAG_BIT)
627 }
628
629 #[inline]
630 fn tag(r: &Self) -> bool {
631 r.0 & Self::TAG_BIT != 0
632 }
633
634 #[inline]
635 fn set_tag(r: &mut Self) {
636 r.0 |= Self::TAG_BIT;
637 }
638
639 #[inline]
640 fn clear_tag(r: &mut Self) {
641 r.0 &= !Self::TAG_BIT;
642 }
643}
644
645pub struct DirectorPool<I: IndexLike = u32, const TRACK: bool = true, const PROOFS: bool = false> {
672 work: VecI<PoolDirector, I, TRACK>,
674 proof: AppendOnlyVec<PoolDirector, I, TRACK>,
676}
677
678impl<I: IndexLike, const TRACK: bool, const PROOFS: bool> Default
679 for DirectorPool<I, TRACK, PROOFS>
680{
681 fn default() -> Self {
682 Self::new()
683 }
684}
685
686impl<I: IndexLike, const TRACK: bool, const PROOFS: bool> DirectorPool<I, TRACK, PROOFS> {
687 pub fn new() -> Self {
688 Self {
689 work: VecI::new(),
690 proof: AppendOnlyVec::new(),
691 }
692 }
693
694 pub fn append(&mut self, bit_length: u32, data: &[PoolDirector]) -> I {
702 let start = self.work.len();
703 self.work
704 .try_push(PoolDirector::new(bit_length as u64))
705 .expect("director pool sized by its index word");
706 for &w in data {
707 self.work
708 .try_push(w)
709 .expect("director pool sized by its index word");
710 }
711 start
712 }
713
714 pub fn bit_length(&self, start: I) -> u32 {
716 u32::try_from(self.work.get(start).bits())
717 .expect("pool entry bit length exceeds u32: `start` does not name a header word")
718 }
719
720 pub fn get(&self, idx: I) -> PoolDirector {
722 self.work.get(idx)
723 }
724
725 pub fn set(&mut self, idx: I, val: PoolDirector) {
727 self.work.set(idx, val);
728 }
729
730 pub fn read(&self, start: I) -> (u32, std::vec::Vec<PoolDirector>) {
732 let bit_length = u32::try_from(self.work.get(start).bits())
733 .expect("pool entry bit length exceeds u32: `start` does not name a header word");
734 let word_count = ceil_div(bit_length, PoolDirector::USABLE_BITS);
735 let mut data = std::vec::Vec::with_capacity(word_count);
736 for i in 0..word_count {
737 let at = crate::containers::index_like::checked_add_usize(start, i + 1)
740 .expect("director pool entry extends past the pool's index word");
741 data.push(self.work.get(at));
742 }
743 (bit_length, data)
744 }
745
746 pub fn len(&self) -> I {
748 self.work.len()
749 }
750
751 pub fn is_empty(&self) -> bool {
752 self.work.is_empty()
753 }
754
755 pub fn mark(&mut self, shrink: ShrinkPolicy) -> VecToken {
757 self.work
758 .try_mark(shrink)
759 .expect("mark: frame depth is bounded by the saturation driver")
760 }
761
762 pub fn restore(&mut self, token: VecToken) {
764 self.work
765 .try_restore(token)
766 .expect("restore: token minted by this container's own mark");
767 }
768
769 pub fn snapshot_to_proof(&mut self, work_start: I) -> I {
778 assert!(PROOFS, "snapshot_to_proof called with PROOFS=false");
779 let (bit_length, data) = self.read(work_start);
780 let proof_start = self.proof.len();
781 self.proof
782 .try_push(PoolDirector::new(bit_length as u64))
783 .expect("proof pool sized by its index word");
784 for w in data {
785 self.proof
786 .try_push(w)
787 .expect("proof pool sized by its index word");
788 }
789 proof_start
790 }
791
792 pub fn read_proof(&self, start: I) -> (u32, std::vec::Vec<PoolDirector>) {
794 let bit_length = self.proof.get(start).bits() as u32;
795 let word_count = ceil_div(bit_length, PoolDirector::USABLE_BITS);
796 let mut data = std::vec::Vec::with_capacity(word_count);
797 for i in 0..word_count {
798 let at = crate::containers::index_like::checked_add_usize(start, i + 1)
802 .expect("proof pool entry extends past the pool's index word");
803 data.push(*self.proof.get(at));
804 }
805 (bit_length, data)
806 }
807
808 pub fn proof_len(&self) -> I {
810 self.proof.len()
811 }
812}
813
814fn ceil_div(a: u32, b: u32) -> usize {
815 (a as usize).div_ceil(b as usize)
816}
817
818pub mod ops {
837 #[inline]
843 fn row_mask(n: u8) -> u64 {
844 match 1u64.checked_shl(n as u32) {
845 Some(v) => v - 1,
846 None => u64::MAX,
848 }
849 }
850
851 #[inline]
853 pub fn row_extract(bits: u64, i: u8, n: u8) -> u64 {
854 let shift = (i as u32) * (n as u32);
855 (bits >> shift) & row_mask(n)
856 }
857
858 #[inline]
860 pub fn row_set(bits: u64, i: u8, n: u8, val: u64) -> u64 {
861 let shift = (i as u32) * (n as u32);
862 let mask = row_mask(n);
863 (bits & !(mask << shift)) | ((val & mask) << shift)
864 }
865
866 #[inline]
868 pub fn col_present(bits: u64, j: u8, k: u8, n: u8) -> bool {
869 for i in 0..k {
870 if row_extract(bits, i, n) & (1u64 << j) != 0 {
871 return true;
872 }
873 }
874 false
875 }
876
877 #[inline]
879 pub fn embed_bitset(bits: u64, k: u8, n: u8) -> u64 {
880 let mask = row_mask(n);
881 let mut result = 0u64;
882 for i in 0..k {
883 result |= row_extract(bits, i, n);
884 }
885 result & mask
886 }
887
888 pub fn identity(k: u8, n: u8) -> u64 {
890 let mut bits = 0u64;
891 for i in 0..k.min(n) {
892 bits |= 1u64 << ((i as u32) * (n as u32) + (i as u32));
893 }
894 bits
895 }
896
897 pub fn compose(outer: u64, inner: u64, k_inner: u8, k_mid: u8, n_outer: u8) -> u64 {
903 let mut result = 0u64;
904 for i in 0..k_inner {
905 let inner_row = row_extract(inner, i, k_mid);
906 if inner_row == 0 {
907 continue; }
909 let p = inner_row.trailing_zeros() as u8;
910 let outer_row = row_extract(outer, p, n_outer);
911 result |= outer_row << ((i as u32) * (n_outer as u32));
912 }
913 result
914 }
915
916 pub fn widen_columns(bits: u64, k: u8, old_n: u8, new_n: u8) -> u64 {
919 debug_assert!(new_n >= old_n);
920 let mut result = 0u64;
921 for i in 0..k {
922 let row = row_extract(bits, i, old_n);
923 result |= row << ((i as u32) * (new_n as u32));
924 }
925 result
926 }
927
928 pub fn add_zero_rows(bits: u64, old_k: u8, new_k: u8, n: u8) -> u64 {
932 debug_assert!(new_k >= old_k);
933 let used = (old_k as u32) * (n as u32);
937 if used >= 64 {
938 bits
939 } else {
940 bits & ((1u64 << used) - 1)
941 }
942 }
943
944 pub fn permute_rows(bits: u64, perm: &[u8], k: u8, n: u8) -> u64 {
946 debug_assert!(perm.len() == k as usize);
947 let mut result = 0u64;
948 for i in 0..k {
949 let row = row_extract(bits, perm[i as usize], n);
950 result |= row << ((i as u32) * (n as u32));
951 }
952 result
953 }
954
955 pub fn shift(bits: u64, k: u8, n: u8, d: u8) -> u64 {
958 let new_n = n.checked_add(d).expect("parent arity overflow (max 255)");
959 let mut result = 0u64;
960 for i in 0..k {
962 let row = row_extract(bits, i, n);
963 let shifted = row << (d as u32);
964 result |= shifted << (((d + i) as u32) * (new_n as u32));
965 }
966 result
967 }
968
969 pub fn delete_column(bits: u64, j: u8, k: u8, n: u8) -> u64 {
972 let new_n = n
973 .checked_sub(1)
974 .expect("delete_column on a matrix with no columns");
975 let mut result = 0u64;
976 for i in 0..k {
977 let row = row_extract(bits, i, n);
978 let lo = row & row_mask(j);
980 let hi = row.checked_shr(j as u32 + 1).unwrap_or(0) << j;
984 result |= (lo | hi) << ((i as u32) * (new_n as u32));
985 }
986 result
987 }
988}
989
990#[cfg(test)]
995mod tests {
996 use super::*;
997
998 #[test]
999 fn zst_child_edge_same_size_as_g() {
1000 assert_eq!(
1001 core::mem::size_of::<Edge<u32, ()>>(),
1002 core::mem::size_of::<u32>(),
1003 );
1004 }
1005
1006 #[test]
1007 fn child_edge_sizes() {
1008 assert_eq!(core::mem::size_of::<Edge<u32, u16>>(), 8);
1010 assert_eq!(core::mem::size_of::<Edge<u32, u32>>(), 8);
1011 assert_eq!(core::mem::size_of::<Edge<u32, u64>>(), 16);
1012 }
1013
1014 #[test]
1015 fn inline_roundtrip() {
1016 let m = Director::<u32>::new_inline(0b0110_1001);
1017 assert!(m.is_inline());
1018 assert_eq!(m.inline_bits(), 0b0110_1001);
1019 }
1020
1021 #[test]
1022 fn spill_roundtrip() {
1023 let m = Director::<u32>::new_spilled(42);
1024 assert!(!m.is_inline());
1025 assert_eq!(m.pool_index(), 42);
1026 }
1027
1028 #[test]
1029 fn zero_matrix() {
1030 let m = Director::<u64>::zero();
1031 assert!(m.is_inline());
1032 assert_eq!(m.inline_bits(), 0);
1033 }
1034
1035 #[test]
1036 fn zst_always_inline() {
1037 let m = Director::<()>::zero();
1038 assert!(m.is_inline());
1039 }
1040
1041 #[test]
1042 #[should_panic(expected = "cannot spill")]
1043 fn zst_cannot_spill() {
1044 Director::<()>::new_spilled(0);
1045 }
1046
1047 #[test]
1048 fn dir_word_u16_limits() {
1049 let m = Director::<u16>::new_inline(0x7FFF);
1051 assert!(m.is_inline());
1052 assert_eq!(m.inline_bits(), 0x7FFF);
1053 }
1054
1055 #[test]
1056 fn dir_word_u64_limits() {
1057 let m = Director::<u64>::new_inline(0x7FFF_FFFF_FFFF_FFFF);
1059 assert!(m.is_inline());
1060 }
1061
1062 #[test]
1063 fn ground_child_edge() {
1064 let e = Edge::<u32, u32>::ground(7);
1065 assert_eq!(e.class, 7);
1066 assert_eq!(e.director.inline_bits(), 0);
1067 }
1068
1069 #[test]
1070 fn pool_word_size() {
1071 assert_eq!(core::mem::size_of::<PoolDirector>(), 8);
1072 }
1073
1074 #[test]
1075 fn pool_word_roundtrip() {
1076 let w = PoolDirector::new(0x7FFF_FFFF_FFFF_FFFF);
1077 assert_eq!(w.bits(), 0x7FFF_FFFF_FFFF_FFFF);
1078 }
1079
1080 #[test]
1081 fn pool_word_tagged() {
1082 let mut w = PoolDirector::new(42);
1083 assert!(!PoolDirector::tag(&w));
1084 PoolDirector::set_tag(&mut w);
1085 assert!(PoolDirector::tag(&w));
1086 assert_eq!(PoolDirector::from_repr(&w).bits(), 42);
1088 PoolDirector::clear_tag(&mut w);
1089 assert!(!PoolDirector::tag(&w));
1090 assert_eq!(w.bits(), 42);
1091 }
1092
1093 #[test]
1094 fn dir_pool_append_read() {
1095 let mut pool = DirectorPool::<u32, false, false>::new();
1096 let data = [PoolDirector::new(0b1010101), PoolDirector::new(0b1100110)];
1097 let start = pool.append(126, &data);
1098 let (len, words) = pool.read(start);
1099 assert_eq!(len, 126);
1100 assert_eq!(words.len(), 2);
1101 assert_eq!(words[0].bits(), 0b1010101);
1102 assert_eq!(words[1].bits(), 0b1100110);
1103 }
1104
1105 #[test]
1106 fn dir_pool_mark_restore() {
1107 let mut pool = DirectorPool::<u32, true, false>::new();
1108 let token = pool.mark(crate::containers::ShrinkPolicy::Never);
1109 pool.append(63, &[PoolDirector::new(0xFF)]);
1110 pool.append(63, &[PoolDirector::new(0xAA)]);
1111 assert_eq!(pool.len(), 4);
1112 pool.restore(token);
1113 assert!(pool.is_empty());
1114 }
1115
1116 #[test]
1117 fn dir_pool_mutate_in_place() {
1118 let mut pool = DirectorPool::<u32, false, false>::new();
1119 let start = pool.append(63, &[PoolDirector::new(0xFF)]);
1120 assert_eq!(pool.get(start + 1).bits(), 0xFF);
1121 pool.set(start + 1, PoolDirector::new(0xAB));
1122 assert_eq!(pool.get(start + 1).bits(), 0xAB);
1123 }
1124
1125 #[test]
1126 fn dir_pool_proof_snapshot() {
1127 let mut pool = DirectorPool::<u32, false, true>::new();
1128 let start = pool.append(63, &[PoolDirector::new(0x42)]);
1129 let proof_start = pool.snapshot_to_proof(start);
1130 pool.set(start + 1, PoolDirector::new(0x99));
1132 let (len, data) = pool.read_proof(proof_start);
1134 assert_eq!(len, 63);
1135 assert_eq!(data[0].bits(), 0x42);
1136 let (_, wdata) = pool.read(start);
1138 assert_eq!(wdata[0].bits(), 0x99);
1139 }
1140
1141 #[test]
1144 #[should_panic(expected = "does not fit")]
1145 fn spill_index_past_word_capacity_panics() {
1146 Director::<u16>::new_spilled(1 << 15);
1150 }
1151
1152 #[test]
1153 fn spill_index_at_word_capacity_boundary() {
1154 let m = Director::<u16>::new_spilled((1 << 15) - 1);
1155 assert!(!m.is_inline());
1156 assert_eq!(m.pool_index(), (1 << 15) - 1);
1157 }
1158
1159 #[test]
1160 fn full_64_bit_matrix_survives_the_pool() {
1161 let mut pool = DirectorPool::<u32, false, false>::new();
1165 let m = Director::<u64>::identity(8, 8, &mut pool);
1166 assert!(!m.is_inline(), "64 bits exceed u64's 63 inline bits");
1167 let (bit_length, words) = pool.read(pool_start::<u32>(m.pool_index()));
1168 assert_eq!(bit_length, 64);
1169 assert_eq!(words.len(), 2, "63 usable bits per pool word");
1170 for w in &words {
1171 assert!(!PoolDirector::tag(w), "capture tag must stay clear");
1172 }
1173 assert_eq!(m.row_extract(7, 8, &pool), 1 << 7);
1175 assert_eq!(m.embed_bitset(8, 8, &pool), 0xFF);
1176 }
1177
1178 #[test]
1179 #[should_panic(expected = "cannot exceed 64")]
1180 fn oversized_matrix_dimensions_panic() {
1181 let mut pool = DirectorPool::<u32, false, false>::new();
1184 Director::<u64>::identity(9, 9, &mut pool);
1185 }
1186
1187 #[test]
1188 fn single_row_64_columns() {
1189 let mut pool = DirectorPool::<u32, false, false>::new();
1192 let m = Director::<u64>::identity(1, 64, &mut pool);
1193 assert_eq!(m.row_extract(0, 64, &pool), 1);
1194 let d = m.delete_column(63, 1, 64, &mut pool);
1197 assert_eq!(d.row_extract(0, 63, &pool), 1);
1198 }
1199
1200 #[test]
1201 #[should_panic(expected = "no columns")]
1202 fn delete_column_on_empty_width_panics() {
1203 let mut pool = DirectorPool::<u32, false, false>::new();
1205 let m = Director::<u32>::zero();
1206 m.delete_column(0, 1, 0, &mut pool);
1207 }
1208
1209 #[test]
1210 #[should_panic(expected = "out of range")]
1211 fn delete_nonexistent_column_panics() {
1212 let mut pool = DirectorPool::<u32, false, false>::new();
1213 let m = Director::<u32>::identity(2, 2, &mut pool);
1214 m.delete_column(2, 2, 2, &mut pool);
1215 }
1216
1217 #[test]
1218 fn pool_index_word_narrower_than_u32() {
1219 let mut pool = DirectorPool::<u16, true, false>::new();
1222 let token = pool.mark(crate::containers::ShrinkPolicy::Never);
1223 let start: u16 = pool.append(63, &[PoolDirector::new(0x5A)]);
1224 assert_eq!(pool.len(), 2u16);
1225 assert_eq!(pool.read(start).1[0].bits(), 0x5A);
1226 pool.set(start + 1, PoolDirector::new(0xA5));
1227 assert_eq!(pool.get(start + 1).bits(), 0xA5);
1228 pool.restore(token);
1229 assert!(pool.is_empty());
1230 }
1231
1232 #[test]
1235 fn typed_api_inline() {
1236 let mut pool = DirectorPool::<u32, false, false>::new();
1237 let m = Director::<u32>::identity(2, 3, &mut pool);
1239 assert!(m.is_inline());
1240 assert_eq!(m.row_extract(0, 3, &pool), 0b001);
1241 assert_eq!(m.row_extract(1, 3, &pool), 0b010);
1242 assert_eq!(m.embed_bitset(2, 3, &pool), 0b011);
1243 assert!(m.col_present(0, 2, 3, &pool));
1244 assert!(m.col_present(1, 2, 3, &pool));
1245 assert!(!m.col_present(2, 2, 3, &pool));
1246 }
1247
1248 #[test]
1249 fn typed_api_compose() {
1250 let mut pool = DirectorPool::<u32, false, false>::new();
1251 let id = Director::<u32>::identity(2, 2, &mut pool);
1252 let m = Director::<u32>::new_inline(0b10_01); let c = Director::compose(&id, &m, 2, 2, 2, &mut pool);
1254 assert_eq!(c.inline_bits(), m.inline_bits());
1255 }
1256
1257 #[test]
1258 fn typed_api_shift_delete_roundtrip() {
1259 let mut pool = DirectorPool::<u32, false, false>::new();
1260 let m = Director::<u32>::identity(2, 2, &mut pool);
1261 let shifted = m.shift(2, 2, 1, &mut pool);
1262 assert_eq!(shifted.row_extract(0, 3, &pool), 0b000);
1264 assert_eq!(shifted.row_extract(1, 3, &pool), 0b010);
1265 assert_eq!(shifted.row_extract(2, 3, &pool), 0b100);
1266 let del = shifted.delete_column(0, 3, 3, &mut pool);
1268 assert_eq!(del.row_extract(0, 2, &pool), 0b00);
1270 assert_eq!(del.row_extract(1, 2, &pool), 0b01);
1271 assert_eq!(del.row_extract(2, 2, &pool), 0b10);
1272 }
1273
1274 #[test]
1275 fn typed_api_spill_and_read() {
1276 let mut pool = DirectorPool::<u32, false, false>::new();
1278 let m = Director::<u16>::identity(4, 4, &mut pool);
1280 assert!(!m.is_inline(), "4×4 should spill with u16");
1281 assert_eq!(m.row_extract(0, 4, &pool), 0b0001);
1283 assert_eq!(m.row_extract(1, 4, &pool), 0b0010);
1284 assert_eq!(m.row_extract(2, 4, &pool), 0b0100);
1285 assert_eq!(m.row_extract(3, 4, &pool), 0b1000);
1286 assert_eq!(m.embed_bitset(4, 4, &pool), 0b1111);
1287 }
1288
1289 use super::ops::*;
1294
1295 #[test]
1296 fn identity_2x3() {
1297 let m = identity(2, 3);
1299 assert_eq!(row_extract(m, 0, 3), 0b001);
1300 assert_eq!(row_extract(m, 1, 3), 0b010);
1301 }
1302
1303 #[test]
1304 fn identity_embed() {
1305 let m = identity(3, 4);
1306 assert_eq!(embed_bitset(m, 3, 4), 0b0111);
1307 }
1308
1309 #[test]
1310 fn compose_identity_left() {
1311 let m = 0b010_001u64; let id = identity(3, 3);
1314 assert_eq!(compose(id, m, 2, 3, 3), m);
1315 }
1316
1317 #[test]
1318 fn compose_identity_right() {
1319 let m = 0b010_001u64; let id = identity(2, 2);
1322 assert_eq!(compose(m, id, 2, 2, 3), m);
1323 }
1324
1325 #[test]
1326 fn compose_swap() {
1327 let swap = 0b01_10u64; let id = identity(2, 2);
1330 let result = compose(id, swap, 2, 2, 2);
1331 assert_eq!(result, swap);
1332 }
1333
1334 #[test]
1335 fn widen_preserves_rows() {
1336 let m = 0b10_01u64; let w = widen_columns(m, 2, 2, 4);
1338 assert_eq!(row_extract(w, 0, 4), 0b0001);
1339 assert_eq!(row_extract(w, 1, 4), 0b0010);
1340 }
1341
1342 #[test]
1343 fn add_zero_rows_preserves() {
1344 let m = 0b10_01u64; let r = add_zero_rows(m, 2, 4, 2);
1346 assert_eq!(row_extract(r, 0, 2), 0b01);
1347 assert_eq!(row_extract(r, 1, 2), 0b10);
1348 }
1350
1351 #[test]
1352 fn shift_1() {
1353 let m = 0b1u64; let s = shift(m, 1, 1, 1);
1356 assert_eq!(row_extract(s, 0, 2), 0b00);
1358 assert_eq!(row_extract(s, 1, 2), 0b10);
1359 }
1360
1361 #[test]
1362 fn shift_preserves_structure() {
1363 let m = identity(2, 2);
1365 let s = shift(m, 2, 2, 1);
1366 assert_eq!(row_extract(s, 0, 3), 0b000);
1368 assert_eq!(row_extract(s, 1, 3), 0b010);
1370 assert_eq!(row_extract(s, 2, 3), 0b100);
1372 }
1373
1374 #[test]
1375 fn delete_column_middle() {
1376 let m = 0b100_010u64;
1378 let d = delete_column(m, 0, 2, 3);
1380 assert_eq!(row_extract(d, 0, 2), 0b01);
1381 assert_eq!(row_extract(d, 1, 2), 0b10);
1382 }
1383
1384 #[test]
1385 fn delete_column_removes_reference() {
1386 let m = 0b010_001u64;
1388 let d = delete_column(m, 1, 2, 3);
1390 assert_eq!(row_extract(d, 0, 2), 0b01);
1391 assert_eq!(row_extract(d, 1, 2), 0b00);
1392 }
1393
1394 #[test]
1395 fn permute_swap() {
1396 let m = identity(2, 2);
1398 let p = permute_rows(m, &[1, 0], 2, 2);
1399 assert_eq!(row_extract(p, 0, 2), 0b10);
1401 assert_eq!(row_extract(p, 1, 2), 0b01);
1403 }
1404
1405 mod prop {
1423 use super::*;
1424 use proptest::prelude::*;
1425
1426 fn arb_matrix(k: u8, n: u8) -> impl Strategy<Value = u64> {
1430 proptest::collection::vec(0..=(n as usize), k as usize).prop_map(move |cols| {
1431 let mut bits = 0u64;
1432 for (i, &c) in cols.iter().enumerate() {
1433 if c < n as usize {
1434 bits |= 1u64 << (i * n as usize + c);
1435 }
1436 }
1437 bits
1438 })
1439 }
1440
1441 fn arb_perm(k: u8) -> impl Strategy<Value = Vec<u8>> {
1442 Just((0..k).collect::<Vec<u8>>()).prop_shuffle()
1443 }
1444
1445 fn dims_and_matrix() -> impl Strategy<Value = (u8, u8, u64)> {
1446 (1u8..=5, 1u8..=5)
1447 .prop_filter("fits", |&(k, n)| (k as u32) * (n as u32) <= 63)
1448 .prop_flat_map(|(k, n)| arb_matrix(k, n).prop_map(move |m| (k, n, m)))
1449 }
1450
1451 fn two_composable() -> impl Strategy<Value = (u8, u8, u8, u64, u64)> {
1452 (1u8..=4, 1u8..=4, 1u8..=4)
1453 .prop_filter("fits", |&(ki, km, no)| {
1454 [
1455 ki as u32 * km as u32,
1456 km as u32 * no as u32,
1457 ki as u32 * no as u32,
1458 ]
1459 .iter()
1460 .all(|&x| x <= 63)
1461 })
1462 .prop_flat_map(|(ki, km, no)| {
1463 (arb_matrix(km, no), arb_matrix(ki, km))
1464 .prop_map(move |(o, i)| (ki, km, no, o, i))
1465 })
1466 }
1467
1468 fn three_composable() -> impl Strategy<Value = (u8, u8, u8, u8, u64, u64, u64)> {
1469 (1u8..=3, 1u8..=3, 1u8..=3, 1u8..=3)
1470 .prop_filter("fits", |&(ka, kb, kc, nd)| {
1471 [kb * nd, ka * kb, kc * ka, ka * nd, kc * kb, kc * nd]
1472 .iter()
1473 .all(|&x| (x as u32) <= 63)
1474 })
1475 .prop_flat_map(|(ka, kb, kc, nd)| {
1476 (arb_matrix(kb, nd), arb_matrix(ka, kb), arb_matrix(kc, ka))
1477 .prop_map(move |(a, b, c)| (ka, kb, kc, nd, a, b, c))
1478 })
1479 }
1480
1481 fn shift_args() -> impl Strategy<Value = (u8, u8, u8, u64)> {
1482 (1u8..=4, 1u8..=4, 1u8..=3)
1483 .prop_filter("fits", |&(k, n, d)| {
1484 (k as u32 + d as u32) * (n as u32 + d as u32) <= 63
1485 })
1486 .prop_flat_map(|(k, n, d)| arb_matrix(k, n).prop_map(move |m| (k, n, d, m)))
1487 }
1488
1489 fn delete_args() -> impl Strategy<Value = (u8, u8, u8, u64)> {
1490 (1u8..=5, 2u8..=6)
1491 .prop_filter("fits", |&(k, n)| (k as u32) * (n as u32) <= 63)
1492 .prop_flat_map(|(k, n)| {
1493 (0..n, arb_matrix(k, n)).prop_map(move |(j, m)| (k, n, j, m))
1494 })
1495 }
1496
1497 fn widen_args() -> impl Strategy<Value = (u8, u8, u8, u8, u64)> {
1498 (1u8..=4, 1u8..=4, 0u8..=3, 0u8..=3)
1499 .prop_filter("fits", |&(k, a, d1, d2)| {
1500 (k as u32) * ((a + d1 + d2) as u32) <= 63
1501 })
1502 .prop_flat_map(|(k, a, d1, d2)| {
1503 arb_matrix(k, a).prop_map(move |m| (k, a, a + d1, a + d1 + d2, m))
1504 })
1505 }
1506
1507 fn add_rows_args() -> impl Strategy<Value = (u8, u8, u8, u64)> {
1508 (1u8..=4, 1u8..=3, 1u8..=5)
1509 .prop_filter("fits", |&(k, extra, n)| {
1510 ((k + extra) as u32) * (n as u32) <= 63
1511 })
1512 .prop_flat_map(|(k, extra, n)| arb_matrix(k, n).prop_map(move |m| (k, extra, n, m)))
1513 }
1514
1515 fn perm_args() -> impl Strategy<Value = (u8, u8, u64, Vec<u8>)> {
1516 (1u8..=5, 1u8..=5)
1517 .prop_filter("fits", |&(k, n)| (k as u32) * (n as u32) <= 63)
1518 .prop_flat_map(|(k, n)| {
1519 (arb_matrix(k, n), arb_perm(k)).prop_map(move |(m, p)| (k, n, m, p))
1520 })
1521 }
1522
1523 proptest! {
1526 #[test]
1528 fn prop_identity_left((k, n, m) in dims_and_matrix()) {
1529 let id = identity(n, n);
1530 prop_assert_eq!(compose(id, m, k, n, n), m);
1531 }
1532
1533 #[test]
1535 fn prop_identity_right((k, n, m) in dims_and_matrix()) {
1536 let id = identity(k, k);
1537 prop_assert_eq!(compose(m, id, k, k, n), m);
1538 }
1539
1540 #[test]
1542 fn prop_compose_associative((ka, kb, kc, nd, a, b, c) in three_composable()) {
1543 let ab = compose(a, b, ka, kb, nd);
1544 let bc = compose(b, c, kc, ka, kb);
1545 prop_assert_eq!(compose(ab, c, kc, ka, nd), compose(a, bc, kc, kb, nd));
1546 }
1547
1548 #[test]
1550 fn prop_compose_embed_subset((ki, km, no, outer, inner) in two_composable()) {
1551 let composed = compose(outer, inner, ki, km, no);
1552 prop_assert_eq!(embed_bitset(composed, ki, no) & !embed_bitset(outer, km, no), 0);
1553 }
1554
1555 #[test]
1557 fn prop_widen_transitive((k, a, b, c, m) in widen_args()) {
1558 let step = widen_columns(widen_columns(m, k, a, b), k, b, c);
1559 prop_assert_eq!(step, widen_columns(m, k, a, c));
1560 }
1561
1562 #[test]
1564 fn prop_shift_structure((k, n, d, m) in shift_args()) {
1565 let s = shift(m, k, n, d);
1566 let nn = n + d;
1567 for i in 0..d {
1568 prop_assert_eq!(row_extract(s, i, nn), 0);
1569 }
1570 for i in 0..k {
1571 prop_assert_eq!(row_extract(s, d + i, nn), row_extract(m, i, n) << d);
1572 }
1573 }
1574
1575 #[test]
1577 fn prop_permute_preserves_embed((k, n, m, p) in perm_args()) {
1578 prop_assert_eq!(embed_bitset(permute_rows(m, &p, k, n), k, n), embed_bitset(m, k, n));
1579 }
1580
1581 #[test]
1583 fn prop_permute_inverse((k, n, m, p) in perm_args()) {
1584 let mut inv = vec![0u8; k as usize];
1585 for (i, &pi) in p.iter().enumerate() { inv[pi as usize] = i as u8; }
1586 prop_assert_eq!(permute_rows(permute_rows(m, &p, k, n), &inv, k, n), m);
1587 }
1588
1589 #[test]
1591 fn prop_delete_preserves_injection((k, n, j, m) in delete_args()) {
1592 let d = delete_column(m, j, k, n);
1593 for i in 0..k {
1594 prop_assert!(row_extract(d, i, n - 1).count_ones() <= 1);
1595 }
1596 }
1597
1598 #[test]
1600 fn prop_compose_preserves_injection((ki, km, no, outer, inner) in two_composable()) {
1601 let c = compose(outer, inner, ki, km, no);
1602 for i in 0..ki {
1603 prop_assert!(row_extract(c, i, no).count_ones() <= 1);
1604 }
1605 }
1606
1607 #[test]
1609 fn prop_delete_column_remaps((k, n, j, m) in delete_args()) {
1610 let d = delete_column(m, j, k, n);
1611 for jp in 0..n-1 {
1612 let orig = if jp < j { jp } else { jp + 1 };
1613 prop_assert_eq!(col_present(d, jp, k, n-1), col_present(m, orig, k, n));
1614 }
1615 }
1616
1617 #[test]
1619 fn prop_add_rows_structure((k, extra, n, m) in add_rows_args()) {
1620 let r = add_zero_rows(m, k, k + extra, n);
1621 for i in 0..k {
1622 prop_assert_eq!(row_extract(r, i, n), row_extract(m, i, n));
1623 }
1624 for i in k..k+extra {
1625 prop_assert_eq!(row_extract(r, i, n), 0);
1626 }
1627 }
1628
1629 #[test]
1631 fn prop_shift_delete_roundtrip((k, n, d, m) in shift_args()) {
1632 let mut s = shift(m, k, n, d);
1633 let mut ck = k + d;
1634 let mut cn = n + d;
1635 for _ in 0..d {
1636 s = delete_column(s, 0, ck, cn);
1637 cn -= 1;
1638 let mut rebuilt = 0u64;
1639 for i in 1..ck {
1640 rebuilt |= row_extract(s, i, cn) << (((i-1) as u32) * (cn as u32));
1641 }
1642 s = rebuilt;
1643 ck -= 1;
1644 }
1645 prop_assert_eq!(s, m);
1646 }
1647 }
1648 }
1649}