entropyfs 0.4.0

Entropy-native Linux filesystem: persist irreducible state, materialize structure, preserve exact bytes.
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
//! Representation descriptors and the residual algebra.
//!
//! The defining equation: `X = Materialize(D)` where `X` is the exact
//! logical byte sequence and `D` is the persisted representation descriptor.
//! This module defines `D` (in-memory form) and the exact, bounded,
//! non-Turing-complete descriptor language (ADR-0005).

#![forbid(unsafe_code)]

use crate::core::extent::ChunkId;

/// rANS codec variants supported in v1.
///
/// All codecs share the upstream bitstream contract
/// (`docs/theory/rans-state.md`); the scalar paths are the authority.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum RansCodec {
    /// Single-state byte rANS.
    Single = 0,
    /// Two-state interleaved byte rANS.
    Interleaved2 = 1,
}

impl RansCodec {
    /// Decode the persisted codec tag.
    pub fn from_u8(v: u8) -> Option<Self> {
        match v {
            0 => Some(Self::Single),
            1 => Some(Self::Interleaved2),
            _ => None,
        }
    }

    /// Persisted tag.
    pub const fn tag(self) -> u8 {
        self as u8
    }
}

/// Entropy universe identifiers (registry is part of the format).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum UniverseId {
    /// Uniform XOF v1 — deterministic BLAKE3-based expander. This is the
    /// Phase-1 **negative control** universe (ADR-0005): it establishes
    /// that a random implicit dictionary does not create free compression
    /// once selector cost is included.
    UniformXofV1 = 0x01,
}

impl UniverseId {
    /// Decode a persisted universe id.
    pub fn from_u8(v: u8) -> Option<Self> {
        match v {
            0x01 => Some(Self::UniformXofV1),
            _ => None,
        }
    }

    /// Persisted tag.
    pub const fn tag(self) -> u8 {
        self as u8
    }
}

/// Bounded deterministic reversible transform identifiers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum TransformId {
    /// Identity.
    Identity = 0x00,
}

impl TransformId {
    /// Decode a persisted transform id.
    pub fn from_u8(v: u8) -> Option<Self> {
        match v {
            0x00 => Some(Self::Identity),
            _ => None,
        }
    }

    /// Persisted tag.
    pub const fn tag(self) -> u8 {
        self as u8
    }
}

/// One edited position for [`Residual::XorSparse`]: byte at `pos` of the
/// target equals `base[pos] ^ val`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Edit {
    /// Position within the residual (0-based).
    pub pos: u32,
    /// XOR difference value.
    pub val: u8,
}

/// One changed range for [`Residual::RangeReplace`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RangeChange {
    /// Inclusive start of the replaced range.
    pub start: u32,
    /// Exclusive end of the replaced range.
    pub end: u32,
}

/// Exact residual forms for base+residual and entropy+residual
/// representations (`docs/adr/0005-representation-set.md`).
///
/// Semantics: for target `X`, base `B` (both of length `len`):
///
/// - `XorSparse`: `X[i] = B[i] ^ val` at edit positions; `X[i] = B[i]`
///   elsewhere.
/// - `RangeReplace`: `X[start..end] = literals` in order; elsewhere
///   `X[i] = B[i]`.
/// - `RansCoded`: the encoded stream decodes to `decoded_len` bytes `D`;
///   `X[i] = B[i] ^ D[i]`.
/// - `BaseSequence`: the output `X` is built by walking a command stream
///   — COPY(base_offset, len) copies from the base, LITERAL(run) appends
///   literal bytes. Shift-aware: inserted/deleted regions do not break it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Residual {
    /// Sparse XOR edit set.
    XorSparse {
        /// Length of the residual in bytes (== chunk length).
        len: u64,
        /// Sorted, non-overlapping edits (positions strictly increasing).
        edits: Vec<Edit>,
    },
    /// Non-overlapping replaced ranges.
    RangeReplace {
        /// Length of the residual in bytes.
        len: u64,
        /// Sorted, non-overlapping changes.
        changes: Vec<RangeChange>,
        /// Concatenated replacement literals (total == Σ(end−start)).
        literals: Vec<u8>,
    },
    /// rANS-coded XOR difference stream.
    RansCoded {
        /// Length of the residual in bytes (== chunk length).
        len: u64,
        /// Content id of the encoded stream object.
        enc_obj: ChunkId,
        /// Content id of the rANS model object.
        model: ChunkId,
        /// Model scale bits.
        scale_bits: u8,
        /// Codec used for the stream.
        codec: RansCodec,
        /// Decoded stream length.
        decoded_len: u64,
    },
    /// Shift-aware copy/literal delta against the base (Phase-8 §5).
    ///
    /// Command stream (one byte per command): `0x00..=0x7F` is a literal
    /// run of `b + 1` (1..=128) bytes from the literal stream;
    /// `0x80..=0xFF` is a copy of `b - 0x80 + 4` (4..=131) bytes from the
    /// base at a u32 LE base offset (next 4 bytes of the offset stream).
    /// The output is built by appending: literals verbatim, copies from
    /// `base[off..off+len]` (validated against the base length).
    BaseSequence {
        /// Length of the residual in bytes (== chunk length).
        len: u64,
        /// Content id of the encoded object (3 concatenated streams).
        enc_obj: ChunkId,
        /// Content id of the model object (3 slots, same codec as
        /// SEQUENCE_RANS).
        model: ChunkId,
        /// Model scale bits.
        scale_bits: u8,
        /// Codec used for the streams.
        codec: RansCodec,
        /// Encoded command-stream length.
        seq_len: u32,
        /// Encoded literal-stream length.
        lit_len: u32,
        /// Encoded offset-stream length.
        off_len: u32,
        /// Decoded command count.
        cmds: u32,
        /// Decoded literal byte count.
        lit_out: u32,
    },
}

