rust-j2k 0.5.0

Decodes JPEG 2000 images in pure Rust, for programs that need to read them without linking a C 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
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
//! The MQ arithmetic decoder (ISO/IEC 15444-1 Annex C; identical coder to
//! JBIG2). A binary arithmetic decoder driven by a per-context probability
//! state. `decode(cx)` returns one bit (the "decision") and updates that
//! context's state via the standard transition table.

/// One row of the MQ probability estimation state machine (ISO Table C-2):
/// the LPS probability estimate `qe`, the next-state indices on MPS/LPS
/// renormalization, and whether an LPS exchange flips the MPS sense.
#[derive(Debug, Clone, Copy)]
pub struct QeEntry {
    pub qe: u16,
    pub next_mps: u8,
    pub next_lps: u8,
    pub switch: bool,
}

/// The 47-entry MQ state table (ISO/IEC 15444-1 Table C-2), identical to the
/// constants in OpenJPEG's `mqc_states`. Indexed by a context's row; each row
/// gives the LPS probability `qe`, the next state on an MPS- or LPS-driven
/// renormalization, and whether an LPS exchange flips the MPS sense (`switch`).
#[rustfmt::skip]
pub const QE_TABLE: &[QeEntry] = &[
    QeEntry { qe: 0x5601, next_mps:  1, next_lps:  1, switch: true  },
    QeEntry { qe: 0x3401, next_mps:  2, next_lps:  6, switch: false },
    QeEntry { qe: 0x1801, next_mps:  3, next_lps:  9, switch: false },
    QeEntry { qe: 0x0ac1, next_mps:  4, next_lps: 12, switch: false },
    QeEntry { qe: 0x0521, next_mps:  5, next_lps: 29, switch: false },
    QeEntry { qe: 0x0221, next_mps: 38, next_lps: 33, switch: false },
    QeEntry { qe: 0x5601, next_mps:  7, next_lps:  6, switch: true  },
    QeEntry { qe: 0x5401, next_mps:  8, next_lps: 14, switch: false },
    QeEntry { qe: 0x4801, next_mps:  9, next_lps: 14, switch: false },
    QeEntry { qe: 0x3801, next_mps: 10, next_lps: 14, switch: false },
    QeEntry { qe: 0x3001, next_mps: 11, next_lps: 17, switch: false },
    QeEntry { qe: 0x2401, next_mps: 12, next_lps: 18, switch: false },
    QeEntry { qe: 0x1c01, next_mps: 13, next_lps: 20, switch: false },
    QeEntry { qe: 0x1601, next_mps: 29, next_lps: 21, switch: false },
    QeEntry { qe: 0x5601, next_mps: 15, next_lps: 14, switch: true  },
    QeEntry { qe: 0x5401, next_mps: 16, next_lps: 14, switch: false },
    QeEntry { qe: 0x5101, next_mps: 17, next_lps: 15, switch: false },
    QeEntry { qe: 0x4801, next_mps: 18, next_lps: 16, switch: false },
    QeEntry { qe: 0x3801, next_mps: 19, next_lps: 17, switch: false },
    QeEntry { qe: 0x3401, next_mps: 20, next_lps: 18, switch: false },
    QeEntry { qe: 0x3001, next_mps: 21, next_lps: 19, switch: false },
    QeEntry { qe: 0x2801, next_mps: 22, next_lps: 19, switch: false },
    QeEntry { qe: 0x2401, next_mps: 23, next_lps: 20, switch: false },
    QeEntry { qe: 0x2201, next_mps: 24, next_lps: 21, switch: false },
    QeEntry { qe: 0x1c01, next_mps: 25, next_lps: 22, switch: false },
    QeEntry { qe: 0x1801, next_mps: 26, next_lps: 23, switch: false },
    QeEntry { qe: 0x1601, next_mps: 27, next_lps: 24, switch: false },
    QeEntry { qe: 0x1401, next_mps: 28, next_lps: 25, switch: false },
    QeEntry { qe: 0x1201, next_mps: 29, next_lps: 26, switch: false },
    QeEntry { qe: 0x1101, next_mps: 30, next_lps: 27, switch: false },
    QeEntry { qe: 0x0ac1, next_mps: 31, next_lps: 28, switch: false },
    QeEntry { qe: 0x09c1, next_mps: 32, next_lps: 29, switch: false },
    QeEntry { qe: 0x08a1, next_mps: 33, next_lps: 30, switch: false },
    QeEntry { qe: 0x0521, next_mps: 34, next_lps: 31, switch: false },
    QeEntry { qe: 0x0441, next_mps: 35, next_lps: 32, switch: false },
    QeEntry { qe: 0x02a1, next_mps: 36, next_lps: 33, switch: false },
    QeEntry { qe: 0x0221, next_mps: 37, next_lps: 34, switch: false },
    QeEntry { qe: 0x0141, next_mps: 38, next_lps: 35, switch: false },
    QeEntry { qe: 0x0111, next_mps: 39, next_lps: 36, switch: false },
    QeEntry { qe: 0x0085, next_mps: 40, next_lps: 37, switch: false },
    QeEntry { qe: 0x0049, next_mps: 41, next_lps: 38, switch: false },
    QeEntry { qe: 0x0025, next_mps: 42, next_lps: 39, switch: false },
    QeEntry { qe: 0x0015, next_mps: 43, next_lps: 40, switch: false },
    QeEntry { qe: 0x0009, next_mps: 44, next_lps: 41, switch: false },
    QeEntry { qe: 0x0005, next_mps: 45, next_lps: 42, switch: false },
    QeEntry { qe: 0x0001, next_mps: 45, next_lps: 43, switch: false },
    QeEntry { qe: 0x5601, next_mps: 46, next_lps: 46, switch: false },
];

