msrtc-rans 0.2.2

Safe public Rust entropy-coder API for msrtc_rans
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
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
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
// Licensed under the MIT license.
// Author: Riaan de Beer - github.com/infinityabundance - rdebeer.infinityabundance@gmail.com
// Derived from Microsoft MLVC msrtc_rans (MIT)
// See NOTICE file for attribution.

//! # Entropy encoder/decoder (high-level PMF/bypass/CDF pipeline)
//!
//! Implements the high-level entropy coder matching Microsoft's
//! `EntropyEncoder` / `EntropyDecoder` in `EntropyCoder.cpp`.
//!
//! Builds on the raw rANS primitives from `msrtc-rans-core`.

#![allow(missing_docs)]

use alloc::vec::Vec;

use msrtc_rans_core::sink::VecSink;
use msrtc_rans_core::source::SliceSource;
use msrtc_rans_core::source::Source;
use msrtc_rans_core::variant::{Rans64, RansByte, RansParams};
use msrtc_rans_core::{
    Freq, Rans64DecSymbol, Rans64EncSymbol, Rans64Encoder, RansByteDecSymbol, RansByteEncSymbol,
    RansByteEncoder, RawRansError,
};

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// Size of Freq in bits (sizeof(u32) * 8 = 32).
const FREQ_BITS: u32 = (core::mem::size_of::<Freq>() * 8) as u32;

// ---------------------------------------------------------------------------
// Error types
// ---------------------------------------------------------------------------

/// Errors that can occur during entropy encode/decode operations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EntropyError {
    /// Invalid PMF data (lengths, offsets, or table).
    InvalidPmf,
    /// Invalid parameter value (symbolBits, bypassBits, etc.).
    InvalidParams,
    /// Encoder/decoder is not initialized.
    InvalidState,
    /// Stream data is truncated or corrupted.
    InvalidStream,
    /// Raw rANS primitive error.
    RawRansError(RawRansError),
}

impl core::fmt::Display for EntropyError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            EntropyError::InvalidPmf => write!(f, "invalid PMF data"),
            EntropyError::InvalidParams => write!(f, "invalid parameter value"),
            EntropyError::InvalidState => write!(f, "invalid state (not initialized)"),
            EntropyError::InvalidStream => write!(f, "invalid stream"),
            EntropyError::RawRansError(e) => write!(f, "raw rANS error: {}", e),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for EntropyError {}

// ---------------------------------------------------------------------------
// Distribution descriptor
// ---------------------------------------------------------------------------

/// Describes one probability distribution (one set of PMF symbols).
#[derive(Debug, Clone)]
struct DistributionDesc {
    /// Offset applied to input values for this distribution.
    value_offset: i32,
    /// Sentinel index = length - 1 (last PMF element is tail mass for bypass).
    bypass_sentinel: i32,
    /// Starting offset of this distribution in the global symbol/CDF table.
    symbol_offset: usize,
}

// ---------------------------------------------------------------------------
// Helper: validate distribution descriptors from PMF arrays
// ---------------------------------------------------------------------------