/// The representation descriptor set, v1 (ADR-0005).
///
/// Every variant's `len` is the exact materialized output length. All
/// arithmetic on these values is checked at parse and materialization time;
/// a malformed descriptor yields a typed error, never a panic.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Representation {
    /// All-zero extent.
    Zero {
        /// Materialized length in bytes.
        len: u64,
    },
    /// Single repeated byte.
    Fill {
        /// The repeated byte value.
        value: u8,
        /// Materialized length in bytes.
        len: u64,
    },
    /// Short literal bytes stored inside the descriptor.
    Inline {
        /// The literal bytes.
        data: Vec<u8>,
    },
    /// Literal bytes stored as an object.
    Raw {
        /// Content id of the literal-bytes object.
        obj: ChunkId,
        /// Materialized length in bytes.
        len: u64,
    },
    /// rANS-encoded stream with a persisted model.
    Rans {
        /// Content id of the model object.
        model: ChunkId,
        /// Content id of the encoded stream object.
        enc_obj: ChunkId,
        /// Model scale bits.
        scale_bits: u8,
        /// Codec used for the stream.
        codec: RansCodec,
        /// Materialized length.
        len: u64,
    },
    /// Exact sub-range reference into an existing logical chunk.
    ExactRef {
        /// Target chunk content id (its descriptor resolves via the store's
        /// chunk index).
        target: ChunkId,
        /// Offset into the target chunk.
        off: u64,
        /// Referenced length.
        len: u64,
    },
    /// Base chunk plus exact residual.
    BaseResidual {
        /// Base chunk content id.
        base: ChunkId,
        /// Materialized length of the base chunk (must be >= `len`).
        base_len: u64,
        /// Residual.
        residual: Residual,
        /// Materialized length.
        len: u64,
    },
    /// Combinatorial sparse configuration: `k` marked positions among `len`,
    /// position subset encoded as combination rank, values as literals.
    Sparse {
        /// Number of marked positions.
        k: u32,
        /// Combination rank in `[0, C(len, k))`.
        rank: u128,
        /// Literal value at each marked position (k bytes).
        literals: Vec<u8>,
        /// Materialized length.
        len: u64,
    },
    /// Low-cardinality palette configuration: `m ≤ 16` symbols with counts,
    /// multinomial rank over `n!/(∏c!)`.
    Palette {
        /// Palette symbols (distinct bytes).
        palette: Vec<u8>,
        /// Multiplicity of each palette symbol (sums to `len`).
        counts: Vec<u32>,
        /// Multinomial rank in `[0, n!/(∏c!))`.
        rank: u128,
        /// Materialized length.
        len: u64,
    },
    /// Periodic structure: pattern repeated `count` times plus tail.
    Periodic {
        /// Pattern length.
        period: u32,
        /// Pattern bytes.
        pattern: Vec<u8>,
        /// Number of full repetitions.
        count: u32,
        /// Tail bytes (length `tail_len`, `0 <= tail_len < period`).
        tail: Vec<u8>,
        /// Materialized length (= period*count + tail.len()).
        len: u64,
    },
    /// Permutation of `m ≤ 34` distinct bytes, encoded by factoradic rank
    /// over the sorted distinct symbols.
    Permutation {
        /// Factoradic rank in `[0, m!)`.
        rank: u128,
        /// The sorted distinct symbols (length == m == len).
        alphabet: Vec<u8>,
        /// Materialized length (== m, ≤ 34).
        len: u64,
    },
    /// Entropy universe reference: `X = T(E(U, S, P)) ⊕ R`.
    EntropyRef {
        /// Universe.
        universe: UniverseId,
        /// Seed/state.
        seed: [u8; 16],
        /// Coordinate.
        coordinate: u64,
        /// Transform.
        transform: TransformId,
        /// Exact residual (may be empty for exact matches).
        residual: Residual,
        /// Materialized length.
        len: u64,
    },
    /// Local match coding + entropy: LZ77-style COPY/LITERAL token streams
    /// entropy-coded with ryg-rans-rs (the general-purpose compression
    /// floor, Phase-8 directive §4).
    ///
    /// Three byte streams, each rANS-coded:
    ///
    /// - *commands*: one byte per command. `0x00..=0x7F` is a literal run
    ///   of length `b + 1` (1..=128); `0x80..=0xFF` is a copy of length
    ///   `b - 0x80 + 4` (4..=131) whose offset (u16 LE) follows in the
    ///   offset stream.
    /// - *literals*: the literal-run bytes, in command order.
    /// - *offsets*: one u16 LE offset per copy command.
    ///
    /// The `model` object holds the three models length-prefixed; the
    /// `enc_obj` holds the three encoded streams concatenated (lengths in
    /// the descriptor). Copy offsets are relative to the current output
    /// position (local history), so the decoder needs only the decoded
    /// output buffer.
    SequenceRans {
        /// Content id of the model object (3 length-prefixed models).
        model: ChunkId,
        /// Content id of the encoded object (3 concatenated streams).
        enc_obj: ChunkId,
        /// Model scale bits (shared by all three streams).
        scale_bits: u8,
        /// Codec used for the streams.
        codec: RansCodec,
        /// Encoded command-stream length (bytes).
        seq_len: u32,
        /// Encoded literal-stream length (bytes).
        lit_len: u32,
        /// Encoded offset-stream length (bytes).
        off_len: u32,
        /// Command count (= decoded command-stream length).
        cmds: u32,
        /// Decoded literal-stream length (total literal bytes).
        lit_out: u32,
        /// Materialized length.
        len: u64,
    },
    /// Blockwise-64 enumerative sparse coding: the chunk's nonzero-byte
    /// positions are coded as 64-bit subblocks — per 64-bit word, its
    /// popcount `k` and the subset rank among `C(64, k)` (which fits a
    /// u64 for every `k`), plus the literal byte values. The three streams
    /// (popcounts, ranks, literals) use the same rANS/raw codec as
    /// SEQUENCE_RANS. This removes the `u128` combination-rank cliff of
    /// SPARSE (which cannot represent `10 <= k <= n-10` for 64 KiB
    /// chunks) while staying bounded, SIMD/popcount-friendly, and
    /// random-accessible per word (Phase-8 directive §6; ADR-0005).
    SparseBlock64 {
        /// Content id of the model object (3 slots).
        model: ChunkId,
        /// Content id of the encoded object (3 concatenated streams).
        enc_obj: ChunkId,
        /// Model scale bits.
        scale_bits: u8,
        /// Codec used for the streams.
        codec: RansCodec,
        /// Encoded popcount-stream length.
        pc_len: u32,
        /// Encoded rank-stream length.
        rank_len: u32,
        /// Encoded literal-stream length.
        lit_len: u32,
        /// Number of 64-bit words (= ceil(len / 8)).
        words: u32,
        /// Number of nonzero words (= decoded rank-stream entries).
        nonzero: u32,
        /// Decoded literal byte count (= total marked bytes).
        lit_out: u32,
        /// Materialized length.
        len: u64,
    },
    /// Cross-chunk dictionary match coding (Phase-9B; ADR-0005): the
    /// SEQUENCE_RANS command semantics plus a fourth *copy-source* stream
    /// (one byte per copy: `SRC_LOCAL` = the u16 value is a backward
    /// distance in the already-materialized output, `SRC_DICT` = it is an
    /// absolute offset into the dictionary chunk). The dictionary is the
    /// previous same-file chunk (v1); it is a content-addressed chunk
    /// reference, so its own persisted state is accounted where it is
    /// materialized, and the reference depth (dictionary chain + 1) is
    /// capped by `max_reference_depth` so cross-chunk dictionary chains
    /// never defeat bounded random access.
    SequenceDict {
        /// Content id of the dictionary chunk.
        dictionary: ChunkId,
        /// Materialized length of the dictionary chunk (≤ 64 KiB; u16
        /// DICT offsets).
        dictionary_len: u32,
        /// Content id of the model object (4 length-prefixed slots).
        model: ChunkId,
        /// Content id of the encoded object (4 concatenated streams:
        /// commands, literals, offsets, copy sources).
        enc_obj: ChunkId,
        /// Model scale bits (shared by all four streams).
        scale_bits: u8,
        /// Codec used for the streams.
        codec: RansCodec,
        /// Encoded command-stream length (bytes).
        seq_len: u32,
        /// Encoded literal-stream length (bytes).
        lit_len: u32,
        /// Encoded offset-stream length (bytes).
        off_len: u32,
        /// Encoded copy-source-stream length (bytes).
        src_len: u32,
        /// Command count (= decoded command-stream length).
        cmds: u32,
        /// Decoded literal-stream length (total literal bytes).
        lit_out: u32,
        /// Materialized length.
        len: u64,
    },
    /// Shared amortized dictionary match coding (Phase-9C; ADR-0005): the
    /// SEQUENCE_RANS command semantics with a fourth *copy-source* stream
    /// whose per-copy byte selects among `SRC_LOCAL` (the u16 value is a
    /// backward distance in the already-materialized output), `SRC_DICT`
    /// (absolute offset into the previous same-file chunk, when present),
    /// and `SRC_SHARED` (absolute offset into a shared cross-file
    /// dictionary chunk). The shared dictionary is a content-addressed
    /// chunk chosen by the background optimizer to amortize structure
    /// common to a file family/directory; it is persisted state (its own
    /// object/chunk is accounted where it is materialized) and its
    /// reference depth is capped by `max_reference_depth` like every other
    /// reference family. `dictionary` may be ZERO (= no file dictionary;
    /// the shared dictionary is then the only external source).
    SequenceSharedDict {
        /// Content id of the previous same-file chunk (ZERO = absent).
        dictionary: ChunkId,
        /// Materialized length of the file dictionary (0 when absent).
        dictionary_len: u32,
        /// Content id of the shared cross-file dictionary chunk (never
        /// ZERO; ≤ 64 KiB so u16 offsets bound it).
        shared: ChunkId,
        /// Materialized length of the shared dictionary.
        shared_len: u32,
        /// Content id of the model object (4 length-prefixed slots).
        model: ChunkId,
        /// Content id of the encoded object (4 concatenated streams:
        /// commands, literals, offsets, copy sources).
        enc_obj: ChunkId,
        /// Model scale bits (shared by all four streams).
        scale_bits: u8,
        /// Codec used for the streams.
        codec: RansCodec,
        /// Encoded command-stream length (bytes).
        seq_len: u32,
        /// Encoded literal-stream length (bytes).
        lit_len: u32,
        /// Encoded offset-stream length (bytes).
        off_len: u32,
        /// Encoded copy-source-stream length (bytes).
        src_len: u32,
        /// Command count (= decoded command-stream length).
        cmds: u32,
        /// Decoded literal-stream length (total literal bytes).
        lit_out: u32,
        /// Materialized length.
        len: u64,
    },
}