/// Per-context state: an index into [`QE_TABLE`] and the current MPS sense,
/// packed as `2 × index + mps`, OpenJPEG's `mqc_states` numbering. One lookup
/// in [`MQ_STATES`] then gives the state's `Qe` and both successor states,
/// with any MPS switch already applied.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Context {
    state: u8,
}

impl Context {
    /// The context at [`QE_TABLE`] row `index` with MPS sense `mps` (0 or 1).
    pub const fn new(index: u8, mps: u8) -> Self {
        Context {
            state: index * 2 + mps,
        }
    }

    /// The [`QE_TABLE`] row of the context's probability state.
    #[cfg(test)]
    pub fn index(self) -> u8 {
        self.state >> 1
    }

    /// The context's current MPS sense, 0 or 1.
    #[cfg(test)]
    pub fn mps(self) -> u8 {
        self.state & 1
    }
}

/// [`QE_TABLE`] expanded to packed context states (see [`Context`]): for the
/// two MPS senses of each row, the row's `Qe` in bits 0..16, the state after an
/// MPS renormalization in bits 16..24, and the state after an LPS
/// renormalization in bits 24..32, with the `switch` flip folded in. A state's
/// MPS sense is its own low bit. The table has 256 entries so a `u8` state
/// indexes it without a bounds check; only the first 94 are reachable.
static MQ_STATES: [u32; 256] = {
    let mut states = [0u32; 256];
    let mut s = 0;
    while s < 2 * QE_TABLE.len() {
        let e = QE_TABLE[s / 2];
        let mps = (s % 2) as u8;
        let lps_mps = if e.switch { 1 - mps } else { mps };
        let next_mps = e.next_mps * 2 + mps;
        let next_lps = e.next_lps * 2 + lps_mps;
        states[s] = e.qe as u32 | (next_mps as u32) << 16 | (next_lps as u32) << 24;
        s += 1;
    }
    states
};