fn initialize_distribution_desc(
    distribution_descs: &mut Vec<DistributionDesc>,
    pmf_lengths: &[i32],
    pmf_offsets: &[i32],
    pmf_table_size: usize,
) -> Result<(), EntropyError> {
    let distribution_count = pmf_lengths.len();
    if pmf_offsets.len() != distribution_count {
        return Err(EntropyError::InvalidPmf);
    }
    distribution_descs.reserve(distribution_count);

    let mut symbol_cursor: usize = 0;
    for i in 0..distribution_count {
        let length = pmf_lengths[i];
        // Each length must be > 1 (last element is bypass tail mass)
        if length <= 1 || pmf_table_size - symbol_cursor < length as usize {
            return Err(EntropyError::InvalidPmf);
        }
        distribution_descs.push(DistributionDesc {
            value_offset: pmf_offsets[i],
            bypass_sentinel: length - 1,
            symbol_offset: symbol_cursor,
        });
        symbol_cursor += length as usize;
    }

    if symbol_cursor != pmf_table_size {
        return Err(EntropyError::InvalidPmf);
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Helper: check probability bits against max
// ---------------------------------------------------------------------------

#[inline]
fn check_bits(prob_bits: u32, max_scale_bits: u32) -> Result<(), EntropyError> {
    if prob_bits < 2 || prob_bits > max_scale_bits {
        return Err(EntropyError::InvalidParams);
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Helper: convert byte slice to u32 units (LE)
// ---------------------------------------------------------------------------

#[inline]
fn bytes_to_u32_units(data: &[u8]) -> Vec<u32> {
    data.chunks_exact(4)
        .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]))
        .collect()
}

// ---------------------------------------------------------------------------
// Raw rANS encoder trait — abstracts RansByteEncoder and Rans64Encoder
// ---------------------------------------------------------------------------

/// Trait abstracting over raw rANS encoder variants for the entropy coder.
pub(crate) trait RawEncoder {
    type Unit: Copy + Default;
    type Symbol;
    fn put_raw(&mut self, start: Freq, freq: Freq, scale_bits: Freq);
    fn put_symbol(&mut self, symbol: &Self::Symbol);
    fn flush(&mut self);
    fn into_units(self) -> Vec<Self::Unit>;
}

impl RawEncoder for RansByteEncoder<VecSink<u8>> {
    type Unit = u8;
    type Symbol = RansByteEncSymbol;

    fn put_raw(&mut self, start: Freq, freq: Freq, scale_bits: Freq) {
        self.put_raw(start, freq, scale_bits);
    }

    fn put_symbol(&mut self, symbol: &Self::Symbol) {
        self.put(symbol);
    }

    fn flush(&mut self) {
        self.flush();
    }

    fn into_units(self) -> Vec<u8> {
        self.into_sink().encoded().to_vec()
    }
}

impl RawEncoder for Rans64Encoder<VecSink<u32>> {
    type Unit = u32;
    type Symbol = Rans64EncSymbol;

    fn put_raw(&mut self, start: Freq, freq: Freq, scale_bits: Freq) {
        self.put_raw(start, freq, scale_bits);
    }

    fn put_symbol(&mut self, symbol: &Self::Symbol) {
        self.put(symbol);
    }

    fn flush(&mut self) {
        self.flush();
    }

    fn into_units(self) -> Vec<u32> {
        self.into_sink().encoded().to_vec()
    }
}

// ---------------------------------------------------------------------------
// Internal encoder state — generic across variants
// ---------------------------------------------------------------------------

struct EncoderState<S: EncSymbol> {
    symbol_bits: Freq,
    distribution_descs: Vec<DistributionDesc>,
    symbols: Vec<S>,
    bypass_bits: Freq,
    bypass_max_value: Freq,
}

/// Trait for encoder symbol types.
pub(crate) trait EncSymbol: Sized {
    fn try_new(start: Freq, freq: Freq, scale_bits: Freq) -> Result<Self, RawRansError>;
}

impl EncSymbol for RansByteEncSymbol {
    fn try_new(start: Freq, freq: Freq, scale_bits: Freq) -> Result<Self, RawRansError> {
        Self::try_new(start, freq, scale_bits)
    }
}

impl EncSymbol for Rans64EncSymbol {
    fn try_new(start: Freq, freq: Freq, scale_bits: Freq) -> Result<Self, RawRansError> {
        Self::try_new(start, freq, scale_bits)
    }
}

impl<S: EncSymbol> EncoderState<S> {
    fn uninitialized() -> Self {
        Self {
            symbol_bits: 0,
            distribution_descs: Vec::new(),
            symbols: Vec::new(),
            bypass_bits: 0,
            bypass_max_value: 0,
        }
    }

    fn initialize(
        &mut self,
        pmf_lengths: &[i32],
        pmf_offsets: &[i32],
        pmf_table: &[i32],
        symbol_bits: i32,
        bypass_bits: i32,
        max_scale_bits: u32,
    ) -> Result<(), EntropyError> {
        let sb = symbol_bits as Freq;
        let bb = bypass_bits as Freq;
        check_bits(sb, max_scale_bits)?;
        check_bits(bb, max_scale_bits)?;

        // Issue 2a: safe maximum — RansByte allows 30, Rans64 allows 31 for bypass
        let is_byte_variant = max_scale_bits < 32;
        let max_safe_bits = if is_byte_variant { 30u32 } else { 31u32 };
        if sb > max_safe_bits || bb > max_safe_bits {
            return Err(EntropyError::InvalidParams);
        }

        let mut distribution_descs = Vec::new();
        initialize_distribution_desc(
            &mut distribution_descs,
            pmf_lengths,
            pmf_offsets,
            pmf_table.len(),
        )?;

        // Issue 2b: use u64 for max_freq computation to avoid i32 overflow
        let max_freq = 1u64 << symbol_bits;
        let mut symbols: Vec<S> = Vec::with_capacity(pmf_table.len());
        let mut pmf_cursor: usize = 0;

        for desc in &distribution_descs {
            // Issue 2b: track cumulative start in u64
            let mut start: u64 = 0;
            for _i in 0..=desc.bypass_sentinel {
                let freq = pmf_table[pmf_cursor] as u64;
                pmf_cursor += 1;
                if !(freq > 0 && freq <= max_freq - start) {
                    return Err(EntropyError::InvalidPmf);
                }
                let sym = S::try_new(start as Freq, freq as Freq, sb).map_err(|e| match e {
                    RawRansError::InvalidScaleBits { .. } => EntropyError::InvalidParams,
                    RawRansError::InvalidParameters => EntropyError::InvalidPmf,
                })?;
                symbols.push(sym);
                start += freq;
            }
        }

        self.distribution_descs = distribution_descs;
        self.symbols = symbols;
        self.symbol_bits = sb;
        self.bypass_bits = bb;
        // Issue 2c: compute from u64 to avoid overflow at bb=32
        self.bypass_max_value = ((1u64 << bb) - 1) as Freq;
        Ok(())
    }

    fn encode_to_vec<E: RawEncoder<Symbol = S>>(
        &self,
        indices: &[i32],
        values: &[i32],
        make_encoder: impl FnOnce() -> E,
    ) -> Result<Vec<E::Unit>, EntropyError> {
        if self.symbol_bits == 0 {
            return Err(EntropyError::InvalidState);
        }
        if indices.len() != values.len() {
            return Err(EntropyError::InvalidParams);
        }

        let mut encoder = make_encoder();

        // Encode in reverse order (matching C++: iterate from last to first)
        let data_size = indices.len();
        let mut idx = data_size as isize - 1;
        while idx >= 0 {
            let index = indices[idx as usize];
            let value = values[idx as usize];

            if index < 0 {
                // Skip encoding, decoder returns 0 for skipped indices
                idx -= 1;
                continue;
            }

            // Clamp distribution index to a valid range
            let dist_len = self.distribution_descs.len();
            let ui = if (index as usize) < dist_len {
                index as usize
            } else {
                dist_len - 1
            };
            let desc = &self.distribution_descs[ui];

            // Issue 5: checked add to avoid i32 overflow
            let adjusted = value
                .checked_add(desc.value_offset)
                .ok_or(EntropyError::InvalidParams)?;
            let symbol_index: i32;
            if adjusted < 0 || adjusted >= desc.bypass_sentinel {
                // Out of PMF range — use bypass
                // Issue 5: use checked_neg and checked_mul for safety
                let bypass_value: Freq = if adjusted < 0 {
                    // 2 * (-value) - 1
                    let neg = adjusted.checked_neg().ok_or(EntropyError::InvalidParams)?;
                    2u64.wrapping_mul(neg as u64).wrapping_sub(1) as Freq
                } else {
                    2u64.wrapping_mul((adjusted - desc.bypass_sentinel) as u64) as Freq
                };
                self.encode_bypass_value(&mut encoder, bypass_value);
                symbol_index = desc.bypass_sentinel;
            } else {
                symbol_index = adjusted;
            }

            let sym_idx = desc.symbol_offset + symbol_index as usize;
            encoder.put_symbol(&self.symbols[sym_idx]);
            idx -= 1;
        }

        encoder.flush();
        Ok(encoder.into_units())
    }

    #[inline]
    fn encode_bypass_value<E: RawEncoder>(&self, encoder: &mut E, bypass_value: Freq) {
        // Split bypassValue into bypassBits-sized digits (LSB first)
        let max_parts = (FREQ_BITS as usize / self.bypass_bits as usize).max(2);
        let mut bypass_buffer = Vec::with_capacity(max_parts);

        let mut bv = bypass_value;
        while bv != 0 {
            bypass_buffer.push(bv & self.bypass_max_value);
            bv >>= self.bypass_bits;
        }

        let mut bypass_count = bypass_buffer.len() as Freq;

        // Put digits in reverse order (MSB first in the bitstream)
        // since the rANS encoder writes from end to start
        for &digit in bypass_buffer.iter().rev() {
            encoder.put_raw(digit, 1, self.bypass_bits);
        }

        // Encode bypass count as remainder-coded prefix
        // (each maxValue digit means "more to follow")
        let mut bypass_prefix_count: Freq = 0;
        while bypass_count >= self.bypass_max_value {
            bypass_count -= self.bypass_max_value;
            bypass_prefix_count += 1;
        }
        // Put bypassCount remainder (terminal digit)
        encoder.put_raw(bypass_count, 1, self.bypass_bits);
        // Put bypassCount prefix markers
        for _ in 0..bypass_prefix_count {
            encoder.put_raw(self.bypass_max_value, 1, self.bypass_bits);
        }
    }
}

// ---------------------------------------------------------------------------
// Internal decoder state — generic across variants
// ---------------------------------------------------------------------------

struct DecoderState {
    symbol_bits: Freq,
    distribution_descs: Vec<DistributionDesc>,
    cdf_table: Vec<Freq>,
    bypass_bits: Freq,
    bypass_max_value: Freq,
}

impl DecoderState {
    fn uninitialized() -> Self {
        Self {
            symbol_bits: 0,
            distribution_descs: Vec::new(),
            cdf_table: Vec::new(),
            bypass_bits: 0,
            bypass_max_value: 0,
        }
    }

    fn initialize(
        &mut self,
        pmf_lengths: &[i32],
        pmf_offsets: &[i32],
        pmf_table: &[i32],
        symbol_bits: i32,
        bypass_bits: i32,
        max_scale_bits: u32,
    ) -> Result<(), EntropyError> {
        let sb = symbol_bits as Freq;
        let bb = bypass_bits as Freq;
        check_bits(sb, max_scale_bits)?;
        check_bits(bb, max_scale_bits)?;

        // Issue 2a: safe maximum
        let is_byte_variant = max_scale_bits < 32;
        let max_safe_bits = if is_byte_variant { 30u32 } else { 31u32 };
        if sb > max_safe_bits || bb > max_safe_bits {
            return Err(EntropyError::InvalidParams);
        }

        let mut distribution_descs = Vec::new();
        initialize_distribution_desc(
            &mut distribution_descs,
            pmf_lengths,
            pmf_offsets,
            pmf_table.len(),
        )?;

        // Build CDF table: for each distribution, store cumulative starts
        // plus one extra entry per distribution for the total sum
        let num_dist = distribution_descs.len();
        let mut cdf_table = vec![0u32; pmf_table.len() + num_dist];
        // Issue 2b: use u64 for max_freq
        let max_freq = 1u64 << symbol_bits;

        let mut cursor: usize = 0;
        for dist_idx in 0..num_dist {
            // Update symbol_offset to point into the CDF table (not the PMF table)
            distribution_descs[dist_idx].symbol_offset = cursor + dist_idx;

            let mut start: u64 = 0;
            for _i in 0..=distribution_descs[dist_idx].bypass_sentinel {
                let freq = pmf_table[cursor] as u64;
                if !(freq > 0 && freq <= max_freq - start) {
                    return Err(EntropyError::InvalidPmf);
                }
                cdf_table[cursor + dist_idx] = start as Freq;
                start += freq;
                cursor += 1;
            }
            cdf_table[cursor + dist_idx] = start as Freq; // total sum
        }

        self.distribution_descs = distribution_descs;
        self.cdf_table = cdf_table;
        self.symbol_bits = sb;
        self.bypass_bits = bb;
        // Issue 2c: compute from u64
        self.bypass_max_value = ((1u64 << bb) - 1) as Freq;
        Ok(())
    }

    fn decode_from_slice(
        &self,
        values: &mut [i32],
        indices: &[i32],
        data: &[u8],
        is_byte_variant: bool,
    ) -> Result<(), EntropyError> {
        if self.symbol_bits == 0 {
            return Err(EntropyError::InvalidState);
        }
        if values.len() != indices.len() {
            return Err(EntropyError::InvalidParams);
        }

        if is_byte_variant {
            let units = data.to_vec();
            let source = SliceSource::new(&units);
            let mut decoder = msrtc_rans_core::RansByteDecoder::new(source);
            if !decoder.init() {
                return Err(EntropyError::InvalidStream);
            }
            self.decode_inner_byte(&mut decoder, values, indices)?;
            if !decoder.source().is_exhausted() || !decoder.check_eof() {
                return Err(EntropyError::InvalidStream);
            }
        } else {
            // Issue 3: Reject misaligned Rans64 streams (must be 4-byte aligned)
            if data.len() % 4 != 0 {
                return Err(EntropyError::InvalidStream);
            }
            let units = bytes_to_u32_units(data);
            let source = SliceSource::new(&units);
            let mut decoder = msrtc_rans_core::Rans64Decoder::new(source);
            if !decoder.init() {
                return Err(EntropyError::InvalidStream);
            }
            self.decode_inner_64(&mut decoder, values, indices)?;
            if !decoder.source().is_exhausted() || !decoder.check_eof() {
                return Err(EntropyError::InvalidStream);
            }
        }
        Ok(())
    }

    /// Helper: decode bypass count using remainder-coded prefix for RansByte decoder.
    #[inline]
    fn decode_bypass_count_byte(
        &self,
        decoder: &mut msrtc_rans_core::RansByteDecoder<SliceSource<'_, u8>>,
    ) -> Result<Freq, EntropyError> {
        let mut total: Freq = 0;
        loop {
            let value = decoder.get(self.bypass_bits);
            if !decoder.advance(value, 1, self.bypass_bits) {
                return Err(EntropyError::InvalidStream);
            }
            total += value;
            if value != self.bypass_max_value {
                break;
            }
            if total > FREQ_BITS {
                return Err(EntropyError::InvalidStream);
            }
        }
        Ok(total)
    }

    /// Helper: decode bypass count for Rans64 decoder.
    #[inline]
    fn decode_bypass_count_64(
        &self,
        decoder: &mut msrtc_rans_core::Rans64Decoder<SliceSource<'_, u32>>,
    ) -> Result<Freq, EntropyError> {
        let mut total: Freq = 0;
        loop {
            let value = decoder.get(self.bypass_bits);
            if !decoder.advance(value, 1, self.bypass_bits) {
                return Err(EntropyError::InvalidStream);
            }
            total += value;
            if value != self.bypass_max_value {
                break;
            }
            if total > FREQ_BITS {
                return Err(EntropyError::InvalidStream);
            }
        }
        Ok(total)
    }

    /// Helper: decode bypass value for RansByte decoder.
    #[inline]
    fn decode_bypass_value_payload_byte(
        &self,
        decoder: &mut msrtc_rans_core::RansByteDecoder<SliceSource<'_, u8>>,
        bypass_count: Freq,
    ) -> Result<Freq, EntropyError> {
        // Issue 2c: use u64 for intermediate value to avoid overflow on shift
        let mut encoded_value: u64 = 0;
        let total_bits = bypass_count as u64 * self.bypass_bits as u64;
        let mut shift: u64 = 0;
        while shift < total_bits {
            let v = decoder.get(self.bypass_bits);
            if !decoder.advance(v, 1, self.bypass_bits) {
                return Err(EntropyError::InvalidStream);
            }
            encoded_value |= (v as u64) << shift;
            shift += self.bypass_bits as u64;
        }
        Ok(encoded_value as Freq)
    }

    /// Helper: decode bypass value for Rans64 decoder.
    #[inline]
    fn decode_bypass_value_payload_64(
        &self,
        decoder: &mut msrtc_rans_core::Rans64Decoder<SliceSource<'_, u32>>,
        bypass_count: Freq,
    ) -> Result<Freq, EntropyError> {
        // Issue 2c: use u64 for intermediate value to avoid overflow on shift
        let mut encoded_value: u64 = 0;
        let total_bits = bypass_count as u64 * self.bypass_bits as u64;
        let mut shift: u64 = 0;
        while shift < total_bits {
            let v = decoder.get(self.bypass_bits);
            if !decoder.advance(v, 1, self.bypass_bits) {
                return Err(EntropyError::InvalidStream);
            }
            encoded_value |= (v as u64) << shift;
            shift += self.bypass_bits as u64;
        }
        Ok(encoded_value as Freq)
    }

    pub(crate) fn decode_inner_byte(
        &self,
        decoder: &mut msrtc_rans_core::RansByteDecoder<SliceSource<'_, u8>>,
        values: &mut [i32],
        indices: &[i32],
    ) -> Result<(), EntropyError> {
        if self.symbol_bits == 0 {
            return Err(EntropyError::InvalidState);
        }
        if values.len() != indices.len() {
            return Err(EntropyError::InvalidParams);
        }

        for (i, &index) in indices.iter().enumerate() {
            if index < 0 {
                values[i] = 0;
                continue;
            }

            let dist_len = self.distribution_descs.len();
            let ui = if (index as usize) < dist_len {
                index as usize
            } else {
                dist_len - 1
            };
            let desc = &self.distribution_descs[ui];

            // Get cumulative frequency from state (low symbolBits bits)
            let cum_freq = decoder.get(self.symbol_bits);
            debug_assert!(cum_freq < (1u32 << self.symbol_bits));

            // Binary search in CDF table to find the symbol
            let base_offset = desc.symbol_offset;
            let lo = base_offset + 1;
            let hi = base_offset + desc.bypass_sentinel as usize + 1;

            // upper_bound: first element > cum_freq
            let upper_idx = {
                let mut low = lo;
                let mut high = hi;
                while low < high {
                    let mid = low + (high - low) / 2;
                    if cum_freq < self.cdf_table[mid] {
                        high = mid;
                    } else {
                        low = mid + 1;
                    }
                }
                low
            };
            // upper_bound - 1 gives the last element ≤ cum_freq
            let start_idx = upper_idx - 1;

            let s0 = self.cdf_table[start_idx];
            let s1 = self.cdf_table[start_idx + 1];
            let freq = s1 - s0;

            if !decoder.advance_symbol(&RansByteDecSymbol::new(s0, freq), self.symbol_bits) {
                return Err(EntropyError::InvalidStream);
            }

            let mut symbol = (start_idx - base_offset) as i32;
            if symbol == desc.bypass_sentinel {
                let bypass_count = self.decode_bypass_count_byte(decoder)?;
                let bypass_value = self.decode_bypass_value_payload_byte(decoder, bypass_count)?;
                // Issue 5: safe conversion with overflow checks using i64
                let half = (bypass_value >> 1) as i64;
                if bypass_value & 1 != 0 {
                    // Negative: 2*(-value) - 1 -> value = -(bypassValue >> 1) - 1
                    // = -(half as i64) - 1
                    symbol = (-half)
                        .checked_sub(1)
                        .ok_or(EntropyError::InvalidStream)?
                        .try_into()
                        .map_err(|_| EntropyError::InvalidStream)?;
                } else {
                    // Positive: 2*(value - sentinel) -> value = (bypassValue >> 1) + sentinel
                    symbol = half
                        .checked_add(desc.bypass_sentinel as i64)
                        .ok_or(EntropyError::InvalidStream)?
                        .try_into()
                        .map_err(|_| EntropyError::InvalidStream)?;
                }
            }

            values[i] = (symbol as i64)
                .checked_sub(desc.value_offset as i64)
                .ok_or(EntropyError::InvalidStream)?
                .try_into()
                .map_err(|_| EntropyError::InvalidStream)?;
        }
        Ok(())
    }

    pub(crate) fn decode_inner_64(
        &self,
        decoder: &mut msrtc_rans_core::Rans64Decoder<SliceSource<'_, u32>>,
        values: &mut [i32],
        indices: &[i32],
    ) -> Result<(), EntropyError> {
        if self.symbol_bits == 0 {
            return Err(EntropyError::InvalidState);
        }
        if values.len() != indices.len() {
            return Err(EntropyError::InvalidParams);
        }

        for (i, &index) in indices.iter().enumerate() {
            if index < 0 {
                values[i] = 0;
                continue;
            }

            let dist_len = self.distribution_descs.len();
            let ui = if (index as usize) < dist_len {
                index as usize
            } else {
                dist_len - 1
            };
            let desc = &self.distribution_descs[ui];

            let cum_freq = decoder.get(self.symbol_bits);
            debug_assert!(cum_freq < (1u32 << self.symbol_bits));

            let base_offset = desc.symbol_offset;
            let lo = base_offset + 1;
            let hi = base_offset + desc.bypass_sentinel as usize + 1;

            let upper_idx = {
                let mut low = lo;
                let mut high = hi;
                while low < high {
                    let mid = low + (high - low) / 2;
                    if cum_freq < self.cdf_table[mid] {
                        high = mid;
                    } else {
                        low = mid + 1;
                    }
                }
                low
            };
            let start_idx = upper_idx - 1;

            let s0 = self.cdf_table[start_idx];
            let s1 = self.cdf_table[start_idx + 1];
            let freq = s1 - s0;

            if !decoder.advance_symbol(&Rans64DecSymbol::new(s0, freq), self.symbol_bits) {
                return Err(EntropyError::InvalidStream);
            }

            let mut symbol = (start_idx - base_offset) as i32;
            if symbol == desc.bypass_sentinel {
                let bypass_count = self.decode_bypass_count_64(decoder)?;
                let bypass_value = self.decode_bypass_value_payload_64(decoder, bypass_count)?;
                // Issue 5: safe conversion with overflow checks using i64
                let half = (bypass_value >> 1) as i64;
                if bypass_value & 1 != 0 {
                    // Negative: 2*(-value) - 1 -> value = -(bypassValue >> 1) - 1
                    // = -(half as i64) - 1
                    symbol = (-half)
                        .checked_sub(1)
                        .ok_or(EntropyError::InvalidStream)?
                        .try_into()
                        .map_err(|_| EntropyError::InvalidStream)?;
                } else {
                    // Positive: 2*(value - sentinel) -> value = (bypassValue >> 1) + sentinel
                    symbol = half
                        .checked_add(desc.bypass_sentinel as i64)
                        .ok_or(EntropyError::InvalidStream)?
                        .try_into()
                        .map_err(|_| EntropyError::InvalidStream)?;
                }
            }

            values[i] = (symbol as i64)
                .checked_sub(desc.value_offset as i64)
                .ok_or(EntropyError::InvalidStream)?
                .try_into()
                .map_err(|_| EntropyError::InvalidStream)?;
        }
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Helper traits to map RansParams to encoder/decoder types
// ---------------------------------------------------------------------------

/// Maps `RansParams` implementations to their encoder symbol types.
///
/// This trait is automatically implemented for both `RansByte` and `Rans64`
/// and should not need to be implemented manually.
pub trait EncoderVariantForS: RansParams {
    /// The encoder symbol type for this variant.
    type EncSymbol: EncSymbol;

    /// The raw rANS encoder type for this variant.
    type RawEnc: RawEncoder<Symbol = Self::EncSymbol>;

    /// Maximum scale bits for this variant.
    const MAX_SCALE_BITS: u32;

    /// Convert raw encoder units to a byte vector.
    fn units_to_bytes(units: Vec<<Self::RawEnc as RawEncoder>::Unit>) -> Vec<u8>;

    /// Create a new encoder instance.
    fn make_encoder() -> Self::RawEnc;
}

impl EncoderVariantForS for RansByte {
    type EncSymbol = RansByteEncSymbol;
    type RawEnc = RansByteEncoder<VecSink<u8>>;
    const MAX_SCALE_BITS: u32 = 30;
    fn units_to_bytes(units: Vec<u8>) -> Vec<u8> {
        units
    }
    fn make_encoder() -> Self::RawEnc {
        RansByteEncoder::new(VecSink::new(4096))
    }
}

impl EncoderVariantForS for Rans64 {
    type EncSymbol = Rans64EncSymbol;
    type RawEnc = Rans64Encoder<VecSink<u32>>;
    const MAX_SCALE_BITS: u32 = 32;
    fn units_to_bytes(units: Vec<u32>) -> Vec<u8> {
        let mut bytes = Vec::with_capacity(units.len() * 4);
        for &u in &units {
            bytes.extend_from_slice(&u.to_le_bytes());
        }
        bytes
    }
    fn make_encoder() -> Self::RawEnc {
        Rans64Encoder::new(VecSink::new(4096))
    }
}

// ---------------------------------------------------------------------------
// Public EntropyEncoder
// ---------------------------------------------------------------------------

/// High-level entropy encoder using PMF distributions with bypass support.
///
/// Generic over `S: RansParams` (`RansByte` or `Rans64`).
///
/// # Example
///
/// ```ignore
/// use msrtc_rans::entropy::EntropyEncoder;
/// use msrtc_rans::RansByte;
///
/// let mut enc: EntropyEncoder<RansByte> = EntropyEncoder::new();
/// enc.initialize(
///     &[4, 6],       // pmf_lengths
///     &[1, 2],       // pmf_offsets
///     &[1, 3, 1, 1, 1, 3, 5, 3, 1, 1],  // pmf_table
///     16,            // symbol_bits
///     4,             // bypass_bits
/// ).unwrap();
///
/// let mut buffer = Vec::new();
/// enc.encode(&[0, 1], &[1, 1], &mut buffer).unwrap();
/// ```
pub struct EntropyEncoder<S: EncoderVariantForS> {
    state: EncoderState<<S as EncoderVariantForS>::EncSymbol>,
}

impl<S: EncoderVariantForS> EntropyEncoder<S> {
    /// Create a new uninitialized entropy encoder.
    pub fn new() -> Self {
        Self {
            state: EncoderState::uninitialized(),
        }
    }

    /// Initialize the encoder with PMF distribution data.
    ///
    /// * `pmf_lengths` — number of symbols per distribution (including bypass sentinel)
    /// * `pmf_offsets` — value offsets per distribution
    /// * `pmf_table` — flat array of symbol frequencies for all distributions
    /// * `symbol_bits` — number of bits for symbol encoding (e.g. 16)
    /// * `bypass_bits` — number of bits for bypass encoding (e.g. 4)
    pub fn initialize(
        &mut self,
        pmf_lengths: &[i32],
        pmf_offsets: &[i32],
        pmf_table: &[i32],
        symbol_bits: u32,
        bypass_bits: u32,
    ) -> Result<(), EntropyError> {
        self.state.initialize(
            pmf_lengths,
            pmf_offsets,
            pmf_table,
            symbol_bits as i32,
            bypass_bits as i32,
            <S as EncoderVariantForS>::MAX_SCALE_BITS,
        )
    }

    /// One-shot encode: encode `indices`/`values` into `buffer`.
    ///
    /// The encoded bytes are appended to `buffer`.
    pub fn encode(
        &self,
        indices: &[i32],
        values: &[i32],
        buffer: &mut Vec<u8>,
    ) -> Result<(), EntropyError> {
        let units = self.state.encode_to_vec(indices, values, S::make_encoder)?;
        let bytes = S::units_to_bytes(units);
        buffer.extend_from_slice(&bytes);
        Ok(())
    }
}

impl<S: EncoderVariantForS> Default for EntropyEncoder<S> {
    fn default() -> Self {
        Self::new()
    }
}

fn _assert_encoder_bounds() {
    fn _is_encoder<S: EncoderVariantForS>() {}
    _is_encoder::<RansByte>();
    _is_encoder::<Rans64>();
}

// ---------------------------------------------------------------------------
// Public EntropyDecoder
// ---------------------------------------------------------------------------

/// High-level entropy decoder using CDF tables for symbol lookup.
///
/// Generic over `S: RansParams` (`RansByte` or `Rans64`).
pub struct EntropyDecoder<S: RansParams> {
    state: DecoderState,
    _phantom: core::marker::PhantomData<S>,
}

impl<S: RansParams> EntropyDecoder<S> {
    /// Create a new uninitialized entropy decoder.
    pub fn new() -> Self {
        Self {
            state: DecoderState::uninitialized(),
            _phantom: core::marker::PhantomData,
        }
    }

    /// Initialize the decoder with PMF distribution data.
    ///
    /// * `pmf_lengths` — number of symbols per distribution (including bypass sentinel)
    /// * `pmf_offsets` — value offsets per distribution
    /// * `pmf_table` — flat array of symbol frequencies for all distributions
    /// * `symbol_bits` — number of bits for symbol encoding (e.g. 16)
    /// * `bypass_bits` — number of bits for bypass encoding (e.g. 4)
    pub fn initialize(
        &mut self,
        pmf_lengths: &[i32],
        pmf_offsets: &[i32],
        pmf_table: &[i32],
        symbol_bits: u32,
        bypass_bits: u32,
    ) -> Result<(), EntropyError> {
        let max_scale_bits = match S::NAME {
            "RansByte" => 30u32,
            "Rans64" => 32u32,
            _ => return Err(EntropyError::InvalidParams),
        };
        self.state.initialize(
            pmf_lengths,
            pmf_offsets,
            pmf_table,
            symbol_bits as i32,
            bypass_bits as i32,
            max_scale_bits,
        )
    }

    /// One-shot decode: decode from `data` into `values`.
    ///
    /// * `values` — output buffer (must be same length as `indices`)
    /// * `indices` — distribution indices for each value to decode
    /// * `data` — encoded byte stream
    pub fn decode(
        &self,
        values: &mut [i32],
        indices: &[i32],
        data: &[u8],
    ) -> Result<(), EntropyError> {
        let is_byte = match S::NAME {
            "RansByte" => true,
            "Rans64" => false,
            _ => return Err(EntropyError::InvalidParams),
        };
        self.state.decode_from_slice(values, indices, data, is_byte)
    }

    /// Decode from a slice but do NOT require the source to be fully exhausted.
    ///
    /// This is used when decoding from a `RansDecoderStream` where multiple encoded
    /// segments are concatenated. The method decodes `values`/`indices` from the
    /// beginning of `data` and returns the number of bytes consumed.
    ///
    /// * `values` — output buffer (must be same length as `indices`)
    /// * `indices` — distribution indices for each value to decode
    /// * `data` — encoded byte stream (may contain extra trailing data)
    ///
    /// Returns the number of bytes consumed from `data` on success.
    pub fn decode_partial(
        &self,
        values: &mut [i32],
        indices: &[i32],
        data: &[u8],
    ) -> Result<usize, EntropyError> {
        if self.state.symbol_bits == 0 {
            return Err(EntropyError::InvalidState);
        }
        if values.len() != indices.len() {
            return Err(EntropyError::InvalidParams);
        }

        let consumed = match S::NAME {
            "RansByte" => {
                let units = data.to_vec();
                let source = SliceSource::new(&units);
                let mut decoder = msrtc_rans_core::RansByteDecoder::new(source);
                if !decoder.init() {
                    return Err(EntropyError::InvalidStream);
                }
                self.state
                    .decode_inner_byte(&mut decoder, values, indices)?;
                if !decoder.check_eof() {
                    return Err(EntropyError::InvalidStream);
                }
                decoder.source().position()
            }
            "Rans64" => {
                if data.len() % 4 != 0 {
                    return Err(EntropyError::InvalidStream);
                }
                let units = bytes_to_u32_units(data);
                let source = SliceSource::new(&units);
                let mut decoder = msrtc_rans_core::Rans64Decoder::new(source);
                if !decoder.init() {
                    return Err(EntropyError::InvalidStream);
                }
                self.state.decode_inner_64(&mut decoder, values, indices)?;
                if !decoder.check_eof() {
                    return Err(EntropyError::InvalidStream);
                }
                decoder.source().position() * 4
            }
            _ => return Err(EntropyError::InvalidParams),
        };

        Ok(consumed)
    }
}

impl<S: RansParams> Default for EntropyDecoder<S> {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    // Reference test case from test_msrtc_rans.py:
    //   PMF_LENGTHS = [4, 6]
    //   PMF_OFFSETS = [1, 2]
    //   PMF_TABLE   = [1, 3, 1, 1, 1, 3, 5, 3, 1, 1]
    //   INDICES     = [0, 1, 0, 1]
    //   VALUES      = [-2, 1, 0, 1]
    //   SYMBOL_BITS = 16
    //   BYPASS_BITS = 4
    //
    // Reference bitstreams from upstream oracle (EntropyCoder.cpp):
    //   RansByte: hex = "0500bd040001a10003000b00"
    //   Rans64:   hex = "0500a1bd04000000110a002f03000300"

    const PMF_LENGTHS: [i32; 2] = [4, 6];
    const PMF_OFFSETS: [i32; 2] = [1, 2];
    const PMF_TABLE: [i32; 10] = [1, 3, 1, 1, 1, 3, 5, 3, 1, 1];
    const INDICES: [i32; 4] = [0, 1, 0, 1];
    const VALUES: [i32; 4] = [-2, 1, 0, 1];
    const SYMBOL_BITS: u32 = 16;
    const BYPASS_BITS: u32 = 4;

    const REF_HEX_BYTE: &str = "0500bd040001a10003000b00";
    const REF_HEX_64: &str = "0500a1bd04000000110a002f03000300";

    fn hex_decode(hex: &str) -> Vec<u8> {
        (0..hex.len())
            .step_by(2)
            .map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap())
            .collect()
    }

    #[test]
    fn test_encoder_byte_initialize() {
        let mut enc: EntropyEncoder<RansByte> = EntropyEncoder::new();
        assert!(
            enc.initialize(
                &PMF_LENGTHS,
                &PMF_OFFSETS,
                &PMF_TABLE,
                SYMBOL_BITS,
                BYPASS_BITS
            )
            .is_ok()
        );
    }

    #[test]
    fn test_encoder_64_initialize() {
        let mut enc: EntropyEncoder<Rans64> = EntropyEncoder::new();
        assert!(
            enc.initialize(
                &PMF_LENGTHS,
                &PMF_OFFSETS,
                &PMF_TABLE,
                SYMBOL_BITS,
                BYPASS_BITS
            )
            .is_ok()
        );
    }

    #[test]
    fn test_encoder_rejects_invalid_pmf() {
        let mut enc: EntropyEncoder<RansByte> = EntropyEncoder::new();
        // Mismatched lengths/offsets
        assert_eq!(
            enc.initialize(&[4], &[1, 2], &PMF_TABLE, SYMBOL_BITS, BYPASS_BITS),
            Err(EntropyError::InvalidPmf)
        );
    }

    #[test]
    fn test_encoder_rejects_invalid_params() {
        let mut enc: EntropyEncoder<RansByte> = EntropyEncoder::new();
        // symbol_bits < 2
        assert_eq!(
            enc.initialize(&PMF_LENGTHS, &PMF_OFFSETS, &PMF_TABLE, 1, BYPASS_BITS),
            Err(EntropyError::InvalidParams)
        );
    }

    #[test]
    fn test_encoder_byte_rejects_length_leq_one() {
        let mut enc: EntropyEncoder<RansByte> = EntropyEncoder::new();
        // Length <= 1 is invalid (need tail mass for bypass)
        assert_eq!(
            enc.initialize(&[1, 6], &[1, 2], &PMF_TABLE, SYMBOL_BITS, BYPASS_BITS),
            Err(EntropyError::InvalidPmf)
        );
    }

    #[test]
    fn test_encode_byte_matches_reference() {
        // Encodes values=[-2, 1, 0, 1] with RansByte.
        // Value -2 (index 0, offset 1 => adjusted=-1) triggers bypass.
        let mut enc: EntropyEncoder<RansByte> = EntropyEncoder::new();
        enc.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();

        let mut buffer = Vec::new();
        enc.encode(&INDICES, &VALUES, &mut buffer).unwrap();

        let expected = hex_decode(REF_HEX_BYTE);
        assert_eq!(
            buffer, expected,
            "RansByte encode output does not match reference hex"
        );
    }

    #[test]
    fn test_encode_64_matches_reference() {
        let mut enc: EntropyEncoder<Rans64> = EntropyEncoder::new();
        enc.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();

        let mut buffer = Vec::new();
        enc.encode(&INDICES, &VALUES, &mut buffer).unwrap();

        let expected = hex_decode(REF_HEX_64);
        assert_eq!(
            buffer, expected,
            "Rans64 encode output does not match reference hex"
        );
    }

    #[test]
    fn test_encode_in_range_values_no_bypass() {
        // Values that are all in-range (no bypass):
        // Dist 0: offset=1, sentinel=3, valid adjusted: [0,2] => value: [-1, 1]
        // Dist 1: offset=2, sentinel=5, valid adjusted: [0,4] => value: [-2, 2]
        let in_range_values = [1i32, 1, 0, 1];
        let mut enc: EntropyEncoder<RansByte> = EntropyEncoder::new();
        enc.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();

        let mut buffer = Vec::new();
        let result = enc.encode(&INDICES, &in_range_values, &mut buffer);
        assert!(result.is_ok(), "encode should succeed: {:?}", result);
        assert!(!buffer.is_empty(), "encoded buffer should not be empty");
    }

    #[test]
    fn test_decode_byte_roundtrip_in_range() {
        // Verify roundtrip encode-decode with in-range values (no bypass).
        let values = [1i32, 1, 0, 1];

        let mut enc: EntropyEncoder<RansByte> = EntropyEncoder::new();
        enc.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();

        let mut encoded = Vec::new();
        enc.encode(&INDICES, &values, &mut encoded).unwrap();

        let mut dec: EntropyDecoder<RansByte> = EntropyDecoder::new();
        dec.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();

        let mut decoded = vec![0i32; values.len()];
        dec.decode(&mut decoded, &INDICES, &encoded).unwrap();

        assert_eq!(
            decoded, values,
            "roundtrip decode should match original values"
        );
    }

    #[test]
    fn test_decode_64_roundtrip_in_range() {
        let values = [1i32, 1, 0, 1];

        let mut enc: EntropyEncoder<Rans64> = EntropyEncoder::new();
        enc.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();

        let mut encoded = Vec::new();
        enc.encode(&INDICES, &values, &mut encoded).unwrap();

        let mut dec: EntropyDecoder<Rans64> = EntropyDecoder::new();
        dec.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();

        let mut decoded = vec![0i32; values.len()];
        dec.decode(&mut decoded, &INDICES, &encoded).unwrap();

        assert_eq!(
            decoded, values,
            "Rans64 roundtrip decode should match original values"
        );
    }

    #[test]
    fn test_decode_byte_roundtrip_bypass() {
        // Roundtrip with values that require bypass (value=-2 is out-of-range).
        let values = [-2i32, 1, 0, 1];

        let mut enc: EntropyEncoder<RansByte> = EntropyEncoder::new();
        enc.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();

        let mut encoded = Vec::new();
        enc.encode(&INDICES, &values, &mut encoded).unwrap();

        let mut dec: EntropyDecoder<RansByte> = EntropyDecoder::new();
        dec.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();

        let mut decoded = vec![0i32; values.len()];
        dec.decode(&mut decoded, &INDICES, &encoded).unwrap();

        assert_eq!(
            decoded, values,
            "bypass roundtrip decode should match original values"
        );
    }

    #[test]
    fn test_decode_64_roundtrip_bypass() {
        let values = [-2i32, 1, 0, 1];

        let mut enc: EntropyEncoder<Rans64> = EntropyEncoder::new();
        enc.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();

        let mut encoded = Vec::new();
        enc.encode(&INDICES, &values, &mut encoded).unwrap();

        let mut dec: EntropyDecoder<Rans64> = EntropyDecoder::new();
        dec.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();

        let mut decoded = vec![0i32; values.len()];
        dec.decode(&mut decoded, &INDICES, &encoded).unwrap();

        assert_eq!(
            decoded, values,
            "Rans64 bypass roundtrip decode should match original values"
        );
    }

    // -----------------------------------------------------------------------
    // Issue 2d: scale-32 safe / reject tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_encoder_64_symbol_bits_31_accepted() {
        // Rans64 symbol_bits=31 is within max_safe_bits (31)
        let mut enc: EntropyEncoder<Rans64> = EntropyEncoder::new();
        assert!(
            enc.initialize(&PMF_LENGTHS, &PMF_OFFSETS, &PMF_TABLE, 31, BYPASS_BITS)
                .is_ok()
        );
    }

    #[test]
    fn test_encoder_64_symbol_bits_32_rejected() {
        // Rans64 symbol_bits=32 exceeds max_safe_bits (31), must not panic
        let mut enc: EntropyEncoder<Rans64> = EntropyEncoder::new();
        assert_eq!(
            enc.initialize(&PMF_LENGTHS, &PMF_OFFSETS, &PMF_TABLE, 32, BYPASS_BITS),
            Err(EntropyError::InvalidParams)
        );
    }

    #[test]
    fn test_encoder_64_bypass_bits_32_rejected() {
        // Rans64 bypass_bits=32 exceeds max_safe_bits (31), must not panic
        let mut enc: EntropyEncoder<Rans64> = EntropyEncoder::new();
        assert_eq!(
            enc.initialize(&PMF_LENGTHS, &PMF_OFFSETS, &PMF_TABLE, SYMBOL_BITS, 32),
            Err(EntropyError::InvalidParams)
        );
    }

    // -----------------------------------------------------------------------
    // Issue 3: misaligned Rans64 streams rejected
    // -----------------------------------------------------------------------

    #[test]
    fn test_decode_64_rejects_misaligned_1_extra_byte() {
        let mut enc: EntropyEncoder<Rans64> = EntropyEncoder::new();
        enc.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();
        let mut encoded = Vec::new();
        enc.encode(&INDICES, &[1i32, 1, 0, 1], &mut encoded)
            .unwrap();

        // Append 1 extra byte to make it misaligned
        let mut misaligned = encoded.clone();
        misaligned.push(0xAB);

        let mut dec: EntropyDecoder<Rans64> = EntropyDecoder::new();
        dec.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();
        let mut decoded = vec![0i32; 4];
        let result = dec.decode(&mut decoded, &INDICES, &misaligned);
        assert_eq!(result, Err(EntropyError::InvalidStream));
    }

    #[test]
    fn test_decode_64_rejects_misaligned_2_extra_bytes() {
        let mut enc: EntropyEncoder<Rans64> = EntropyEncoder::new();
        enc.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();
        let mut encoded = Vec::new();
        enc.encode(&INDICES, &[1i32, 1, 0, 1], &mut encoded)
            .unwrap();

        let mut misaligned = encoded.clone();
        misaligned.extend_from_slice(&[0xAB, 0xCD]);

        let mut dec: EntropyDecoder<Rans64> = EntropyDecoder::new();
        dec.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();
        let mut decoded = vec![0i32; 4];
        let result = dec.decode(&mut decoded, &INDICES, &misaligned);
        assert_eq!(result, Err(EntropyError::InvalidStream));
    }

    #[test]
    fn test_decode_64_rejects_misaligned_3_extra_bytes() {
        let mut enc: EntropyEncoder<Rans64> = EntropyEncoder::new();
        enc.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();
        let mut encoded = Vec::new();
        enc.encode(&INDICES, &[1i32, 1, 0, 1], &mut encoded)
            .unwrap();

        let mut misaligned = encoded.clone();
        misaligned.extend_from_slice(&[0xAB, 0xCD, 0xEF]);

        let mut dec: EntropyDecoder<Rans64> = EntropyDecoder::new();
        dec.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();
        let mut decoded = vec![0i32; 4];
        let result = dec.decode(&mut decoded, &INDICES, &misaligned);
        assert_eq!(result, Err(EntropyError::InvalidStream));
    }

    #[test]
    fn test_decode_byte_accepts_extra_bytes() {
        // RansByte has byte-level alignment, extra bytes should not be rejected
        let mut enc: EntropyEncoder<RansByte> = EntropyEncoder::new();
        enc.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();
        let mut encoded = Vec::new();
        enc.encode(&INDICES, &[1i32, 1, 0, 1], &mut encoded)
            .unwrap();

        // Append extra bytes
        let mut extended = encoded.clone();
        extended.extend_from_slice(&[0xAB, 0xCD]);

        let mut dec: EntropyDecoder<RansByte> = EntropyDecoder::new();
        dec.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();
        let mut decoded = vec![0i32; 4];
        // This may fail because the decoder checks EOF, but it should NOT
        // be rejected for misalignment
        let _ = dec.decode(&mut decoded, &INDICES, &extended);
        // We don't assert success or failure — we just assert no panic
    }

    // -----------------------------------------------------------------------
    // Issue 4: Expanded bypass coverage
    // -----------------------------------------------------------------------

    #[test]
    fn test_encode_bypass_positive_outlier() {
        // Value > sentinel (positive outlier): dist 0 sentinel=3, offset=1,
        // value=10 => adjusted=11 > 3 => bypass (8/2=4 above sentinel => value 4+3=7-1=6...
        // actually: adjusted=11, sentinel=3, bypass_value = 2*(11-3) = 16
        // decode: 16>>1=8, 8+3=11-1=10 ✓
        let values = [10i32, 1, 0, 1];
        let mut enc: EntropyEncoder<RansByte> = EntropyEncoder::new();
        enc.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();
        let mut encoded = Vec::new();
        enc.encode(&INDICES, &values, &mut encoded).unwrap();

        let mut dec: EntropyDecoder<RansByte> = EntropyDecoder::new();
        dec.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();
        let mut decoded = vec![0i32; 4];
        dec.decode(&mut decoded, &INDICES, &encoded).unwrap();
        assert_eq!(decoded, values);
    }

    #[test]
    fn test_encode_bypass_multi_digit_value() {
        // Value requiring multiple bypassBits-sized chunks (bypass_bits=4)
        // Large bypass value: dist 0 sentinel=3, offset=1, value=200 => adjusted=201
        // bypass_value = 2*(201-3) = 396 = 0x18C, needs multiple 4-bit chunks
        let values = [200i32, 1, 0, 1];
        let mut enc: EntropyEncoder<RansByte> = EntropyEncoder::new();
        enc.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();
        let mut encoded = Vec::new();
        enc.encode(&INDICES, &values, &mut encoded).unwrap();

        let mut dec: EntropyDecoder<RansByte> = EntropyDecoder::new();
        dec.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();
        let mut decoded = vec![0i32; 4];
        dec.decode(&mut decoded, &INDICES, &encoded).unwrap();
        assert_eq!(decoded, values);
    }

    #[test]
    fn test_encode_bypass_bits_2() {
        // Minimum bypass_bits = 2
        let mut enc: EntropyEncoder<RansByte> = EntropyEncoder::new();
        enc.initialize(&PMF_LENGTHS, &PMF_OFFSETS, &PMF_TABLE, SYMBOL_BITS, 2)
            .unwrap();
        let values = [10i32, 1, 0, 1]; // value 10 => bypass
        let mut encoded = Vec::new();
        enc.encode(&INDICES, &values, &mut encoded).unwrap();

        let mut dec: EntropyDecoder<RansByte> = EntropyDecoder::new();
        dec.initialize(&PMF_LENGTHS, &PMF_OFFSETS, &PMF_TABLE, SYMBOL_BITS, 2)
            .unwrap();
        let mut decoded = vec![0i32; 4];
        dec.decode(&mut decoded, &INDICES, &encoded).unwrap();
        assert_eq!(decoded, values);
    }

    #[test]
    fn test_encode_bypass_bits_3() {
        // Odd bypass_bits = 3
        let mut enc: EntropyEncoder<RansByte> = EntropyEncoder::new();
        enc.initialize(&PMF_LENGTHS, &PMF_OFFSETS, &PMF_TABLE, SYMBOL_BITS, 3)
            .unwrap();
        let values = [10i32, 1, 0, 1];
        let mut encoded = Vec::new();
        enc.encode(&INDICES, &values, &mut encoded).unwrap();

        let mut dec: EntropyDecoder<RansByte> = EntropyDecoder::new();
        dec.initialize(&PMF_LENGTHS, &PMF_OFFSETS, &PMF_TABLE, SYMBOL_BITS, 3)
            .unwrap();
        let mut decoded = vec![0i32; 4];
        dec.decode(&mut decoded, &INDICES, &encoded).unwrap();
        assert_eq!(decoded, values);
    }

    #[test]
    fn test_encode_bypass_bits_8() {
        // Larger bypass_bits = 8
        let mut enc: EntropyEncoder<RansByte> = EntropyEncoder::new();
        enc.initialize(&PMF_LENGTHS, &PMF_OFFSETS, &PMF_TABLE, SYMBOL_BITS, 8)
            .unwrap();
        let values = [10i32, 1, 0, 1];
        let mut encoded = Vec::new();
        enc.encode(&INDICES, &values, &mut encoded).unwrap();

        let mut dec: EntropyDecoder<RansByte> = EntropyDecoder::new();
        dec.initialize(&PMF_LENGTHS, &PMF_OFFSETS, &PMF_TABLE, SYMBOL_BITS, 8)
            .unwrap();
        let mut decoded = vec![0i32; 4];
        dec.decode(&mut decoded, &INDICES, &encoded).unwrap();
        assert_eq!(decoded, values);
    }

    #[test]
    fn test_encode_bypass_multiple_bypasses() {
        // Multiple bypass values in one stream: both -2 and 10 need bypass
        // dist 0: offset=1 sentinel=3, dist 1: offset=2 sentinel=5
        // value -2 (dist 0) => adjusted=-1 => bypass (negative)
        // value 10 (dist 1) => adjusted=12 => bypass (positive)
        let values = [-2i32, 10, 0, 1];
        let mut enc: EntropyEncoder<RansByte> = EntropyEncoder::new();
        enc.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();
        let mut encoded = Vec::new();
        enc.encode(&INDICES, &values, &mut encoded).unwrap();

        let mut dec: EntropyDecoder<RansByte> = EntropyDecoder::new();
        dec.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();
        let mut decoded = vec![0i32; 4];
        dec.decode(&mut decoded, &INDICES, &encoded).unwrap();
        assert_eq!(decoded, values);
    }

    #[test]
    fn test_encode_bypass_mixed_in_range_and_bypass() {
        // Mix of in-range and bypass values
        // dist 0: offset=1 sentinel=3, valid adjusted [0,2] => values [-1, 1]
        // dist 1: offset=2 sentinel=5, valid adjusted [0,4] => values [-2, 2]
        // value 0 in dist 0 => in-range, value 1 in dist 0 => in-range
        // value 5 in dist 1 => bypass (adjusted=7 > 4), value -3 in dist 1 => bypass (adjusted=-1 < 0)
        let values = [0i32, 5, 1, -3];
        let mut enc: EntropyEncoder<RansByte> = EntropyEncoder::new();
        enc.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();
        let mut encoded = Vec::new();
        enc.encode(&INDICES, &values, &mut encoded).unwrap();

        let mut dec: EntropyDecoder<RansByte> = EntropyDecoder::new();
        dec.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();
        let mut decoded = vec![0i32; 4];
        dec.decode(&mut decoded, &INDICES, &encoded).unwrap();
        assert_eq!(decoded, values);
    }

    #[test]
    fn test_encode_bypass_negative_outlier_at_boundary() {
        // Negative outlier at boundary: -1 - sentinel (very negative)
        // dist 0: offset=1, sentinel=3, value=-10 => adjusted=-9 => bypass
        // (-9 < 0) => bypass_value = 2*9-1 = 17, decode: 17>>1=8, -(8+1) = -9, -9+1 = -8... wait
        // decode bypass: negative flag set, half=8, symbol = -(8+1) = -9, -9 = -9+1 = -8...
        // Actually: symbol = -9, values[i] = symbol - offset = (-9) - 1 = -10 ✓
        let values = [-10i32, 1, 0, 1];
        let mut enc: EntropyEncoder<RansByte> = EntropyEncoder::new();
        enc.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();
        let mut encoded = Vec::new();
        enc.encode(&INDICES, &values, &mut encoded).unwrap();

        let mut dec: EntropyDecoder<RansByte> = EntropyDecoder::new();
        dec.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();
        let mut decoded = vec![0i32; 4];
        dec.decode(&mut decoded, &INDICES, &encoded).unwrap();
        assert_eq!(decoded, values);
    }

    #[test]
    fn test_encode_bypass_large_positive_outlier() {
        // Large positive outlier
        let values = [10000i32, 1, 0, 1];
        let mut enc: EntropyEncoder<RansByte> = EntropyEncoder::new();
        enc.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();
        let mut encoded = Vec::new();
        enc.encode(&INDICES, &values, &mut encoded).unwrap();

        let mut dec: EntropyDecoder<RansByte> = EntropyDecoder::new();
        dec.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();
        let mut decoded = vec![0i32; 4];
        dec.decode(&mut decoded, &INDICES, &encoded).unwrap();
        assert_eq!(decoded, values);
    }

    // -----------------------------------------------------------------------
    // Issue 5: extreme value overflow protection
    // -----------------------------------------------------------------------

    #[test]
    fn test_encode_bypass_extreme_negative_i32_min_plus_one() {
        // i32::MIN + 1 with offset 1 gives adjusted = i32::MIN + 2 = -2147483646
        // checked_neg of that gives 2147483646, no overflow.
        // This should succeed (no overflow).
        let values = [i32::MIN + 1, 1, 0, 1];
        let mut enc: EntropyEncoder<RansByte> = EntropyEncoder::new();
        enc.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();
        let mut encoded = Vec::new();
        let result = enc.encode(&INDICES, &values, &mut encoded);
        // Must not panic — should succeed or return InvalidParams gracefully
        assert!(result.is_ok() || result == Err(EntropyError::InvalidParams));
    }

    #[test]
    fn test_encode_bypass_extreme_positive_i32_max() {
        // i32::MAX with offset could cause overflow in checked_add -> InvalidParams
        let values = [i32::MAX, 1, 0, 1];
        let mut enc: EntropyEncoder<RansByte> = EntropyEncoder::new();
        enc.initialize(
            &PMF_LENGTHS,
            &PMF_OFFSETS,
            &PMF_TABLE,
            SYMBOL_BITS,
            BYPASS_BITS,
        )
        .unwrap();
        let mut encoded = Vec::new();
        let result = enc.encode(&INDICES, &values, &mut encoded);
        assert_eq!(result, Err(EntropyError::InvalidParams));
    }
}