impl Representation {
    /// The exact materialized output length of this descriptor.
    pub const fn len(&self) -> u64 {
        match self {
            Representation::Zero { len }
            | Representation::Fill { len, .. }
            | Representation::Raw { len, .. }
            | Representation::Rans { len, .. }
            | Representation::ExactRef { len, .. }
            | Representation::BaseResidual { len, .. }
            | Representation::Sparse { len, .. }
            | Representation::Palette { len, .. }
            | Representation::Periodic { len, .. }
            | Representation::EntropyRef { len, .. }
            | Representation::Permutation { len, .. }
            | Representation::SequenceRans { len, .. }
            | Representation::SparseBlock64 { len, .. }
            | Representation::SequenceDict { len, .. }
            | Representation::SequenceSharedDict { len, .. } => *len,
            Representation::Inline { data } => data.len() as u64,
        }
    }

    /// True for zero-length output (only legal for len 0 representations).
    pub const fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// The persistence tag (mirrors `format/descriptor.rs`).
    pub const fn tag(&self) -> u8 {
        match self {
            Representation::Zero { .. } => 0x01,
            Representation::Fill { .. } => 0x02,
            Representation::Raw { .. } => 0x03,
            Representation::Rans { .. } => 0x04,
            Representation::ExactRef { .. } => 0x05,
            Representation::BaseResidual { .. } => 0x06,
            Representation::Sparse { .. } => 0x07,
            Representation::Palette { .. } => 0x08,
            Representation::Periodic { .. } => 0x09,
            Representation::EntropyRef { .. } => 0x0A,
            Representation::Inline { .. } => 0x0B,
            Representation::Permutation { .. } => 0x0C,
            Representation::SequenceRans { .. } => 0x0D,
            Representation::SparseBlock64 { .. } => 0x0E,
            Representation::SequenceDict { .. } => 0x0F,
            Representation::SequenceSharedDict { .. } => 0x10,
        }
    }