/// MQ arithmetic decoder over one code-block's coded bytes.
///
/// Implements the ISO/IEC 15444-1 Annex C "hardware" convention directly:
/// `c`/`a` are the code and interval registers (the comparison reads the high
/// 16 bits of `c`, `c >> 16`), `ct` counts the bits left before the next
/// [`bytein`](Self::bytein), and `pos` is the byte pointer `BP`.
///
/// The pass loops clone the decoder into a local at the start of a pass and
/// write it back at the end, so its registers stay in machine registers
/// across the pass instead of going through memory on every decision.
#[derive(Debug, Clone)]
pub struct MqDecoder<'a> {
    data: &'a [u8],
    pos: usize,
    c: u32,
    a: u32,
    ct: i32,
    /// Set once `c` has taken in a byte from past the end of `data`; see
    /// [`ran_past_end`](Self::ran_past_end).
    past_end: bool,
}

impl<'a> MqDecoder<'a> {
    /// Initialize the decoder (INITDEC, ISO C.3.5) over a code-block segment.
    pub fn new(data: &'a [u8]) -> Self {
        let mut d = MqDecoder {
            data,
            pos: 0,
            c: 0,
            a: 0,
            ct: 0,
            past_end: false,
        };
        d.init();
        d
    }

    /// The coded byte at `pos`, or `0xFF` once `pos` runs off the end. Past the
    /// segment the decoder is fed 1-bits — the marker convention of ISO C.3.4
    /// (a terminating marker reads as `0xFF`) — which also bounds every read so
    /// a truncated or exhausted segment can never index out of `data`.
    #[inline(always)]
    fn byte(&self, pos: usize) -> u8 {
        self.data.get(pos).copied().unwrap_or(0xFF)
    }

    /// Coded bytes of the segment this decoder has not consumed.
    ///
    /// OpenJPEG's `mqc->end - mqc->bp`. Under a predictable termination this is
    /// bounded; see [`ends_predictably`](Self::ends_predictably).
    pub fn unconsumed(&self) -> usize {
        self.data.len().saturating_sub(self.pos)
    }

    /// Whether the segment ended the way `predictable termination` promises
    /// (ISO/IEC 15444-1 D.4.2): the codeword accounts for all but the last two
    /// bytes, whose value the MQ flush leaves undefined.
    ///
    /// This checks only the *unconsumed* side — a segment padded with bytes the
    /// codeword never reaches, which signals a wrong segment length. It does not
    /// check the other direction OpenJPEG's `check_pterm` warns on (the decoder
    /// synthesizing `0xFF` markers past a short segment): a rate-truncated or
    /// `bypass` segment routinely runs a few bytes past its end and OpenJPEG
    /// decodes it anyway, so rejecting there would refuse a valid codestream
    /// (`p1_05`). OpenJPEG only warns either way; this crate keeps the one half
    /// that catches corruption without rejecting sound input.
    pub fn ends_predictably(&self) -> bool {
        self.unconsumed() <= 2
    }

    /// Whether the decoder has read past the end of its segment: the code
    /// register has taken in at least one `0xFF` that [`byte`](Self::byte)
    /// synthesized rather than read from `data`.
    ///
    /// Until then every decision depends only on bytes of the segment, so an
    /// encoder that wrote a correct codeword fixes them. After it, decisions
    /// may depend on fill. That is routine at the end of a rate-truncated pass,
    /// whose length the encoder estimates and can set a few bytes short.
    ///
    /// The flag is sticky. It is set by the [`bytein`](Self::bytein) that moves
    /// `pos` to `data.len()`, or by the marker test that looks at the
    /// synthesized byte after a final `0xFF`. That is the first read of fill,
    /// not the first decision that depends on it: the register reads up to
    /// about 16 bits ahead of the decisions, so the flag can come early, never
    /// late.
    pub fn ran_past_end(&self) -> bool {
        self.past_end
    }

    /// INITDEC (ISO C.3.5): prime the registers and fold in the first byte.
    fn init(&mut self) {
        self.pos = 0;
        self.c = (self.byte(self.pos) as u32) << 16;
        self.bytein();
        self.c <<= 7;
        self.ct -= 7;
        self.a = 0x8000;
    }

    /// BYTEIN (ISO C.3.4): pull the next coded byte into `c`, handling the
    /// `0xFF` stuffing carry (a stuffed byte contributes seven bits, not eight,
    /// and a `0xFF` followed by `> 0x8F` is a marker, so no byte is consumed).
    ///
    /// The adds wrap: with `chigh` steered to `0xFFFF` by hostile bytes, the
    /// stuffed-byte add (`<< 9`) can carry past bit 31. The C reference does
    /// this in `OPJ_UINT32` arithmetic, where the carry silently drops, so
    /// wrapping is the oracle-faithful behavior — spelled out here so debug
    /// and release builds agree instead of the checked add panicking.
    ///
    /// A synthesized byte sets [`ran_past_end`](Self::ran_past_end). The
    /// stuffing arm never reads one: it needs a byte `<= 0x8F` after the
    /// `0xFF`, and a synthesized byte is `0xFF`.
    #[inline]
    fn bytein(&mut self) {
        if self.byte(self.pos) == 0xFF {
            if self.byte(self.pos + 1) > 0x8F {
                // A marker, real or synthesized. It is synthesized when the
                // byte after the `0xFF` lies past the end.
                if self.pos + 1 >= self.data.len() {
                    self.past_end = true;
                }
                self.c = self.c.wrapping_add(0xFF00);
                self.ct = 8;
            } else {
                self.pos += 1;
                self.c = self.c.wrapping_add((self.byte(self.pos) as u32) << 9);
                self.ct = 7;
            }
        } else {
            self.pos += 1;
            if self.pos >= self.data.len() {
                self.past_end = true;
            }
            self.c = self.c.wrapping_add((self.byte(self.pos) as u32) << 8);
            self.ct = 8;
        }
    }

    /// RENORMD (ISO C.3.3): shift `a`/`c` left until `a` is renormalized,
    /// pulling a fresh byte whenever the bit count runs out.
    ///
    /// When `c` holds enough bits for the whole shift, which is most of the
    /// time, the shift happens in one step. That is the standard's loop with
    /// no `BYTEIN` in it, since `ct` stays positive until the last shift.
    #[inline(always)]
    fn renormd(&mut self) {
        // `a` is in `1..0x8000` here, so the shift is 1 to 15.
        let shift = self.a.leading_zeros() as i32 - 16;
        if self.ct >= shift {
            self.a <<= shift;
            self.c <<= shift;
            self.ct -= shift;
            return;
        }
        loop {
            if self.ct == 0 {
                self.bytein();
            }
            self.a <<= 1;
            self.c <<= 1;
            self.ct -= 1;
            if self.a & 0x8000 != 0 {
                break;
            }
        }
    }

    /// Decode one binary decision in context `cx` (DECODE, ISO C.3.2), updating
    /// `cx`'s state. Returns the decoded bit (0 or 1).
    ///
    /// The two exchanges are MPS_EXCHANGE (C.16) and LPS_EXCHANGE (C.17). The
    /// packed state's successors carry the MPS switch, so each is one store.
    #[inline(always)]
    pub fn decode(&mut self, cx: &mut Context) -> u8 {
        let st = MQ_STATES[usize::from(cx.state)];
        let qe = st & 0xFFFF;
        let mps = cx.state & 1;
        let next_mps = (st >> 16) as u8;
        let next_lps = (st >> 24) as u8;
        self.a -= qe;
        if (self.c >> 16) < qe {
            // LPS_EXCHANGE: the decision comes from comparing the two
            // sub-intervals, and `a` becomes the LPS sub-interval.
            let d = if self.a < qe {
                cx.state = next_mps;
                mps
            } else {
                cx.state = next_lps;
                1 - mps
            };
            self.a = qe;
            self.renormd();
            d
        } else {
            self.c -= qe << 16;
            if self.a & 0x8000 == 0 {
                // MPS_EXCHANGE: the MPS sub-interval is the smaller one.
                let d = if self.a < qe {
                    cx.state = next_lps;
                    1 - mps
                } else {
                    cx.state = next_mps;
                    mps
                };
                self.renormd();
                d
            } else {
                mps
            }
        }
    }
}