    /// A human-readable family name (for `explain`/`inspect`).
    pub const fn family(&self) -> &'static str {
        match self {
            Representation::Zero { .. } => "ZERO",
            Representation::Fill { .. } => "FILL",
            Representation::Raw { .. } => "RAW",
            Representation::Rans { .. } => "RANS",
            Representation::ExactRef { .. } => "EXACT_REF",
            Representation::BaseResidual { .. } => "BASE_RESIDUAL",
            Representation::Sparse { .. } => "SPARSE",
            Representation::Palette { .. } => "PALETTE",
            Representation::Periodic { .. } => "PERIODIC",
            Representation::EntropyRef { .. } => "ENTROPY_REF",
            Representation::Inline { .. } => "INLINE",
            Representation::Permutation { .. } => "PERMUTATION",
            Representation::SequenceRans { .. } => "SEQUENCE_RANS",
            Representation::SparseBlock64 { .. } => "SPARSE_BLOCK64",
            Representation::SequenceDict { .. } => "SEQUENCE_DICT",
            Representation::SequenceSharedDict { .. } => "SEQUENCE_SHARED_DICT",
        }
    }

    /// Exact encoded descriptor size in bytes, mirroring
    /// `format::descriptor` sizing rules.
    ///
    /// A test in `src/tests/` asserts this equals the real encoder output
    /// length for random descriptors, keeping the mirror in sync.
    pub fn encoded_size(&self) -> u64 {
        // common prefix: tag (1) + len (4)
        let base = 5u64;
        let payload: u64 = match self {
            Representation::Zero { .. } => 0,
            Representation::Fill { .. } => 1,
            Representation::Inline { data } => data.len() as u64,
            Representation::Raw { .. } => 32,
            Representation::Rans { .. } => 32 + 32 + 1 + 1,
            Representation::ExactRef { .. } => 32 + 4,
            Representation::BaseResidual { residual, .. } => 32 + 4 + residual.encoded_size(),
            Representation::Sparse { literals, .. } => 4 + 16 + literals.len() as u64,
            Representation::Palette {
                palette, counts, ..
            } => 1 + palette.len() as u64 + 4 * counts.len() as u64 + 16,
            Representation::Periodic {
                period,
                pattern: _,
                tail,
                ..
            } => 4 + *period as u64 + 4 + 4 + tail.len() as u64,
            Representation::EntropyRef { residual, .. } => 1 + 16 + 8 + 1 + residual.encoded_size(),
            Representation::Permutation { alphabet, .. } => 16 + alphabet.len() as u64,
            Representation::SequenceRans { .. } => 32 + 32 + 1 + 1 + 4 + 4 + 4 + 4 + 4,
            Representation::SparseBlock64 { .. } => 32 + 32 + 1 + 1 + 4 + 4 + 4 + 4 + 4 + 4,
            // dictionary id + dictionary_len + model + enc + scale + codec
            // + seq/lit/off/src/cmds/lit_out.
            Representation::SequenceDict { .. } => 32 + 4 + 32 + 32 + 1 + 1 + 4 + 4 + 4 + 4 + 4 + 4,
            // file dict id + file dict len + shared id + shared len + model
            // + enc + scale + codec + seq/lit/off/src/cmds/lit_out.
            Representation::SequenceSharedDict { .. } => {
                32 + 4 + 32 + 4 + 32 + 32 + 1 + 1 + 4 + 4 + 4 + 4 + 4 + 4
            }
        };
        base + payload
    }

    /// Validate structural invariants that do not require external
    /// resolution: lengths, palette consistency, periodic arithmetic,
    /// inline size, reference sanity, and the encoded descriptor size
    /// (a descriptor that exceeds `max_descriptor_bytes` could win on raw
    /// byte cost yet be undecodable — every persisted descriptor must
    /// decode).
    pub fn validate(&self, limits: &crate::core::limits::Limits) -> Result<(), ReprError> {
        if self.encoded_size() > limits.max_descriptor_bytes {
            return Err(ReprError::DescriptorTooLarge);
        }
        match self {
            Representation::Zero { len } => {
                check_len(*len, limits)?;
            }
            Representation::Fill { len, .. } => {
                check_len(*len, limits)?;
            }
            Representation::Inline { data } => {
                if data.len() as u64 > limits.max_inline_bytes {
                    return Err(ReprError::InlineTooLarge);
                }
            }
            Representation::Raw { obj, len } => {
                check_len(*len, limits)?;
                if obj.is_zero() {
                    return Err(ReprError::ZeroObjectId);
                }
            }
            Representation::Rans {
                model,
                enc_obj,
                scale_bits,
                len,
                ..
            } => {
                check_len(*len, limits)?;
                if model.is_zero() || enc_obj.is_zero() {
                    return Err(ReprError::ZeroObjectId);
                }
                if !(1..=16).contains(scale_bits) {
                    return Err(ReprError::BadScaleBits);
                }
            }
            Representation::ExactRef { target, off, len } => {
                check_len(*len, limits)?;
                if target.is_zero() {
                    return Err(ReprError::ZeroObjectId);
                }
                if off.checked_add(*len).is_none() {
                    return Err(ReprError::Overflow);
                }
            }
            Representation::BaseResidual {
                base,
                base_len,
                residual,
                len,
            } => {
                check_len(*len, limits)?;
                if base.is_zero() {
                    return Err(ReprError::ZeroObjectId);
                }
                // Copy/literal deltas (BaseSequence) may reference a base
                // shorter or longer than the target (insertions/deletions);
                // positional residuals require base >= target.
                if !matches!(residual, Residual::BaseSequence { .. }) && *base_len < *len {
                    return Err(ReprError::BaseTooShort);
                }
                residual.validate(*len, limits)?;
            }
            Representation::Sparse {
                k,
                rank,
                literals,
                len,
            } => {
                check_len(*len, limits)?;
                let k64 = *k as u64;
                if k64 > *len {
                    return Err(ReprError::SparseKTooLarge);
                }
                if literals.len() as u64 != k64 {
                    return Err(ReprError::SparseLiteralCount);
                }
                // rank must be < C(len, k)
                match crate::entropy::rank::comb(*len as u128, k64 as u128) {
                    Some(total) if *rank < total => {}
                    Some(_) => return Err(ReprError::SparseRankOutOfRange),
                    None => return Err(ReprError::CombOverflow),
                }
            }
            Representation::Palette {
                palette,
                counts,
                rank,
                len,
            } => {
                check_len(*len, limits)?;
                if palette.is_empty() || palette.len() > limits.max_palette {
                    return Err(ReprError::BadPalette);
                }
                if counts.len() != palette.len() {
                    return Err(ReprError::BadPalette);
                }
                let mut total: u64 = 0;
                for &c in counts.iter() {
                    total = total.checked_add(c as u64).ok_or(ReprError::Overflow)?;
                }
                if total != *len {
                    return Err(ReprError::PaletteCountsMismatch);
                }
                // Every symbol must have a nonzero count (canonical form).
                if counts.contains(&0) {
                    return Err(ReprError::BadPalette);
                }
                match crate::entropy::rank::multinomial(*len, counts) {
                    Some(total_states) if *rank < total_states => {}
                    Some(_) => return Err(ReprError::PaletteRankOutOfRange),
                    None => return Err(ReprError::CombOverflow),
                }
            }
            Representation::Periodic {
                period,
                pattern,
                count,
                tail,
                len,
            } => {
                check_len(*len, limits)?;
                if *period == 0 || *period as u64 > limits.max_period as u64 {
                    return Err(ReprError::BadPeriod);
                }
                if pattern.len() as u64 != *period as u64 {
                    return Err(ReprError::BadPeriod);
                }
                if tail.len() as u64 >= *period as u64 {
                    return Err(ReprError::BadTail);
                }
                let expected = (*period as u64)
                    .checked_mul(*count as u64)
                    .and_then(|v| v.checked_add(tail.len() as u64))
                    .ok_or(ReprError::Overflow)?;
                if expected != *len {
                    return Err(ReprError::PeriodicLenMismatch);
                }
            }
            Representation::EntropyRef {
                universe,
                seed: _,
                coordinate: _,
                transform,
                residual,
                len,
            } => {
                check_len(*len, limits)?;
                // Unknown universe/transform ids are typed errors (registry
                // part of the format, ADR compatibility rules).
                if *universe == crate::core::representation::UniverseId::UniformXofV1 {
                    // known
                } else {
                    return Err(ReprError::UnknownUniverse);
                }
                if *transform != crate::core::representation::TransformId::Identity {
                    return Err(ReprError::UnknownTransform);
                }
                residual.validate(*len, limits)?;
            }
            Representation::Permutation {
                rank,
                alphabet,
                len,
            } => {
                check_len(*len, limits)?;
                let m = *len;
                if m == 0 || m > 34 {
                    return Err(ReprError::PermutationSize);
                }
                if alphabet.len() as u64 != m {
                    return Err(ReprError::BadPermutationAlphabet);
                }
                // alphabet must be strictly increasing (canonical form).
                for w in alphabet.windows(2) {
                    if w[0] >= w[1] {
                        return Err(ReprError::BadPermutationAlphabet);
                    }
                }
                let total =
                    crate::entropy::rank::factorial(m as u128).ok_or(ReprError::CombOverflow)?;
                if *rank >= total {
                    return Err(ReprError::PermutationRankOutOfRange);
                }
            }
            Representation::SequenceRans {
                model,
                enc_obj,
                scale_bits,
                seq_len,
                lit_len,
                off_len,
                cmds,
                lit_out,
                len,
                ..
            } => {
                check_len(*len, limits)?;
                if model.is_zero() || enc_obj.is_zero() {
                    return Err(ReprError::ZeroObjectId);
                }
                if !(1..=16).contains(scale_bits) {
                    return Err(ReprError::BadScaleBits);
                }
                // Stream-length sanity: every byte is bounded by the chunk
                // class (streams cannot exceed the materialized size plus
                // a generous constant), and a copy needs at least one
                // command. `lit_out` must be <= len (literals are a subset
                // of the output).
                let max_stream = limits.max_chunk_size.saturating_add(64);
                for s in [*seq_len, *lit_len, *off_len] {
                    if s as u64 > max_stream {
                        return Err(ReprError::SequenceStreamTooLarge);
                    }
                }
                if (*lit_out as u64) > *len {
                    return Err(ReprError::SequenceLitOutMismatch);
                }
                if *cmds == 0 && *len > 0 {
                    return Err(ReprError::SequenceNoCommands);
                }
                // Every command writes at least one byte, so the command
                // count cannot exceed the output length (bounds the decode
                // allocation for the command stream).
                if (*cmds as u64) > *len {
                    return Err(ReprError::SequenceCmdsMismatch);
                }
            }
            Representation::SparseBlock64 {
                model,
                enc_obj,
                scale_bits,
                pc_len,
                rank_len,
                lit_len,
                words,
                nonzero,
                lit_out,
                len,
                ..
            } => {
                check_len(*len, limits)?;
                if model.is_zero() || enc_obj.is_zero() {
                    return Err(ReprError::ZeroObjectId);
                }
                if !(1..=16).contains(scale_bits) {
                    return Err(ReprError::BadScaleBits);
                }
                let max_stream = limits.max_chunk_size.saturating_add(64);
                for s in [*pc_len, *rank_len, *lit_len] {
                    if s as u64 > max_stream {
                        return Err(ReprError::SequenceStreamTooLarge);
                    }
                }
                // Word count must cover the output: words*8 >= len.
                if (*words as u64).saturating_mul(8) < *len {
                    return Err(ReprError::SparseBlockWords);
                }
                if (*nonzero as u64) > *words as u64 {
                    return Err(ReprError::SparseBlockWords);
                }
                if (*lit_out as u64) > *len {
                    return Err(ReprError::SequenceLitOutMismatch);
                }
                // Every marked byte carries a literal; the rank stream is
                // 8 bytes per nonzero word. Each nonzero word has >= 1
                // marked byte, so nonzero <= lit_out.
                if (*nonzero as u64) > *lit_out as u64 {
                    return Err(ReprError::SparseBlockLiteralCount);
                }
            }
            Representation::SequenceDict {
                dictionary,
                dictionary_len,
                model,
                enc_obj,
                scale_bits,
                seq_len,
                lit_len,
                off_len,
                src_len,
                cmds,
                lit_out,
                len,
                ..
            } => {
                check_len(*len, limits)?;
                if dictionary.is_zero() || model.is_zero() || enc_obj.is_zero() {
                    return Err(ReprError::ZeroObjectId);
                }
                if !(1..=16).contains(scale_bits) {
                    return Err(ReprError::BadScaleBits);
                }
                // DICT offsets are u16: the dictionary must be non-empty
                // and at most 64 KiB, and it is a logical chunk, so it
                // cannot exceed the chunk-class bound either.
                if *dictionary_len == 0
                    || *dictionary_len as u64 > crate::rans::sequence::MAX_DICT as u64
                    || *dictionary_len as u64 > limits.max_chunk_size
                {
                    return Err(ReprError::BadDictionary);
                }
                let max_stream = limits.max_chunk_size.saturating_add(64);
                for s in [*seq_len, *lit_len, *off_len, *src_len] {
                    if s as u64 > max_stream {
                        return Err(ReprError::SequenceStreamTooLarge);
                    }
                }
                if (*lit_out as u64) > *len {
                    return Err(ReprError::SequenceLitOutMismatch);
                }
                if *cmds == 0 && *len > 0 {
                    return Err(ReprError::SequenceNoCommands);
                }
                // Every command writes at least one byte, so the command
                // count cannot exceed the output length.
                if (*cmds as u64) > *len {
                    return Err(ReprError::SequenceCmdsMismatch);
                }
            }
            Representation::SequenceSharedDict {
                dictionary,
                dictionary_len,
                shared,
                shared_len,
                model,
                enc_obj,
                scale_bits,
                seq_len,
                lit_len,
                off_len,
                src_len,
                cmds,
                lit_out,
                len,
                ..
            } => {
                check_len(*len, limits)?;
                // The shared dictionary is mandatory; the file dictionary
                // is optional (ZERO id + zero length = absent).
                if shared.is_zero() || model.is_zero() || enc_obj.is_zero() {
                    return Err(ReprError::ZeroObjectId);
                }
                if !(1..=16).contains(scale_bits) {
                    return Err(ReprError::BadScaleBits);
                }
                if *shared_len == 0
                    || *shared_len as u64 > crate::rans::sequence::MAX_DICT as u64
                    || *shared_len as u64 > limits.max_chunk_size
                {
                    return Err(ReprError::BadDictionary);
                }
                // The optional file dictionary must be self-consistent.
                let file_absent = dictionary.is_zero() && *dictionary_len == 0;
                let file_present = !dictionary.is_zero()
                    && *dictionary_len > 0
                    && *dictionary_len as u64 <= crate::rans::sequence::MAX_DICT as u64
                    && *dictionary_len as u64 <= limits.max_chunk_size;
                if !file_absent && !file_present {
                    return Err(ReprError::BadDictionary);
                }
                let max_stream = limits.max_chunk_size.saturating_add(64);
                for s in [*seq_len, *lit_len, *off_len, *src_len] {
                    if s as u64 > max_stream {
                        return Err(ReprError::SequenceStreamTooLarge);
                    }
                }
                if (*lit_out as u64) > *len {
                    return Err(ReprError::SequenceLitOutMismatch);
                }
                if *cmds == 0 && *len > 0 {
                    return Err(ReprError::SequenceNoCommands);
                }
                if (*cmds as u64) > *len {
                    return Err(ReprError::SequenceCmdsMismatch);
                }
            }
        }
        Ok(())
    }
}