/// Raw bit reader for the lazy (`bypass`) coding style (ISO/IEC 15444-1 D.6,
/// OpenJPEG's `opj_mqc_raw_decode`).
///
/// Under `bypass` the significance-propagation and magnitude-refinement passes
/// of the low bit-planes are not MQ-coded — their decisions are packed as plain
/// bits, most significant first, one raw codeword segment at a time. The only
/// twist is bit-unstuffing: because a `0xFF` byte followed by a byte above
/// `0x8F` is a marker, the encoder stuffs a `0` after every `0xFF`, so the byte
/// after a `0xFF` yields seven bits, not eight. Past the segment the reader sees
/// the `0xFF` marker convention (all further bits read as `1`), which also keeps
/// every access inside `data`.
#[derive(Debug)]
pub struct RawDecoder<'a> {
    data: &'a [u8],
    /// Index of the next byte to pull into `c` (OpenJPEG's `bp`).
    pos: usize,
    /// The byte currently being consumed, MSB first.
    c: u8,
    /// Bits left in `c`.
    ct: i32,
}

impl<'a> RawDecoder<'a> {
    /// Start a raw reader over one codeword segment's bytes.
    pub fn new(data: &'a [u8]) -> Self {
        RawDecoder {
            data,
            pos: 0,
            c: 0,
            ct: 0,
        }
    }

    /// The byte at `pos`, or `0xFF` once `pos` runs off the end — the marker
    /// convention (ISO C.3.4) that feeds 1-bits past the segment and bounds
    /// every read, exactly as [`MqDecoder::byte`] does for the MQ path.
    fn byte(&self, pos: usize) -> u8 {
        self.data.get(pos).copied().unwrap_or(0xFF)
    }

    /// Decode one raw bit (`opj_mqc_raw_decode`). Returns 0 or 1.
    pub fn decode(&mut self) -> u8 {
        if self.ct == 0 {
            if self.c == 0xFF {
                // A `0xFF` was just consumed. `> 0x8F` is a marker: stay put and
                // keep feeding 1-bits. Otherwise the next byte's top bit is the
                // stuffed `0`, so it contributes only its low seven bits.
                if self.byte(self.pos) > 0x8F {
                    self.c = 0xFF;
                    self.ct = 8;
                } else {
                    self.c = self.byte(self.pos);
                    self.pos += 1;
                    self.ct = 7;
                }
            } else {
                self.c = self.byte(self.pos);
                self.pos += 1;
                self.ct = 8;
            }
        }
        self.ct -= 1;
        (self.c >> self.ct) & 1
    }
}

#[cfg(test)]
mod tests {
    use super::{Context, MQ_STATES, MqDecoder, QE_TABLE, QeEntry, RawDecoder};

    /// ISO/IEC 15444-1 Annex C / ITU-T T.88 (08/2018) §H.2 "Test sequence for
    /// arithmetic coder": these 30 coded bytes decode to [`H2_DECODED`] under a
    /// single context that starts at state 0 with MPS 0. It is the standard's
    /// own worked example, so it proves the decoder against an external oracle
    /// rather than against our own output.
    #[rustfmt::skip]
    const H2_CODED: [u8; 30] = [
        0x84, 0xC7, 0x3B, 0xFC, 0xE1, 0xA1, 0x43, 0x04,
        0x02, 0x20, 0x00, 0x00, 0x41, 0x0D, 0xBB, 0x86,
        0xF4, 0x31, 0x7F, 0xFF, 0x88, 0xFF, 0x37, 0x47,
        0x1A, 0xDB, 0x6A, 0xDF, 0xFF, 0xAC,
    ];

    /// The 256 decisions H.2 expects, packed MSB-first into 32 bytes.
    #[rustfmt::skip]
    const H2_DECODED: [u8; 32] = [
        0x00, 0x02, 0x00, 0x51, 0x00, 0x00, 0x00, 0xC0,
        0x03, 0x52, 0x87, 0x2A, 0xAA, 0xAA, 0xAA, 0xAA,
        0x82, 0xC0, 0x20, 0x00, 0xFC, 0xD7, 0x9E, 0xF6,
        0xBF, 0x7F, 0xED, 0x90, 0x4F, 0x46, 0xA3, 0xBF,
    ];

    /// The worked test sequence decodes to the exact expected decision stream.
    #[test]
    fn h2_test_sequence_decodes_exactly() {
        let mut mq = MqDecoder::new(&H2_CODED);
        // "For this entire test, a single value of CX is used. I(CX) is
        // initially 0 and MPS(CX) is initially 0." (H.2)
        let mut cx = Context::default();
        for (i, &expected) in H2_DECODED.iter().enumerate() {
            let mut actual = 0u8;
            for _ in 0..8 {
                actual = (actual << 1) | mq.decode(&mut cx);
            }
            assert_eq!(actual, expected, "decoded byte {i}");
        }
    }

    /// Decoding past the end of the segment is well defined (the marker
    /// convention feeds 1-bits) and must never read past `data` or panic.
    #[test]
    fn decode_past_end_is_bounded() {
        let mut mq = MqDecoder::new(&H2_CODED);
        let mut cx = Context::default();
        // Far more decisions than the segment encodes; the guard in `byte`
        // keeps every read in bounds.
        for _ in 0..(H2_DECODED.len() * 8 * 4) {
            let _ = mq.decode(&mut cx);
        }
    }

    /// `ran_past_end` is set exactly when the decoder first takes in a byte from
    /// past the segment, no sooner and no later.
    ///
    /// The oracle is a second decoder over the same prefix followed by `0x00`
    /// bytes. Until the first decoder reads a synthesized `0xFF`, both have read
    /// the same bytes and their registers agree. The read that takes in the
    /// `0xFF` (where the second decoder reads `0x00`) makes them differ. Every
    /// prefix of the H.2 sequence is checked, which covers a prefix ending in
    /// `0xFF` (the marker arm) and the empty segment.
    #[test]
    fn ran_past_end_is_exact_at_the_segment_boundary() {
        for n in 0..=H2_CODED.len() {
            let prefix = &H2_CODED[..n];
            let mut extended = prefix.to_vec();
            extended.extend_from_slice(&[0x00; 8]);
            let mut short = MqDecoder::new(prefix);
            let mut long = MqDecoder::new(&extended);
            let (mut cx_short, mut cx_long) = (Context::default(), Context::default());
            let mut diverged = false;
            for step in 0..(H2_DECODED.len() * 8 + 64) {
                diverged |= (short.c, short.a, short.ct) != (long.c, long.a, long.ct);
                assert_eq!(
                    short.ran_past_end(),
                    diverged,
                    "prefix of {n} bytes, before decision {step}, pos {}",
                    short.pos
                );
                let _ = short.decode(&mut cx_short);
                let _ = long.decode(&mut cx_long);
            }
            // The whole sequence ends in `0xFF 0xAC`, a marker inside the
            // segment: the decoder stops there and never reads past the end.
            // Every shorter prefix runs out.
            assert_eq!(
                short.ran_past_end(),
                n < H2_CODED.len(),
                "prefix of {n} bytes"
            );
        }
    }

    /// A tiny and an empty segment must initialize and decode without panicking
    /// (every read falls through to the `0xFF` marker convention).
    #[test]
    fn tiny_and_empty_segments_do_not_panic() {
        for data in [[].as_slice(), [0xFF].as_slice(), [0x00].as_slice()] {
            let mut mq = MqDecoder::new(data);
            let mut cx = Context::default();
            for _ in 0..64 {
                let _ = mq.decode(&mut cx);
            }
        }
    }