fn check_len(len: u64, limits: &crate::core::limits::Limits) -> Result<(), ReprError> {
    if len > limits.max_chunk_size {
        return Err(ReprError::ChunkTooLarge);
    }
    Ok(())
}

impl Residual {
    /// Length of the residual in bytes.
    pub const fn len(&self) -> u64 {
        match self {
            Residual::XorSparse { len, .. }
            | Residual::RangeReplace { len, .. }
            | Residual::RansCoded { len, .. }
            | Residual::BaseSequence { len, .. } => *len,
        }
    }

    /// Whether the residual covers zero bytes.
    pub const fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Encoded size in bytes, mirroring `format::descriptor` sizing.
    pub fn encoded_size(&self) -> u64 {
        match self {
            Residual::XorSparse { edits, .. } => 1 + 4 + 5 * edits.len() as u64,
            Residual::RangeReplace {
                changes, literals, ..
            } => 1 + 4 + 8 * changes.len() as u64 + literals.len() as u64,
            Residual::RansCoded { .. } => 1 + 32 + 32 + 1 + 1 + 4,
            Residual::BaseSequence { .. } => 1 + 32 + 32 + 1 + 1 + 4 + 4 + 4 + 4 + 4,
        }
    }

    /// Validate structural invariants against the representation length.
    pub fn validate(
        &self,
        repr_len: u64,
        limits: &crate::core::limits::Limits,
    ) -> Result<(), ReprError> {
        if self.len() != repr_len {
            return Err(ReprError::ResidualLenMismatch);
        }
        match self {
            Residual::XorSparse { edits, .. } => {
                if edits.len() as u64 > limits.max_fanout as u64 {
                    return Err(ReprError::FanoutTooLarge);
                }
                let mut prev: Option<u32> = None;
                for e in edits {
                    if e.pos as u64 >= repr_len {
                        return Err(ReprError::EditOutOfRange);
                    }
                    if let Some(p) = prev {
                        if e.pos <= p {
                            return Err(ReprError::EditsNotSorted);
                        }
                    }
                    prev = Some(e.pos);
                }
            }
            Residual::RangeReplace {
                changes, literals, ..
            } => {
                if changes.len() as u64 > limits.max_fanout as u64 {
                    return Err(ReprError::FanoutTooLarge);
                }
                let mut expected_lits: u64 = 0;
                let mut prev: Option<u32> = None;
                for c in changes {
                    if c.start >= c.end || c.end as u64 > repr_len {
                        return Err(ReprError::RangeOutOfRange);
                    }
                    if let Some(p) = prev {
                        if c.start <= p {
                            return Err(ReprError::RangesOverlap);
                        }
                    }
                    prev = Some(c.end);
                    expected_lits = expected_lits
                        .checked_add((c.end - c.start) as u64)
                        .ok_or(ReprError::Overflow)?;
                }
                if literals.len() as u64 != expected_lits {
                    return Err(ReprError::LiteralCountMismatch);
                }
            }
            Residual::RansCoded {
                enc_obj,
                model,
                scale_bits,
                decoded_len,
                ..
            } => {
                if enc_obj.is_zero() || model.is_zero() {
                    return Err(ReprError::ZeroObjectId);
                }
                if !(1..=16).contains(scale_bits) {
                    return Err(ReprError::BadScaleBits);
                }
                if *decoded_len != repr_len {
                    return Err(ReprError::ResidualLenMismatch);
                }
            }
            Residual::BaseSequence {
                enc_obj,
                model,
                scale_bits,
                seq_len,
                lit_len,
                off_len,
                cmds,
                lit_out,
                ..
            } => {
                if enc_obj.is_zero() || model.is_zero() {
                    return Err(ReprError::ZeroObjectId);
                }
                if !(1..=16).contains(scale_bits) {
                    return Err(ReprError::BadScaleBits);
                }
                // Stream-length sanity: bounded by the chunk class.
                let max_stream = limits.max_chunk_size.saturating_add(64);
                for s in [*seq_len, *lit_len, *off_len] {
                    if s as u64 > max_stream {
                        return Err(ReprError::SequenceStreamTooLarge);
                    }
                }
                // Literals are a subset of the output; every command
                // writes at least one byte, so the command count cannot
                // exceed the output length.
                if (*lit_out as u64) > repr_len {
                    return Err(ReprError::SequenceLitOutMismatch);
                }
                if *cmds == 0 && repr_len > 0 {
                    return Err(ReprError::SequenceNoCommands);
                }
                if (*cmds as u64) > repr_len {
                    return Err(ReprError::SequenceCmdsMismatch);
                }
            }
        }
        Ok(())
    }
}