    /// The BYTEIN adds run in wrapping arithmetic: the C reference does them in
    /// `OPJ_UINT32`, where a carry past bit 31 silently drops. Hostile bytes can
    /// steer `c` to the ceiling before a stuffed-byte add, so pin the wrap here —
    /// a checked `+=` would panic under overflow checks instead.
    #[test]
    fn bytein_wraps_at_the_register_ceiling() {
        let data = [0xFF, 0x8F];
        let mut mq = MqDecoder::new(&data);
        mq.pos = 0;
        mq.ct = 0;
        mq.c = u32::MAX;
        mq.bytein();
        assert_eq!(mq.c, u32::MAX.wrapping_add(0x8F << 9));
    }

    /// The raw reader returns each byte's bits most significant first.
    #[test]
    fn raw_reads_bits_msb_first() {
        let data = [0xB2u8, 0x41]; // 1011_0010  0100_0001
        let mut raw = RawDecoder::new(&data);
        let bits: Vec<u8> = (0..16).map(|_| raw.decode()).collect();
        assert_eq!(bits, [1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1]);
    }

    /// After a `0xFF` byte the next byte contributes only its low seven bits:
    /// the encoder stuffs a `0` in the top bit so the pair can never look like a
    /// marker, and the reader must skip that bit.
    #[test]
    fn raw_unstuffs_the_bit_after_0xff() {
        let data = [0xFFu8, 0x41]; // 0x41 = 0_1000001; the leading 0 is the stuff bit
        let mut raw = RawDecoder::new(&data);
        let bits: Vec<u8> = (0..15).map(|_| raw.decode()).collect();
        // Eight 1s from 0xFF, then the seven low bits of 0x41.
        assert_eq!(bits, [1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1]);
    }

    /// A `0xFF` followed by a byte above `0x8F` is a marker: the reader stops
    /// advancing and feeds 1-bits forever, which is also what happens past the
    /// end of the segment (every synthesized byte is `0xFF`).
    #[test]
    fn raw_past_the_marker_is_all_ones_and_bounded() {
        for data in [[0xFFu8, 0x90].as_slice(), [].as_slice(), [0x00].as_slice()] {
            let mut raw = RawDecoder::new(data);
            // Far more bits than the bytes encode; never indexes out of `data`.
            for _ in 0..256 {
                let _ = raw.decode();
            }
        }
        // The tail past a real marker is all 1s.
        let mut raw = RawDecoder::new(&[0xFF, 0x90]);
        for _ in 0..8 {
            assert_eq!(raw.decode(), 1); // the 0xFF byte
        }
        for _ in 0..64 {
            assert_eq!(raw.decode(), 1); // the synthesized marker tail
        }
    }

    /// ISO/IEC 15444-1 Table C-2, transcribed independently of [`QE_TABLE`] as
    /// `(qe, next_mps, next_lps, switch)`. Kept as a separate literal so a
    /// single mistyped cell in either copy is caught by `table_matches_iso`.
    #[rustfmt::skip]
    const ISO_TABLE_C2: [(u16, u8, u8, bool); 47] = [
        (0x5601,  1,  1, true),  (0x3401,  2,  6, false), (0x1801,  3,  9, false),
        (0x0ac1,  4, 12, false), (0x0521,  5, 29, false), (0x0221, 38, 33, false),
        (0x5601,  7,  6, true),  (0x5401,  8, 14, false), (0x4801,  9, 14, false),
        (0x3801, 10, 14, false), (0x3001, 11, 17, false), (0x2401, 12, 18, false),
        (0x1c01, 13, 20, false), (0x1601, 29, 21, false), (0x5601, 15, 14, true),
        (0x5401, 16, 14, false), (0x5101, 17, 15, false), (0x4801, 18, 16, false),
        (0x3801, 19, 17, false), (0x3401, 20, 18, false), (0x3001, 21, 19, false),
        (0x2801, 22, 19, false), (0x2401, 23, 20, false), (0x2201, 24, 21, false),
        (0x1c01, 25, 22, false), (0x1801, 26, 23, false), (0x1601, 27, 24, false),
        (0x1401, 28, 25, false), (0x1201, 29, 26, false), (0x1101, 30, 27, false),
        (0x0ac1, 31, 28, false), (0x09c1, 32, 29, false), (0x08a1, 33, 30, false),
        (0x0521, 34, 31, false), (0x0441, 35, 32, false), (0x02a1, 36, 33, false),
        (0x0221, 37, 34, false), (0x0141, 38, 35, false), (0x0111, 39, 36, false),
        (0x0085, 40, 37, false), (0x0049, 41, 38, false), (0x0025, 42, 39, false),
        (0x0015, 43, 40, false), (0x0009, 44, 41, false), (0x0005, 45, 42, false),
        (0x0001, 45, 43, false), (0x5601, 46, 46, false),
    ];