/// Typed representation validation errors.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReprError {
    /// Logical length exceeds the format maximum.
    ChunkTooLarge,
    /// Zero content id where an object reference is required.
    ZeroObjectId,
    /// Scale bits outside 1..=16.
    BadScaleBits,
    /// Arithmetic overflow in a length/rank computation.
    Overflow,
    /// Base chunk shorter than the representation length.
    BaseTooShort,
    /// Residual length differs from representation length.
    ResidualLenMismatch,
    /// Edit position out of range.
    EditOutOfRange,
    /// Edits not strictly increasing.
    EditsNotSorted,
    /// Range out of range or degenerate.
    RangeOutOfRange,
    /// Ranges overlap or are not sorted.
    RangesOverlap,
    /// Literal byte count mismatch.
    LiteralCountMismatch,
    /// Too many edits/changes for the format limits.
    FanoutTooLarge,
    /// Sparse k exceeds length.
    SparseKTooLarge,
    /// Sparse literal count does not match k.
    SparseLiteralCount,
    /// Sparse rank out of range.
    SparseRankOutOfRange,
    /// Combination arithmetic overflowed u128 (candidate not representable).
    CombOverflow,
    /// Palette is empty, too large, or has zero-count symbols.
    BadPalette,
    /// Palette counts do not sum to the representation length.
    PaletteCountsMismatch,
    /// Palette rank out of range.
    PaletteRankOutOfRange,
    /// Invalid period or pattern length.
    BadPeriod,
    /// Tail length not < period.
    BadTail,
    /// Periodic arithmetic does not match declared length.
    PeriodicLenMismatch,
    /// INLINE exceeds the format limit.
    InlineTooLarge,
    /// Unknown universe id (registry is format-part).
    UnknownUniverse,
    /// Unknown transform id.
    UnknownTransform,
    /// Encoded descriptor exceeds the format limit.
    DescriptorTooLarge,
    /// Permutation length must be in 1..=34.
    PermutationSize,
    /// Permutation rank out of range.
    PermutationRankOutOfRange,
    /// Permutation alphabet must be strictly increasing with length == m.
    BadPermutationAlphabet,
    /// SEQUENCE_RANS encoded stream exceeds the format limit.
    SequenceStreamTooLarge,
    /// SEQUENCE_RANS literal output exceeds the materialized length.
    SequenceLitOutMismatch,
    /// SEQUENCE_RANS with no commands for a non-empty extent.
    SequenceNoCommands,
    /// SEQUENCE_RANS command count exceeds the materialized length.
    SequenceCmdsMismatch,
    /// SPARSE_BLOCK64 word count does not cover the output or exceeds the
    /// nonzero count.
    SparseBlockWords,
    /// SPARSE_BLOCK64 literal count is inconsistent with the marked bytes.
    SparseBlockLiteralCount,
    /// SEQUENCE_DICT dictionary length is zero, exceeds 64 KiB (u16 DICT
    /// offsets), or exceeds the chunk-class bound.
    BadDictionary,
}

impl std::fmt::Display for ReprError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{self:?}")
    }
}

impl std::error::Error for ReprError {}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::limits::Limits;

    fn l() -> Limits {
        Limits::default()
    }

    #[test]
    fn zero_valid() {
        let r = Representation::Zero { len: 65536 };
        assert_eq!(r.len(), 65536);
        assert_eq!(r.tag(), 0x01);
        r.validate(&l()).unwrap();
    }

    #[test]
    fn zero_too_large_rejected() {
        let r = Representation::Zero { len: 1 << 40 };
        assert_eq!(r.validate(&l()), Err(ReprError::ChunkTooLarge));
    }

    #[test]
    fn periodic_validation() {
        // period 4, pattern "abcd", count 3, tail "xy" => len 14
        let r = Representation::Periodic {
            period: 4,
            pattern: b"abcd".to_vec(),
            count: 3,
            tail: b"xy".to_vec(),
            len: 14,
        };
        r.validate(&l()).unwrap();

        // wrong len
        let bad = Representation::Periodic {
            period: 4,
            pattern: b"abcd".to_vec(),
            count: 3,
            tail: b"xy".to_vec(),
            len: 15,
        };
        assert_eq!(bad.validate(&l()), Err(ReprError::PeriodicLenMismatch));
    }

    #[test]
    fn sparse_validation() {
        // n = 8, k = 3: C(8,3) = 56
        let r = Representation::Sparse {
            k: 3,
            rank: 55,
            literals: vec![1, 2, 3],
            len: 8,
        };
        r.validate(&l()).unwrap();
        let bad = Representation::Sparse {
            k: 3,
            rank: 56,
            literals: vec![1, 2, 3],
            len: 8,
        };
        assert_eq!(bad.validate(&l()), Err(ReprError::SparseRankOutOfRange));
    }

    #[test]
    fn residual_edits_sorted() {
        let res = Residual::XorSparse {
            len: 8,
            edits: vec![Edit { pos: 5, val: 1 }, Edit { pos: 3, val: 2 }],
        };
        assert_eq!(res.validate(8, &l()), Err(ReprError::EditsNotSorted));
    }
}