    /// Each packed state follows its Table C-2 row: its `Qe`, the row and MPS
    /// sense after an MPS renormalization (sense kept), and after an LPS one
    /// (sense flipped only in the `switch` rows).
    #[test]
    fn packed_states_follow_table_c2() {
        for (index, e) in QE_TABLE.iter().enumerate() {
            for mps in 0..2u8 {
                let st = MQ_STATES[usize::from(Context::new(index as u8, mps).state)];
                let after_mps = Context {
                    state: (st >> 16) as u8,
                };
                let after_lps = Context {
                    state: (st >> 24) as u8,
                };
                let lps_sense = if e.switch { 1 - mps } else { mps };
                let at = format!("row {index}, mps {mps}");
                assert_eq!(st & 0xFFFF, u32::from(e.qe), "{at}");
                assert_eq!(
                    (after_mps.index(), after_mps.mps()),
                    (e.next_mps, mps),
                    "{at}"
                );
                assert_eq!(
                    (after_lps.index(), after_lps.mps()),
                    (e.next_lps, lps_sense),
                    "{at}"
                );
            }
        }
    }

    #[test]
    fn table_has_47_states() {
        assert_eq!(QE_TABLE.len(), 47);
    }

    #[test]
    fn anchor_state_zero() {
        // The fixed start state every context is initialized to (ISO C.3.4).
        let e = QE_TABLE[0];
        assert_eq!(e.qe, 0x5601);
        assert_eq!(e.next_mps, 1);
        assert_eq!(e.next_lps, 1);
        assert!(e.switch);
    }

    #[test]
    fn table_matches_iso() {
        for (i, &(qe, next_mps, next_lps, switch)) in ISO_TABLE_C2.iter().enumerate() {
            let QeEntry {
                qe: gqe,
                next_mps: gmps,
                next_lps: glps,
                switch: gsw,
            } = QE_TABLE[i];
            assert_eq!(
                (gqe, gmps, glps, gsw),
                (qe, next_mps, next_lps, switch),
                "row {i}"
            );
        }
    }

    #[test]
    fn transitions_stay_in_bounds() {
        let n = QE_TABLE.len() as u8;
        for (i, e) in QE_TABLE.iter().enumerate() {
            assert!(
                e.next_mps < n,
                "row {i}: next_mps {} out of range",
                e.next_mps
            );
            assert!(
                e.next_lps < n,
                "row {i}: next_lps {} out of range",
                e.next_lps
            );
        }
    }

    /// Structural facts of Table C-2 that hold independently of the row-by-row
    /// values, so they catch a *systematic* transcription error that the twin
    /// `ISO_TABLE_C2` (derived the same way) would share and miss.
    #[test]
    fn known_structural_invariants() {
        // Exactly three states flip the MPS sense on an LPS exchange, and they
        // are states 0, 6 and 14 (the three Qe = 0x5601 "restart" rows).
        let switches: Vec<usize> = QE_TABLE
            .iter()
            .enumerate()
            .filter(|(_, e)| e.switch)
            .map(|(i, _)| i)
            .collect();
        assert_eq!(switches, vec![0, 6, 14]);
        assert!(switches.iter().all(|&i| QE_TABLE[i].qe == 0x5601));

        // The least-probable terminal state is absorbing: both transitions stay.
        let last = QE_TABLE[46];
        assert_eq!(last.next_mps, 46);
        assert_eq!(last.next_lps, 46);
    }
}