zrip-encode 0.9.6

zstd encoder for zrip (internal crate)
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
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
#![forbid(unsafe_code)]

#[cfg(feature = "alloc")]
use alloc::vec::Vec;

use crate::output::OutputSink;
use crate::primitives;
use crate::strategy::BlockPolicy;
use zrip_core::Sequence;
use zrip_core::bitstream::writer::BitWriter;
use zrip_core::error::CompressError;
use zrip_core::fse::{
    FseDecodeEntry, LL_DEFAULT_ACCURACY, LL_DEFAULT_DIST, ML_DEFAULT_ACCURACY, ML_DEFAULT_DIST,
    OF_DEFAULT_ACCURACY, OF_DEFAULT_DIST,
};
use zrip_core::huffman::encode::{HuffmanEncodeTable, byte_histogram};

/// Defines `$name!(p)`, which appends the extra bits of packed sequence `p`
/// after its three state transitions.
///
/// At most 7 + 26 bits are pending after the transitions, so up to 30 extra
/// bits fit without a flush, as in C zstd. Longer extras flush first, and
/// more than 56 (a long literal run, a long match, and a far offset in one
/// sequence) go in two parts, so the container never holds 64 bits.
macro_rules! add_extra_bits_macro {
    ($name:ident, $add_bits:ident, $flush:ident) => {
        macro_rules! $name {
            ($p:expr) => {
                if $p.extra_nbits <= 30 {
                    $add_bits!($p.extra_bits, $p.extra_nbits);
                } else {
                    $flush!();
                    if $p.extra_nbits <= 56 {
                        $add_bits!($p.extra_bits, $p.extra_nbits);
                    } else {
                        $add_bits!($p.extra_bits & 0xFFFF_FFFF, 32);
                        $flush!();
                        $add_bits!($p.extra_bits >> 32, $p.extra_nbits - 32);
                    }
                }
            };
        }
    };
}

#[inline]
fn write_seq_count(output: &mut Vec<u8>, num_seq: u32) {
    if num_seq < 128 {
        output.push(num_seq as u8);
    } else if num_seq < 0x7F00 {
        output.push(((num_seq >> 8) + 128) as u8);
        output.push(num_seq as u8);
    } else {
        output.push(0xFF);
        let adj = num_seq - 0x7F00;
        output.push(adj as u8);
        output.push((adj >> 8) as u8);
    }
}

#[derive(Clone, Copy, Default)]
struct PackedSeq {
    extra_bits: u64,
    ll_c: u8,
    ml_c: u8,
    of_c: u8,
    extra_nbits: u8,
}

/// Code counts of the last packed block, counted while packing. The tables
/// have a slot for every `u8` code, so the counting needs neither masks nor
/// bounds checks.
#[derive(Clone)]
struct SeqFreqs {
    ll: [u32; 256],
    ml: [u32; 256],
    of: [u32; 256],
    extra_bits: u64,
}

impl Default for SeqFreqs {
    fn default() -> Self {
        Self {
            ll: [0; 256],
            ml: [0; 256],
            of: [0; 256],
            extra_bits: 0,
        }
    }
}

pub(crate) struct BlockEncodeWorkspace {
    /// Literals of the last packed block in `lit_buf[..lit_len]`. The buffer
    /// only grows, so packing a block does not clear it.
    pub lit_buf: Vec<u8>,
    lit_len: usize,
    pub lit_section: Vec<u8>,
    pub pred_seq: Vec<u8>,
    pub cust_seq: Vec<u8>,
    pub repeat_seq: Vec<u8>,
    /// Huffman literal streams; bytes past the encoded length are scratch.
    pub huf_concat: Vec<u8>,
    pub pred_writer_buf: Vec<u8>,
    pub cust_writer_buf: Vec<u8>,
    pub repeat_writer_buf: Vec<u8>,
    /// Sequences of the last packed block in `packed_seqs[..num_packed]`.
    packed_seqs: Vec<PackedSeq>,
    num_packed: usize,
    seq_freqs: SeqFreqs,
    custom_seq_tables: CustomSeqTables,
    pub prev_huffman: Option<HuffmanEncodeTable>,
    pub prev_ll: Option<FseEncodeTable>,
    pub prev_of: Option<FseEncodeTable>,
    pub prev_ml: Option<FseEncodeTable>,
}

impl BlockEncodeWorkspace {
    pub fn new() -> Self {
        Self {
            lit_buf: Vec::new(),
            lit_len: 0,
            lit_section: Vec::new(),
            pred_seq: Vec::new(),
            cust_seq: Vec::new(),
            repeat_seq: Vec::new(),
            huf_concat: Vec::new(),
            pred_writer_buf: Vec::new(),
            cust_writer_buf: Vec::new(),
            repeat_writer_buf: Vec::new(),
            packed_seqs: Vec::new(),
            num_packed: 0,
            seq_freqs: SeqFreqs::default(),
            custom_seq_tables: CustomSeqTables::new(),
            prev_huffman: None,
            prev_ll: None,
            prev_of: None,
            prev_ml: None,
        }
    }
}

/// C zstd-style symbolTT entry. Two fields per symbol encode the
/// variable-width bit emission and state transition in one lookup.
/// Total predefined table footprint: ~1.3 KB (was ~20 KB).
#[derive(Clone, Copy)]
#[repr(C)]
struct SymbolTT {
    delta_nb_bits: u32,
    delta_find_state: i32,
}

#[derive(Clone)]
pub(crate) struct FseEncodeTable {
    symbol_tt: [SymbolTT; MAX_SYMBOLS],
    state_table: [u16; MAX_TABLE_SIZE],
    table_size: u32,
    table_log: u8,
}

impl Default for FseEncodeTable {
    fn default() -> Self {
        Self {
            symbol_tt: [SymbolTT {
                delta_nb_bits: 0,
                delta_find_state: 0,
            }; MAX_SYMBOLS],
            state_table: [0; MAX_TABLE_SIZE],
            table_size: 0,
            table_log: 0,
        }
    }
}

/// Symbol slots per table: 53 codes rounded up to a power of two, so the
/// encoders mask symbol indices instead of bounds-checking them.
const MAX_SYMBOLS: usize = 64;
const MAX_TABLE_SIZE: usize = 512;

impl FseEncodeTable {
    pub(crate) fn from_decode_table(
        decode_table: &[FseDecodeEntry],
        accuracy_log: u8,
        max_symbol: usize,
    ) -> Self {
        Self::build(decode_table, 1 << accuracy_log, max_symbol, accuracy_log)
    }

    fn build(
        decode_table: &[FseDecodeEntry],
        table_size: usize,
        max_symbol: usize,
        table_log: u8,
    ) -> Self {
        let num_symbols = max_symbol + 1;
        debug_assert!(num_symbols <= MAX_SYMBOLS);
        debug_assert!(table_size <= MAX_TABLE_SIZE);

        let mut count = [0u32; MAX_SYMBOLS];
        for i in 0..table_size {
            count[decode_table[i].symbol as usize] += 1;
        }

        let mut cumul = [0u32; MAX_SYMBOLS + 1];
        for s in 0..num_symbols {
            cumul[s + 1] = cumul[s] + count[s];
        }

        let default_delta = (table_log as u32 + 1) << 16;
        let mut symbol_tt = [SymbolTT {
            delta_nb_bits: default_delta,
            delta_find_state: 0,
        }; MAX_SYMBOLS];
        let mut total = 0i32;
        for s in 0..num_symbols {
            let c = count[s];
            if c == 0 {
                symbol_tt[s].delta_nb_bits = default_delta | (1u32 << table_log);
                continue;
            }
            let max_bits_out = if c == 1 {
                table_log as u32
            } else {
                table_log as u32 - (31 - (c - 1).leading_zeros())
            };
            let min_state_plus = c << max_bits_out;
            symbol_tt[s].delta_nb_bits = (max_bits_out << 16).wrapping_sub(min_state_plus);
            symbol_tt[s].delta_find_state = total - c as i32;
            total += c as i32;
        }

        let mut state_table = [0u16; MAX_TABLE_SIZE];
        let mut cumul_copy = cumul;
        for (i, entry) in decode_table.iter().enumerate().take(table_size) {
            let s = entry.symbol as usize;
            let idx = cumul_copy[s] as usize;
            state_table[idx] = (table_size + i) as u16;
            cumul_copy[s] += 1;
        }

        Self {
            symbol_tt,
            state_table,
            table_size: table_size as u32,
            table_log,
        }
    }

    fn build_from_distribution_into(
        &mut self,
        distribution: &[i16],
        table_log: u8,
        max_symbol: usize,
    ) -> bool {
        let table_size = 1usize << table_log;
        let num_symbols = max_symbol + 1;
        debug_assert!(num_symbols <= MAX_SYMBOLS);
        debug_assert!(table_size <= MAX_TABLE_SIZE);

        let mut count = [0u32; MAX_SYMBOLS];
        for s in 0..num_symbols {
            let probability = distribution[s];
            count[s] = if probability == -1 {
                1
            } else if probability > 0 {
                probability as u32
            } else {
                0
            };
        }

        let mut cumul = [0u32; MAX_SYMBOLS + 1];
        for s in 0..num_symbols {
            cumul[s + 1] = cumul[s] + count[s];
        }

        let default_delta = (table_log as u32 + 1) << 16;
        let mut symbol_tt = [SymbolTT {
            delta_nb_bits: default_delta,
            delta_find_state: 0,
        }; MAX_SYMBOLS];
        let mut total = 0i32;
        for s in 0..num_symbols {
            let c = count[s];
            if c == 0 {
                symbol_tt[s].delta_nb_bits = default_delta | (1u32 << table_log);
                continue;
            }
            let max_bits_out = if c == 1 {
                table_log as u32
            } else {
                table_log as u32 - (31 - (c - 1).leading_zeros())
            };
            let min_state_plus = c << max_bits_out;
            symbol_tt[s].delta_nb_bits = (max_bits_out << 16).wrapping_sub(min_state_plus);
            symbol_tt[s].delta_find_state = total - c as i32;
            total += c as i32;
        }

        let step = (table_size >> 1) + (table_size >> 3) + 3;
        let mask = table_size - 1;
        let mut high_threshold = table_size - 1;
        let mut table_symbols = [0u8; MAX_TABLE_SIZE];

        for (s, &probability) in distribution.iter().enumerate().take(num_symbols) {
            if probability == -1 {
                if high_threshold == 0 {
                    return false;
                }
                table_symbols[high_threshold] = s as u8;
                high_threshold -= 1;
            }
        }

        let mut position = 0usize;
        if high_threshold == table_size - 1 {
            for (s, &probability) in distribution.iter().enumerate().take(num_symbols) {
                if probability <= 0 {
                    continue;
                }
                let symbol = s as u8;
                let mut remaining = probability as usize;
                while remaining >= 4 {
                    table_symbols[position] = symbol;
                    position = (position + step) & mask;
                    table_symbols[position] = symbol;
                    position = (position + step) & mask;
                    table_symbols[position] = symbol;
                    position = (position + step) & mask;
                    table_symbols[position] = symbol;
                    position = (position + step) & mask;
                    remaining -= 4;
                }
                for _ in 0..remaining {
                    table_symbols[position] = symbol;
                    position = (position + step) & mask;
                }
            }
        } else {
            for (s, &probability) in distribution.iter().enumerate().take(num_symbols) {
                if probability <= 0 {
                    continue;
                }
                for _ in 0..probability {
                    table_symbols[position] = s as u8;
                    position = (position + step) & mask;
                    while position > high_threshold {
                        position = (position + step) & mask;
                    }
                }
            }
        }

        if position != 0 {
            return false;
        }

        self.symbol_tt.fill(SymbolTT {
            delta_nb_bits: default_delta,
            delta_find_state: 0,
        });
        self.state_table[..table_size].fill(0);
        self.table_size = table_size as u32;
        self.table_log = table_log;

        self.symbol_tt[..num_symbols].copy_from_slice(&symbol_tt[..num_symbols]);

        let mut cumul_copy = cumul;
        for (i, &symbol) in table_symbols.iter().enumerate().take(table_size) {
            let s = symbol as usize;
            let idx = cumul_copy[s] as usize;
            self.state_table[idx] = (table_size + i) as u16;
            cumul_copy[s] += 1;
        }

        true
    }

    /// Encodes `symbol` from `state`. Returns the low state bits to emit,
    /// their count, and the next state. The masks keep indices in bounds
    /// without a check; valid tables never need them.
    #[inline(always)]
    fn transition(&self, symbol: u8, state: u32) -> (u32, u32, u32) {
        let tt = &self.symbol_tt[usize::from(symbol) & (MAX_SYMBOLS - 1)];
        let nb = tt.delta_nb_bits.wrapping_add(state) >> 16;
        let idx = ((state >> nb) as i32 + tt.delta_find_state) as usize;
        let next = u32::from(self.state_table[idx & (MAX_TABLE_SIZE - 1)]);
        (state & ((1u32 << nb) - 1), nb, next)
    }

    #[inline]
    fn init_state(&self, symbol: u8) -> u32 {
        let tt = &self.symbol_tt[symbol as usize];
        let nb_bits_out = tt.delta_nb_bits.wrapping_add(1 << 15) >> 16;
        let base_state = (nb_bits_out << 16).wrapping_sub(tt.delta_nb_bits);
        let idx = (base_state >> nb_bits_out) as i32 + tt.delta_find_state;
        debug_assert!(idx >= 0);
        self.state_table[idx as usize] as u32
    }
}

#[cfg(feature = "std")]
static PREDEFINED_TABLES: std::sync::LazyLock<PredefinedEncodeTables> =
    std::sync::LazyLock::new(PredefinedEncodeTables::build);

#[cfg(feature = "std")]
fn predefined_tables() -> &'static PredefinedEncodeTables {
    &PREDEFINED_TABLES
}

#[cfg(not(feature = "std"))]
fn predefined_tables() -> PredefinedEncodeTables {
    PredefinedEncodeTables::build()
}

struct PredefinedEncodeTables {
    ll: FseEncodeTable,
    ml: FseEncodeTable,
    of: FseEncodeTable,
}

impl PredefinedEncodeTables {
    fn build() -> Self {
        use zrip_core::fse::table_builder::build_decode_table_from_default;

        let ll_decode = build_decode_table_from_default(&LL_DEFAULT_DIST, LL_DEFAULT_ACCURACY);
        let ml_decode = build_decode_table_from_default(&ML_DEFAULT_DIST, ML_DEFAULT_ACCURACY);
        let of_decode = build_decode_table_from_default(&OF_DEFAULT_DIST, OF_DEFAULT_ACCURACY);

        Self {
            ll: FseEncodeTable::build(
                &ll_decode,
                1 << LL_DEFAULT_ACCURACY,
                35,
                LL_DEFAULT_ACCURACY,
            ),
            ml: FseEncodeTable::build(
                &ml_decode,
                1 << ML_DEFAULT_ACCURACY,
                52,
                ML_DEFAULT_ACCURACY,
            ),
            of: FseEncodeTable::build(
                &of_decode,
                1 << OF_DEFAULT_ACCURACY,
                31,
                OF_DEFAULT_ACCURACY,
            ),
        }
    }
}

pub fn encode_raw_block(
    data: &[u8],
    last: bool,
    output: &mut impl OutputSink,
) -> Result<(), CompressError> {
    let block_size = data.len() as u32;
    let header = (block_size << 3) | if last { 1 } else { 0 };
    output.push(header as u8)?;
    output.push((header >> 8) as u8)?;
    output.push((header >> 16) as u8)?;
    output.extend_from_slice(data)
}

pub(crate) fn encode_compressed_block(
    src: &[u8],
    sequences: &[Sequence],
    rep_offsets: &mut [u32; 3],
    last: bool,
    output: &mut impl OutputSink,
    workspace: &mut BlockEncodeWorkspace,
    policy: BlockPolicy,
) -> Result<(), CompressError> {
    simd_body!(encode_compressed_block_impl(
        src,
        sequences,
        rep_offsets,
        last,
        output,
        workspace,
        policy
    ))
}

#[inline(always)]
fn encode_compressed_block_impl(
    src: &[u8],
    sequences: &[Sequence],
    rep_offsets: &mut [u32; 3],
    last: bool,
    output: &mut impl OutputSink,
    workspace: &mut BlockEncodeWorkspace,
    policy: BlockPolicy,
) -> Result<(), CompressError> {
    let n = sequences.len();
    let total_match: usize = sequences.iter().map(|s| s.match_length as usize).sum();
    if n == 0 || total_match <= n * 3 {
        return encode_literals_only_block(src, last, output, workspace, policy);
    }

    let saved_rep = *rep_offsets;

    pack_sequences_and_literals::<true>(src, sequences, rep_offsets, workspace);

    let raw_literals = encode_literals_section(
        &workspace.lit_buf[..workspace.lit_len],
        n,
        &mut workspace.lit_section,
        &mut workspace.huf_concat,
        &mut workspace.prev_huffman,
        policy,
    );

    let has_repeat =
        workspace.prev_ll.is_some() && workspace.prev_of.is_some() && workspace.prev_ml.is_some();

    if has_repeat {
        encode_seq_repeat(
            &workspace.packed_seqs[..workspace.num_packed],
            workspace.prev_ll.as_ref().unwrap(),
            workspace.prev_of.as_ref().unwrap(),
            workspace.prev_ml.as_ref().unwrap(),
            &mut workspace.repeat_seq,
            &mut workspace.repeat_writer_buf,
        );
    }

    let do_codes = policy.custom_tables && n >= 64;
    let seq_data = if do_codes {
        let f = &workspace.seq_freqs;
        let ll_freq = f.ll.first_chunk::<36>().unwrap();
        let ml_freq = f.ml.first_chunk::<53>().unwrap();
        let of_freq = f.of.first_chunk::<32>().unwrap();
        let pred_est = estimate_predefined_cost(ll_freq, ml_freq, of_freq, f.extra_bits, n);
        let use_custom = encode_seq_custom(
            &workspace.packed_seqs[..workspace.num_packed],
            ll_freq,
            ml_freq,
            of_freq,
            n,
            pred_est,
            &mut workspace.cust_seq,
            &mut workspace.cust_writer_buf,
            &mut workspace.custom_seq_tables,
        );
        if use_custom && workspace.cust_seq.len() < pred_est {
            &workspace.cust_seq
        } else {
            encode_seq_predefined(
                &workspace.packed_seqs[..workspace.num_packed],
                &mut workspace.pred_seq,
                &mut workspace.pred_writer_buf,
            );
            if use_custom && workspace.cust_seq.len() < workspace.pred_seq.len() {
                &workspace.cust_seq
            } else {
                &workspace.pred_seq
            }
        }
    } else {
        encode_seq_predefined(
            &workspace.packed_seqs[..workspace.num_packed],
            &mut workspace.pred_seq,
            &mut workspace.pred_writer_buf,
        );
        &workspace.pred_seq
    };

    let seq_data = if has_repeat && workspace.repeat_seq.len() < seq_data.len() {
        &workspace.repeat_seq
    } else {
        seq_data
    };

    // Clear dict FSE tables after first block.
    workspace.prev_ll = None;
    workspace.prev_of = None;
    workspace.prev_ml = None;

    let literal_section_len =
        workspace.lit_section.len() + if raw_literals { workspace.lit_len } else { 0 };
    let block_len = literal_section_len + seq_data.len();
    if block_len >= src.len() {
        *rep_offsets = saved_rep;
        // The decoder never sees this block's table, so it cannot be reused.
        workspace.prev_huffman = None;
        return encode_raw_block(src, last, output);
    }

    let block_size = block_len as u32;
    let header = (block_size << 3) | 0x04 | if last { 1 } else { 0 };
    output.push(header as u8)?;
    output.push((header >> 8) as u8)?;
    output.push((header >> 16) as u8)?;
    output.extend_from_slice(&workspace.lit_section)?;
    if raw_literals {
        output.extend_from_slice(&workspace.lit_buf[..workspace.lit_len])?;
    }
    output.extend_from_slice(seq_data)
}

/// Encodes a block without sequences: Huffman-coded literals and an empty
/// sequence section. Falls back to a raw block when that is not smaller.
fn encode_literals_only_block(
    src: &[u8],
    last: bool,
    output: &mut impl OutputSink,
    workspace: &mut BlockEncodeWorkspace,
    policy: BlockPolicy,
) -> Result<(), CompressError> {
    let raw_literals = encode_literals_section(
        src,
        0,
        &mut workspace.lit_section,
        &mut workspace.huf_concat,
        &mut workspace.prev_huffman,
        policy,
    );
    // One byte for the empty sequence section (Number_of_Sequences = 0).
    let block_len = workspace.lit_section.len() + 1;
    if raw_literals || block_len >= src.len() {
        // The decoder never sees this block's table, so it cannot be reused.
        workspace.prev_huffman = None;
        return encode_raw_block(src, last, output);
    }
    let header = ((block_len as u32) << 3) | 0x04 | u32::from(last);
    output.push(header as u8)?;
    output.push((header >> 8) as u8)?;
    output.push((header >> 16) as u8)?;
    output.extend_from_slice(&workspace.lit_section)?;
    output.push(0)
}

/// Encoding choices for a raw-literal block that is almost all literals:
/// Huffman literals for runs over 32 KiB below 6.09 bits per byte, with the
/// predefined sequence tables. The gate sits below the other negative
/// levels' 6.25, so L-7 compresses such data a little, less than L-6.
const LITERAL_HEAVY_POLICY: BlockPolicy = BlockPolicy {
    custom_tables: false,
    max_literal_entropy_fp8: 6 * 256 + 24,
};

pub(crate) fn encode_compressed_block_raw(
    src: &[u8],
    sequences: &[Sequence],
    rep_offsets: &mut [u32; 3],
    last: bool,
    output: &mut impl OutputSink,
    workspace: &mut BlockEncodeWorkspace,
) -> Result<(), CompressError> {
    simd_body!(encode_compressed_block_raw_impl(
        src,
        sequences,
        rep_offsets,
        last,
        output,
        workspace
    ))
}

#[inline(always)]
fn encode_compressed_block_raw_impl(
    src: &[u8],
    sequences: &[Sequence],
    rep_offsets: &mut [u32; 3],
    last: bool,
    output: &mut impl OutputSink,
    workspace: &mut BlockEncodeWorkspace,
) -> Result<(), CompressError> {
    let n = sequences.len();
    let total_match: usize = sequences.iter().map(|s| s.match_length as usize).sum();
    // Matches covering under 1/8 of the block leave raw literals almost no
    // compression, so such blocks try Huffman literals. Only runs over
    // 32 KiB can take them, and a sample of the block, which is nearly all
    // literals, rules out dense ones before the literals are gathered.
    if total_match < src.len() / 8
        && src.len() > 32 * 1024
        && !histogram_too_dense(
            &byte_histogram(&src[..DENSITY_SAMPLE]),
            LITERAL_HEAVY_POLICY.max_literal_entropy_fp8,
        )
    {
        return encode_compressed_block_impl(
            src,
            sequences,
            rep_offsets,
            last,
            output,
            workspace,
            LITERAL_HEAVY_POLICY,
        );
    }
    if total_match <= n * 3 {
        return encode_raw_block(src, last, output);
    }

    let saved_rep = *rep_offsets;

    pack_sequences_and_literals::<false>(src, sequences, rep_offsets, workspace);

    workspace.lit_section.clear();
    encode_raw_literals_header(workspace.lit_len, &mut workspace.lit_section);

    encode_seq_predefined(
        &workspace.packed_seqs[..workspace.num_packed],
        &mut workspace.pred_seq,
        &mut workspace.pred_writer_buf,
    );

    let block_len = workspace.lit_section.len() + workspace.lit_len + workspace.pred_seq.len();
    if block_len >= src.len() {
        *rep_offsets = saved_rep;
        return encode_raw_block(src, last, output);
    }

    let block_size = block_len as u32;
    let header = (block_size << 3) | 0x04 | if last { 1 } else { 0 };
    output.push(header as u8)?;
    output.push((header >> 8) as u8)?;
    output.push((header >> 16) as u8)?;
    output.extend_from_slice(&workspace.lit_section)?;
    output.extend_from_slice(&workspace.lit_buf[..workspace.lit_len])?;
    output.extend_from_slice(&workspace.pred_seq)
}

/// Packs `sequences` for the entropy coders and gathers their literals. With
/// `COUNT`, also counts the codes for custom tables.
fn pack_sequences_and_literals<const COUNT: bool>(
    src: &[u8],
    sequences: &[Sequence],
    rep_offsets: &mut [u32; 3],
    workspace: &mut BlockEncodeWorkspace,
) {
    simd_body!(pack_sequences_and_literals_impl::<COUNT>(
        src,
        sequences,
        rep_offsets,
        workspace
    ));
}

#[inline(always)]
fn pack_sequences_and_literals_impl<const COUNT: bool>(
    src: &[u8],
    sequences: &[Sequence],
    rep_offsets: &mut [u32; 3],
    workspace: &mut BlockEncodeWorkspace,
) {
    let n = sequences.len();
    let src_len = src.len();

    if workspace.lit_buf.len() < src_len + 32 {
        workspace.lit_buf.resize(src_len + 32, 0);
    }
    if workspace.packed_seqs.len() < n {
        workspace.packed_seqs.resize(n, PackedSeq::default());
    }
    // The exact length lets the compiler check literal stores at positions
    // clamped to `src_len` against nothing.
    let lit_buf = &mut workspace.lit_buf[..src_len + 32];
    let freqs = &mut workspace.seq_freqs;
    if COUNT {
        freqs.ll.fill(0);
        freqs.ml.fill(0);
        freqs.of.fill(0);
    }
    let mut extra_bits_total = 0u64;
    let mut lit_pos = 0usize;
    let mut lit_offset = 0usize;

    let mut rep0 = rep_offsets[0];
    let mut rep1 = rep_offsets[1];
    let mut rep2 = rep_offsets[2];

    for (seq, packed) in sequences.iter().zip(&mut workspace.packed_seqs[..n]) {
        let ll = seq.literal_length as usize;
        debug_assert!(lit_offset + ll <= src_len);
        if ll <= 32 && lit_offset + 32 <= src_len {
            let s32: &[u8; 32] = src[lit_offset..].first_chunk().unwrap();
            let d32: &mut [u8; 32] = lit_buf[lit_pos.min(src_len)..].first_chunk_mut().unwrap();
            *d32 = *s32;
        } else {
            lit_buf[lit_pos..lit_pos + ll].copy_from_slice(&src[lit_offset..lit_offset + ll]);
        }
        lit_pos += ll;
        lit_offset += ll + seq.match_length as usize;

        // Repeat offsets for codes 1 to 3. Without literals, code 1 means the
        // second offset and code 3 the first offset minus one. Selects instead
        // of branches: rep and new offsets interleave unpredictably.
        let off = seq.offset;
        let no_lits = seq.literal_length == 0;
        let (c1, c2, c3) = if no_lits {
            (rep1, rep2, rep0 - 1)
        } else {
            (rep0, rep1, rep2)
        };
        let mut ov = if off == c3 { 3 } else { off + 3 };
        if off == c2 {
            ov = 2;
        }
        if off == c1 {
            ov = 1;
        }
        // Code 1 with literals keeps the history; the code naming the second
        // offset swaps the first two; every other code shifts in `off`.
        let keep = !no_lits && ov == 1;
        let swap = ov == 2 - u32::from(no_lits);
        if !(keep || swap) {
            rep2 = rep1;
        }
        if !keep {
            rep1 = rep0;
        }
        rep0 = off;

        let (ll_c, ll_nb, ll_extra) = ll_split(seq.literal_length);
        let (ml_c, ml_nb, ml_extra) = ml_split(seq.match_length);
        let of_c = of_code(ov);
        let of_extra = ov - (1u32 << of_c);
        let extra_bits = (ll_extra as u64)
            | ((ml_extra as u64) << ll_nb)
            | ((of_extra as u64) << (ll_nb + ml_nb));
        let extra_nbits = (ll_nb + ml_nb) as u8 + of_c;

        if COUNT {
            freqs.ll[usize::from(ll_c)] += 1;
            freqs.ml[usize::from(ml_c)] += 1;
            freqs.of[usize::from(of_c)] += 1;
            extra_bits_total += u64::from(extra_nbits);
        }

        *packed = PackedSeq {
            extra_bits,
            ll_c,
            ml_c,
            of_c,
            extra_nbits,
        };
    }
    rep_offsets[0] = rep0;
    rep_offsets[1] = rep1;
    rep_offsets[2] = rep2;

    if lit_offset < src_len {
        let rest = src_len - lit_offset;
        lit_buf[lit_pos..lit_pos + rest].copy_from_slice(&src[lit_offset..src_len]);
        lit_pos += rest;
    }
    freqs.extra_bits = extra_bits_total;
    workspace.lit_len = lit_pos;
    workspace.num_packed = n;
}

/// Approximate log2(x) in 8.8 fixed point (result = log2(x) * 256).
pub(crate) fn log2_fp8(x: u32) -> u32 {
    if x <= 1 {
        return 0;
    }
    let msb = 31 - x.leading_zeros();
    let shifted = if msb > 8 {
        x >> (msb - 8)
    } else {
        x << (8 - msb)
    };
    msb * 256 + (shifted - 256)
}

/// Cheap entropy estimate: returns true if Huffman is likely to produce savings.
/// Avoids the expensive build-table-encode-discard cycle for blocks where
/// Huffman overhead exceeds the compression benefit.
fn huf_worth_trying(data: &[u8]) -> bool {
    if data.len() > 32768 {
        return true;
    }
    if data.len() < 32768 {
        return false;
    }

    let n = data.len() as u32;
    let mut freqs = [0u32; 256];
    let mut max_sym = 0u8;
    for &b in data {
        freqs[b as usize] += 1;
        if b > max_sym {
            max_sym = b;
        }
    }

    if max_sym > 128 {
        return false;
    }

    let active = freqs[..=max_sym as usize]
        .iter()
        .filter(|&&f| f > 0)
        .count();
    if active < 2 {
        return false;
    }

    let log2_n = log2_fp8(n);
    let mut entropy_bits_fp8: u64 = 0;
    for &f in &freqs[..=max_sym as usize] {
        if f > 0 {
            entropy_bits_fp8 += f as u64 * (log2_n - log2_fp8(f)) as u64;
        }
    }

    let estimated_bytes = entropy_bits_fp8.div_ceil(2048);
    let tree_overhead = 1 + (max_sym as u64).div_ceil(2);
    let min_gain = n as u64 / 32;

    estimated_bytes + tree_overhead + min_gain < n as u64
}

/// Literals the entropy gate samples. Shorter literal runs are measured
/// from their full histogram.
const DENSITY_SAMPLE: usize = 4096;

/// Whether bytes with these counts have an order-0 entropy above
/// `limit_fp8` bits per byte (8.8 fixed point).
fn histogram_too_dense(counts: &[u32; 256], limit_fp8: u32) -> bool {
    let n: u32 = counts.iter().sum();
    if n == 0 {
        return false;
    }
    let log2_n = log2_fp8(n);
    let bits_fp8: u64 = counts
        .iter()
        .filter(|&&c| c > 0)
        .map(|&c| u64::from(c) * u64::from(log2_n - log2_fp8(c)))
        .sum();
    bits_fp8 > u64::from(limit_fp8) * u64::from(n)
}

/// Literals sampled from each end before the full histogram when they look
/// incompressible.
const SUSPECT_SAMPLE: usize = 4096;

/// Literals above this order-0 entropy (bits per byte, 8.8 fixed point) stay
/// raw: Huffman would save under 0.4%, less than its table costs. Random bytes
/// measure about 8.02 with the `log2_fp8` estimate.
const FLAT_LITERALS_FP8: u32 = 8 * 256 - 8;

fn encode_literals_section(
    lits: &[u8],
    num_seq: usize,
    output: &mut Vec<u8>,
    huf_concat: &mut Vec<u8>,
    prev_huffman: &mut Option<HuffmanEncodeTable>,
    policy: BlockPolicy,
) -> bool {
    output.clear();

    let try_huffman_literals = policy.custom_tables;

    // Like C zstd: from 256 literals, four streams decode in parallel and
    // repay their 6-byte jump table.
    let use_4_streams = lits.len() >= 256;
    let encode = |table: &HuffmanEncodeTable, concat: &mut Vec<u8>| {
        if use_4_streams {
            table.encode_4_streams_into(lits, concat)
        } else {
            table.encode_single_stream_into(lits, concat)
        }
    };

    // Pick between reusing the previous table, a fresh table with its
    // description, and raw bytes by estimated size, as C zstd does. Reuse is
    // only a win when the old table still fits these literals.
    let want_fresh = try_huffman_literals || huf_worth_trying(lits);
    if prev_huffman.is_none() && !want_fresh {
        encode_raw_literals_header(lits.len(), output);
        return true;
    }
    // Dense literals stay raw. Long runs are judged by a sample, so they
    // skip the full histogram when they fail.
    let limit = policy.max_literal_entropy_fp8;
    let sample = (limit != u32::MAX && lits.len() > DENSITY_SAMPLE)
        .then(|| byte_histogram(&lits[..DENSITY_SAMPLE]));
    if sample.is_some_and(|sample| histogram_too_dense(&sample, limit)) {
        *prev_huffman = None;
        encode_raw_literals_header(lits.len(), output);
        return true;
    }
    // Few sequences per literal suggest incompressible bytes. As in C zstd,
    // two small samples then rule out Huffman before the full histogram.
    let suspect = num_seq == 0 || lits.len() / num_seq >= 20;
    if suspect && lits.len() >= 2 * SUSPECT_SAMPLE {
        let head = byte_histogram(&lits[..SUSPECT_SAMPLE]);
        let tail = byte_histogram(&lits[lits.len() - SUSPECT_SAMPLE..]);
        let sample: [u32; 256] = core::array::from_fn(|i| head[i] + tail[i]);
        if histogram_too_dense(&sample, FLAT_LITERALS_FP8) {
            *prev_huffman = None;
            encode_raw_literals_header(lits.len(), output);
            return true;
        }
    }
    // The density sample already counted the head.
    let freqs = match sample {
        Some(head) => {
            let rest = byte_histogram(&lits[DENSITY_SAMPLE..]);
            core::array::from_fn(|i| head[i] + rest[i])
        }
        None => byte_histogram(lits),
    };
    if histogram_too_dense(&freqs, FLAT_LITERALS_FP8) {
        *prev_huffman = None;
        encode_raw_literals_header(lits.len(), output);
        return true;
    }
    if limit != u32::MAX && lits.len() <= DENSITY_SAMPLE && histogram_too_dense(&freqs, limit) {
        *prev_huffman = None;
        encode_raw_literals_header(lits.len(), output);
        return true;
    }
    let reuse_bits = prev_huffman.as_ref().and_then(|p| p.estimate_bits(&freqs));
    let fresh = if want_fresh {
        HuffmanEncodeTable::from_histogram(&freqs).map(|t| {
            let bits = t.estimate_bits(&freqs).unwrap_or(u64::MAX)
                + t.weights_description().len() as u64 * 8;
            (t, bits)
        })
    } else {
        None
    };
    let fresh_bits = fresh.as_ref().map_or(u64::MAX, |f| f.1);
    // The estimates are lower bounds: when neither beats raw bytes, skip the
    // encode.
    if reuse_bits.unwrap_or(u64::MAX).min(fresh_bits) / 8 >= lits.len() as u64 {
        *prev_huffman = None;
        encode_raw_literals_header(lits.len(), output);
        return true;
    }

    if let Some(bits) = reuse_bits
        && bits <= fresh_bits
    {
        let len = encode(prev_huffman.as_ref().unwrap(), huf_concat);
        if len < lits.len() {
            encode_treeless_literals_header(lits.len(), len, use_4_streams, output);
            output.extend_from_slice(&huf_concat[..len]);
            return false;
        }
    } else if let Some((table, _)) = fresh {
        let len = encode(&table, huf_concat);
        let tree_desc = table.weights_description();
        let compressed_size = tree_desc.len() + len;
        if compressed_size < lits.len() {
            encode_compressed_literals_header(lits.len(), compressed_size, use_4_streams, output);
            output.extend_from_slice(tree_desc);
            output.extend_from_slice(&huf_concat[..len]);
            *prev_huffman = Some(table);
            return false;
        }
    }

    *prev_huffman = None;
    encode_raw_literals_header(lits.len(), output);
    true
}

fn encode_treeless_literals_header(
    regen_size: usize,
    comp_size: usize,
    four_streams: bool,
    output: &mut Vec<u8>,
) {
    encode_huf_literals_header(0x03, regen_size, comp_size, four_streams, output);
}

fn encode_compressed_literals_header(
    regen_size: usize,
    comp_size: usize,
    four_streams: bool,
    output: &mut Vec<u8>,
) {
    encode_huf_literals_header(0x02, regen_size, comp_size, four_streams, output);
}

fn encode_huf_literals_header(
    block_type: u8,
    regen_size: usize,
    comp_size: usize,
    four_streams: bool,
    output: &mut Vec<u8>,
) {
    if regen_size <= 1023 && comp_size <= 1023 {
        let size_format: u8 = if four_streams { 1 } else { 0 };
        let both = (regen_size as u32) | ((comp_size as u32) << 10);
        output.push(block_type | (size_format << 2) | (((both & 0x0F) as u8) << 4));
        output.push((both >> 4) as u8);
        output.push((both >> 12) as u8);
    } else if regen_size <= 16383 && comp_size <= 16383 {
        let both = (regen_size as u32) | ((comp_size as u32) << 14);
        output.push(block_type | (2 << 2) | (((both & 0x0F) as u8) << 4));
        output.push((both >> 4) as u8);
        output.push((both >> 12) as u8);
        output.push((both >> 20) as u8);
    } else {
        let both = (regen_size as u64) | ((comp_size as u64) << 18);
        output.push(block_type | (3 << 2) | (((both & 0x0F) as u8) << 4));
        output.push((both >> 4) as u8);
        output.push((both >> 12) as u8);
        output.push((both >> 20) as u8);
        output.push((both >> 28) as u8);
    }
}

fn encode_raw_literals_header(size: usize, output: &mut Vec<u8>) {
    if size <= 31 {
        output.push((size as u8) << 3);
    } else if size <= 4095 {
        let b0 = 0x04 | ((size as u8 & 0x0F) << 4);
        let b1 = (size >> 4) as u8;
        output.push(b0);
        output.push(b1);
    } else {
        let b0 = 0x0C | ((size as u8 & 0x0F) << 4);
        let b1 = (size >> 4) as u8;
        let b2 = (size >> 12) as u8;
        output.push(b0);
        output.push(b1);
        output.push(b2);
    }
}

fn encode_seq_predefined(packed: &[PackedSeq], output: &mut Vec<u8>, writer_buf: &mut Vec<u8>) {
    simd_body!(encode_seq_predefined_impl(packed, output, writer_buf));
}

#[inline(always)]
fn encode_seq_predefined_impl(
    packed: &[PackedSeq],
    output: &mut Vec<u8>,
    writer_buf: &mut Vec<u8>,
) {
    let n = packed.len();
    let num_seq = n as u32;
    output.clear();
    output.reserve(n * 4 + 4);

    write_seq_count(output, num_seq);

    output.push(0x00);

    let tables = predefined_tables();
    let last = &packed[n - 1];

    let max_out = n * 18 + 16;
    let mut bitstream = primitives::BitstreamScratch::new(writer_buf, max_out);

    let mut ll_state = tables.ll.init_state(last.ll_c);
    let mut of_state = tables.of.init_state(last.of_c);
    let mut ml_state = tables.ml.init_state(last.ml_c);

    let mut pos: usize = 0;
    let mut bits: u64 = 0;
    let mut bits_used: u32 = 0;

    macro_rules! add_bits {
        ($val:expr, $n:expr) => {
            bits |= ($val as u64) << bits_used;
            bits_used += $n as u32;
        };
    }
    macro_rules! flush_fast {
        () => {
            bitstream.flush(pos, bits);
            let nb = (bits_used >> 3) as usize;
            pos += nb;
            bits >>= (nb << 3) as u64;
            bits_used &= 7;
        };
    }
    add_extra_bits_macro!(add_extra_bits, add_bits, flush_fast);
    macro_rules! encode_transition {
        ($table:expr, $symbol:expr, $state:expr) => {{
            let (out, nb, next) = $table.transition($symbol, $state);
            add_bits!(out, nb);
            $state = next;
        }};
    }

    add_bits!(last.extra_bits, last.extra_nbits);

    for k in (0..n - 1).rev() {
        let p = &packed[k];

        flush_fast!();
        encode_transition!(tables.of, p.of_c, of_state);
        encode_transition!(tables.ml, p.ml_c, ml_state);
        encode_transition!(tables.ll, p.ll_c, ll_state);
        add_extra_bits!(p);
    }

    flush_fast!();
    let ll_ts = tables.ll.table_size;
    let of_ts = tables.of.table_size;
    let ml_ts = tables.ml.table_size;
    add_bits!(ml_state - ml_ts, ML_DEFAULT_ACCURACY);
    add_bits!(of_state - of_ts, OF_DEFAULT_ACCURACY);
    add_bits!(ll_state - ll_ts, LL_DEFAULT_ACCURACY);

    add_bits!(1u32, 1u8);
    flush_fast!();
    while bits_used > 0 {
        bitstream.write_byte(pos, bits as u8);
        bits >>= 8;
        bits_used = bits_used.saturating_sub(8);
        pos += 1;
    }
    bitstream.finish(pos);
    output.extend_from_slice(bitstream.as_slice());
}

fn encode_seq_repeat(
    packed: &[PackedSeq],
    ll_t: &FseEncodeTable,
    of_t: &FseEncodeTable,
    ml_t: &FseEncodeTable,
    output: &mut Vec<u8>,
    writer_buf: &mut Vec<u8>,
) {
    simd_body!(encode_seq_repeat_impl(
        packed, ll_t, of_t, ml_t, output, writer_buf
    ));
}

#[inline(always)]
fn encode_seq_repeat_impl(
    packed: &[PackedSeq],
    ll_t: &FseEncodeTable,
    of_t: &FseEncodeTable,
    ml_t: &FseEncodeTable,
    output: &mut Vec<u8>,
    writer_buf: &mut Vec<u8>,
) {
    let n = packed.len();
    let num_seq = n as u32;
    output.clear();
    output.reserve(n * 4 + 4);

    write_seq_count(output, num_seq);

    // Mode byte: repeat (3) for all three streams
    output.push((3 << 6) | (3 << 4) | (3 << 2));

    let last = &packed[n - 1];

    let max_out = n * 18 + 16;
    let mut bitstream = primitives::BitstreamScratch::new(writer_buf, max_out);

    let mut ll_s = ll_t.init_state(last.ll_c);
    let mut of_s = of_t.init_state(last.of_c);
    let mut ml_s = ml_t.init_state(last.ml_c);

    let mut pos: usize = 0;
    let mut bits: u64 = 0;
    let mut bits_used: u32 = 0;

    macro_rules! add_bits {
        ($val:expr, $n:expr) => {
            bits |= ($val as u64) << bits_used;
            bits_used += $n as u32;
        };
    }
    macro_rules! flush_fast {
        () => {
            bitstream.flush(pos, bits);
            let nb = (bits_used >> 3) as usize;
            pos += nb;
            bits >>= (nb << 3) as u64;
            bits_used &= 7;
        };
    }
    add_extra_bits_macro!(add_extra_bits, add_bits, flush_fast);

    add_bits!(last.extra_bits, last.extra_nbits);

    for k in (0..n - 1).rev() {
        let p = &packed[k];

        flush_fast!();
        {
            let (out, nb, next) = of_t.transition(p.of_c, of_s);
            add_bits!(out, nb);
            of_s = next;
        }
        {
            let (out, nb, next) = ml_t.transition(p.ml_c, ml_s);
            add_bits!(out, nb);
            ml_s = next;
        }
        {
            let (out, nb, next) = ll_t.transition(p.ll_c, ll_s);
            add_bits!(out, nb);
            ll_s = next;
        }
        add_extra_bits!(p);
    }

    flush_fast!();
    add_bits!(ml_s - ml_t.table_size, ml_t.table_log);
    add_bits!(of_s - of_t.table_size, of_t.table_log);
    add_bits!(ll_s - ll_t.table_size, ll_t.table_log);

    add_bits!(1u32, 1u8);
    flush_fast!();
    while bits_used > 0 {
        bitstream.write_byte(pos, bits as u8);
        bits >>= 8;
        bits_used = bits_used.saturating_sub(8);
        pos += 1;
    }
    bitstream.finish(pos);
    output.extend_from_slice(bitstream.as_slice());
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum TableMode {
    Compressed,
    Rle(u8),
}

struct TableEnc {
    mode: TableMode,
    enc_table: FseEncodeTable,
    header: Vec<u8>,
    dist: Vec<i16>,
}

impl TableEnc {
    fn new() -> Self {
        Self {
            mode: TableMode::Rle(0),
            enc_table: FseEncodeTable::default(),
            header: Vec::new(),
            dist: Vec::new(),
        }
    }
}

struct CustomSeqTables {
    ll: TableEnc,
    of: TableEnc,
    ml: TableEnc,
}

impl CustomSeqTables {
    fn new() -> Self {
        Self {
            ll: TableEnc::new(),
            of: TableEnc::new(),
            ml: TableEnc::new(),
        }
    }
}

fn normalize_counts_into(freqs: &[u32], accuracy_log: u8, dist: &mut Vec<i16>) {
    let table_size = 1i32 << accuracy_log;
    let total: u64 = freqs.iter().map(|&f| f as u64).sum();

    dist.resize(freqs.len(), 0);
    dist.fill(0);

    if total == 0 {
        return;
    }

    let mut largest_idx = 0;
    let mut largest_freq = 0u32;
    for (i, &freq) in freqs.iter().enumerate() {
        if freq > largest_freq {
            largest_freq = freq;
            largest_idx = i;
        }
    }

    let budget = table_size - 1;
    let mut distributed = 0i32;

    for (i, &freq) in freqs.iter().enumerate() {
        if freq == 0 || i == largest_idx {
            continue;
        }
        if distributed >= budget {
            break;
        }
        let prob = ((freq as u64) * (table_size as u64) / total) as i32;
        if prob < 1 {
            dist[i] = -1;
            distributed += 1;
        } else {
            let capped = prob.min(budget - distributed);
            dist[i] = capped as i16;
            distributed += capped;
        }
    }

    dist[largest_idx] = (table_size - distributed) as i16;
}

fn serialize_fse_table_description_into(distribution: &[i16], accuracy_log: u8, out: &mut Vec<u8>) {
    let buf = core::mem::take(out);
    let mut writer = BitWriter::from_vec(buf);
    writer.write_bits((accuracy_log - 5) as u32, 4);

    let table_size = 1i32 << accuracy_log;
    let mut remaining = table_size + 1;
    let mut threshold = table_size;
    let mut nb_bits = accuracy_log + 1;

    let mut i = 0;
    while i < distribution.len() && remaining > 1 {
        let prob = distribution[i];
        let count = (prob + 1) as i32;
        let max_val = (2 * threshold - 1) - remaining;

        if count < max_val {
            writer.write_bits(count as u32, nb_bits - 1);
        } else if count < threshold {
            writer.write_bits(count as u32, nb_bits);
        } else {
            writer.write_bits((count + max_val) as u32, nb_bits);
        }

        if prob == -1 {
            remaining -= 1;
        } else if prob > 0 {
            remaining -= prob as i32;
        }

        if prob == 0 {
            let mut zeros = 0;
            let start = i + 1;
            while start + zeros < distribution.len() && distribution[start + zeros] == 0 {
                zeros += 1;
            }
            let mut z = zeros;
            loop {
                if z >= 3 {
                    writer.write_bits(3, 2);
                    z -= 3;
                } else {
                    writer.write_bits(z as u32, 2);
                    break;
                }
            }
            i += 1 + zeros;
        } else {
            i += 1;
        }

        while remaining < threshold {
            nb_bits -= 1;
            threshold >>= 1;
        }
    }

    *out = writer.into_bytes();
}

fn build_table_enc(
    out: &mut TableEnc,
    freqs: &[u32],
    max_sym: usize,
    max_log: u8,
    n: usize,
) -> bool {
    let mut num_distinct = 0usize;
    let mut rle_sym = 0usize;
    for (s, &freq) in freqs.iter().enumerate().take(max_sym + 1) {
        if freq > 0 {
            num_distinct += 1;
            rle_sym = s;
        }
    }

    out.header.clear();
    if num_distinct <= 1 {
        out.mode = TableMode::Rle(rle_sym as u8);
        return true;
    }
    let min_log_for_sym = (32 - ((num_distinct as u32 + 1).leading_zeros())) as u8;
    let acc = optimal_table_log(max_log, n, max_sym).max(min_log_for_sym);
    if acc > max_log {
        return false;
    }
    normalize_counts_into(&freqs[..=max_sym], acc, &mut out.dist);
    let dist = &out.dist;
    for s in 0..=max_sym {
        if freqs[s] > 0 && dist[s] == 0 {
            return false;
        }
    }
    serialize_fse_table_description_into(dist, acc, &mut out.header);
    if !out
        .enc_table
        .build_from_distribution_into(dist, acc, max_sym)
    {
        return false;
    }
    out.mode = TableMode::Compressed;
    true
}

#[allow(clippy::too_many_arguments)]
#[inline(never)]
fn encode_seq_custom(
    packed: &[PackedSeq],
    ll_freq: &[u32; 36],
    ml_freq: &[u32; 53],
    of_freq: &[u32; 32],
    n: usize,
    pred_size: usize,
    output: &mut Vec<u8>,
    writer_buf: &mut Vec<u8>,
    tables: &mut CustomSeqTables,
) -> bool {
    simd_body!(encode_seq_custom_impl(
        packed, ll_freq, ml_freq, of_freq, n, pred_size, output, writer_buf, tables
    ))
}

#[allow(clippy::too_many_arguments)]
#[inline(always)]
fn encode_seq_custom_impl(
    packed: &[PackedSeq],
    ll_freq: &[u32; 36],
    ml_freq: &[u32; 53],
    of_freq: &[u32; 32],
    n: usize,
    pred_size: usize,
    output: &mut Vec<u8>,
    writer_buf: &mut Vec<u8>,
    tables: &mut CustomSeqTables,
) -> bool {
    output.clear();

    let ll_max = ll_freq.iter().rposition(|&f| f > 0).unwrap_or(0);
    let ml_max = ml_freq.iter().rposition(|&f| f > 0).unwrap_or(0);
    let of_max = of_freq.iter().rposition(|&f| f > 0).unwrap_or(0);

    let estimated_bits = estimate_fse_bits(&ll_freq[..=ll_max], n)
        + estimate_fse_bits(&ml_freq[..=ml_max], n)
        + estimate_fse_bits(&of_freq[..=of_max], n);
    let estimated_header = 20;
    let estimated_bytes = estimated_bits.div_ceil(8) + estimated_header + 4;
    if estimated_bytes >= pred_size {
        return false;
    }

    if !build_table_enc(&mut tables.ll, ll_freq, ll_max, 9, n) {
        return false;
    }
    if !build_table_enc(&mut tables.of, of_freq, of_max, 8, n) {
        return false;
    }
    if !build_table_enc(&mut tables.ml, ml_freq, ml_max, 9, n) {
        return false;
    }

    let ll_mode: u8 = match tables.ll.mode {
        TableMode::Compressed => 2,
        TableMode::Rle(_) => 1,
    };
    let of_mode: u8 = match tables.of.mode {
        TableMode::Compressed => 2,
        TableMode::Rle(_) => 1,
    };
    let ml_mode: u8 = match tables.ml.mode {
        TableMode::Compressed => 2,
        TableMode::Rle(_) => 1,
    };

    let num_seq = n as u32;
    output.reserve(n * 4 + 64);

    write_seq_count(output, num_seq);

    output.push((ll_mode << 6) | (of_mode << 4) | (ml_mode << 2));

    match tables.ll.mode {
        TableMode::Rle(sym) => output.push(sym),
        TableMode::Compressed => output.extend_from_slice(&tables.ll.header),
    }
    match tables.of.mode {
        TableMode::Rle(sym) => output.push(sym),
        TableMode::Compressed => output.extend_from_slice(&tables.of.header),
    }
    match tables.ml.mode {
        TableMode::Rle(sym) => output.push(sym),
        TableMode::Compressed => output.extend_from_slice(&tables.ml.header),
    }

    let last = &packed[n - 1];

    let max_out = n * 18 + 16;
    let mut bitstream = primitives::BitstreamScratch::new(writer_buf, max_out);
    let mut pos: usize = 0;
    let mut bits: u64 = 0;
    let mut bits_used: u32 = 0;

    macro_rules! add_bits {
        ($val:expr, $n:expr) => {
            bits |= ($val as u64) << bits_used;
            bits_used += $n as u32;
        };
    }
    macro_rules! flush_fast {
        () => {
            bitstream.flush(pos, bits);
            let nb = (bits_used >> 3) as usize;
            pos += nb;
            bits >>= (nb << 3) as u64;
            bits_used &= 7;
        };
    }
    add_extra_bits_macro!(add_extra_bits, add_bits, flush_fast);

    add_bits!(last.extra_bits, last.extra_nbits);

    match (tables.ll.mode, tables.of.mode, tables.ml.mode) {
        (TableMode::Compressed, TableMode::Compressed, TableMode::Compressed) => {
            let ll_t = &tables.ll.enc_table;
            let of_t = &tables.of.enc_table;
            let ml_t = &tables.ml.enc_table;
            let mut ll_s = ll_t.init_state(last.ll_c);
            let mut of_s = of_t.init_state(last.of_c);
            let mut ml_s = ml_t.init_state(last.ml_c);

            for k in (0..n - 1).rev() {
                let p = &packed[k];

                flush_fast!();
                {
                    let (out, nb, next) = of_t.transition(p.of_c, of_s);
                    add_bits!(out, nb);
                    of_s = next;
                }
                {
                    let (out, nb, next) = ml_t.transition(p.ml_c, ml_s);
                    add_bits!(out, nb);
                    ml_s = next;
                }
                {
                    let (out, nb, next) = ll_t.transition(p.ll_c, ll_s);
                    add_bits!(out, nb);
                    ll_s = next;
                }
                add_extra_bits!(p);
            }

            flush_fast!();
            add_bits!(ml_s - ml_t.table_size, ml_t.table_log);
            add_bits!(of_s - of_t.table_size, of_t.table_log);
            add_bits!(ll_s - ll_t.table_size, ll_t.table_log);
        }
        _ => {
            let ll_table = match tables.ll.mode {
                TableMode::Compressed => Some(&tables.ll.enc_table),
                TableMode::Rle(_) => None,
            };
            let of_table = match tables.of.mode {
                TableMode::Compressed => Some(&tables.of.enc_table),
                TableMode::Rle(_) => None,
            };
            let ml_table = match tables.ml.mode {
                TableMode::Compressed => Some(&tables.ml.enc_table),
                TableMode::Rle(_) => None,
            };

            let mut ll_state = ll_table.as_ref().map(|t| t.init_state(last.ll_c));
            let mut of_state = of_table.as_ref().map(|t| t.init_state(last.of_c));
            let mut ml_state = ml_table.as_ref().map(|t| t.init_state(last.ml_c));

            macro_rules! encode_transition_opt {
                ($table:expr, $state:expr, $symbol:expr) => {
                    if let (Some(t), Some(s)) = (&$table, &mut $state) {
                        let (out, nb, next) = t.transition($symbol, *s);
                        add_bits!(out, nb);
                        *s = next;
                    }
                };
            }

            for k in (0..n - 1).rev() {
                let p = &packed[k];

                flush_fast!();
                encode_transition_opt!(of_table, of_state, p.of_c);
                encode_transition_opt!(ml_table, ml_state, p.ml_c);
                encode_transition_opt!(ll_table, ll_state, p.ll_c);
                add_extra_bits!(p);
            }

            flush_fast!();
            if let (Some(t), Some(s)) = (&ml_table, ml_state) {
                add_bits!(s - t.table_size, t.table_log);
            }
            if let (Some(t), Some(s)) = (&of_table, of_state) {
                add_bits!(s - t.table_size, t.table_log);
            }
            if let (Some(t), Some(s)) = (&ll_table, ll_state) {
                add_bits!(s - t.table_size, t.table_log);
            }
        }
    }

    add_bits!(1u32, 1u8);
    flush_fast!();
    while bits_used > 0 {
        bitstream.write_byte(pos, bits as u8);
        bits >>= 8;
        bits_used = bits_used.saturating_sub(8);
        pos += 1;
    }
    bitstream.finish(pos);
    output.extend_from_slice(bitstream.as_slice());

    true
}

// Predefined FSE bit costs per symbol, in 256ths of a bit.
// cost_256 = 256 * (accuracy_log - log2(max(1, |dist[s]|)))
#[rustfmt::skip]
static LL_PRED_COST_256: [u16; 36] = [
    1024, 1130, 1280, 1280, 1280, 1280, 1280, 1280, 1280, 1280, 1280, 1280, 1280,
    1536, 1536, 1536,
    1280, 1280, 1280, 1280, 1280, 1280, 1280, 1280, 1280,
    1130, 1280,
    1536, 1536, 1536, 1536, 1536,
    1536, 1536, 1536, 1536,
];

#[rustfmt::skip]
static ML_PRED_COST_256: [u16; 53] = [
    1536,
    1024, 1130, 1280, 1280, 1280, 1280, 1280, 1280,
    1536, 1536, 1536, 1536, 1536, 1536, 1536, 1536, 1536, 1536, 1536,
    1536, 1536, 1536, 1536, 1536, 1536, 1536, 1536, 1536, 1536, 1536, 1536,
    1536, 1536, 1536, 1536, 1536, 1536, 1536, 1536, 1536, 1536, 1536, 1536, 1536, 1536,
    1536, 1536, 1536, 1536, 1536, 1536, 1536,
];

#[rustfmt::skip]
static OF_PRED_COST_256: [u16; 32] = [
    1280, 1280, 1280, 1280, 1280, 1280,
    1024, 1024, 1024,
    1280, 1280, 1280, 1280, 1280, 1280, 1280, 1280, 1280, 1280, 1280,
    1280, 1280, 1280, 1280,
    1280, 1280, 1280, 1280, 1280, 1280, 1280, 1280,
];

fn estimate_predefined_cost(
    ll_freq: &[u32; 36],
    ml_freq: &[u32; 53],
    of_freq: &[u32; 32],
    extra_bits: u64,
    n: usize,
) -> usize {
    let mut fse_cost_256: u64 = 0;
    for (c, &f) in ll_freq.iter().enumerate() {
        fse_cost_256 += f as u64 * LL_PRED_COST_256[c] as u64;
    }
    for (c, &f) in ml_freq.iter().enumerate() {
        fse_cost_256 += f as u64 * ML_PRED_COST_256[c] as u64;
    }
    for (c, &f) in of_freq.iter().enumerate() {
        fse_cost_256 += f as u64 * OF_PRED_COST_256[c] as u64;
    }

    let total_bits = fse_cost_256.div_ceil(256) + extra_bits;
    let header_bytes = if n < 128 {
        2
    } else if n < 0x7F00 {
        3
    } else {
        4
    };
    (total_bits as usize + 17 + 8) / 8 + header_bytes
}

fn estimate_fse_bits(freqs: &[u32], total: usize) -> usize {
    if total == 0 {
        return 0;
    }
    let log2_total = (usize::BITS).saturating_sub(total.leading_zeros());
    let mut bits: u64 = 0;
    for &f in freqs {
        if f > 0 {
            let log2_f = (u32::BITS).saturating_sub(f.leading_zeros());
            let cost = log2_total.saturating_sub(log2_f);
            bits += f as u64 * cost as u64;
        }
    }
    bits as usize
}

fn optimal_table_log(max_log: u8, num_seq: usize, max_symbol: usize) -> u8 {
    let min_log = 5u8;
    if num_seq <= 1 {
        return min_log;
    }
    let seq_log = 32 - ((num_seq as u32 - 1).leading_zeros());
    let min_bits_sym = if max_symbol > 0 {
        (32 - (max_symbol as u32).leading_zeros()) as u8 + 2
    } else {
        0
    };
    let target = seq_log.saturating_sub(2) as u8;
    target.max(min_log).max(min_bits_sym).min(max_log)
}

#[rustfmt::skip]
const LL_CODE_TABLE: [u8; 64] = [
     0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
    16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21,
    22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
    24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
];

#[rustfmt::skip]
const ML_CODE_TABLE: [u8; 128] = [
    // mlBase = matchLength - 3, indexed 0..127
     0,  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, 32, 33, 33, 34, 34, 35, 35, 36, 36, 36, 36, 37, 37, 37, 37,
    38, 38, 38, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 39, 39,
    40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
    41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
    42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42,
    42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42,
];

#[inline]
fn of_code(offset_value: u32) -> u8 {
    (31 - offset_value.leading_zeros()) as u8
}

/// Rows `code | extra_bits << 8 | baseline << 16` for each index of a code
/// table. Each code covers a run of indices whose length is a power of two,
/// so the run gives the baseline and the extra-bit count.
const fn code_rows<const N: usize>(codes: &[u8; N]) -> [u32; N] {
    let mut rows = [0u32; N];
    let mut i = 0;
    while i < N {
        let code = codes[i];
        let mut first = i;
        while first > 0 && codes[first - 1] == code {
            first -= 1;
        }
        let mut end = i;
        while end < N && codes[end] == code {
            end += 1;
        }
        let nb = (end - first).trailing_zeros();
        rows[i] = code as u32 | nb << 8 | (first as u32) << 16;
        i += 1;
    }
    rows
}

/// [`code_rows`] of literal lengths below 64.
const LL_ROWS: [u32; 64] = code_rows(&LL_CODE_TABLE);
/// [`code_rows`] of match lengths less 3, below 128.
const ML_ROWS: [u32; 128] = code_rows(&ML_CODE_TABLE);

/// A literal length's code, extra-bit count and extra bits. One row lookup
/// replaces the code, bit-count and baseline tables.
#[inline(always)]
fn ll_split(ll: u32) -> (u8, u32, u32) {
    if ll < 64 {
        let row = LL_ROWS[ll as usize];
        (row as u8, (row >> 8) & 0xFF, ll - (row >> 16))
    } else {
        let high_bit = 31 - ll.leading_zeros();
        (high_bit as u8 + 19, high_bit, ll - (1 << high_bit))
    }
}

/// A match length's code, extra-bit count and extra bits, as [`ll_split`].
#[inline(always)]
fn ml_split(ml: u32) -> (u8, u32, u32) {
    let ml_base = ml - 3;
    if ml_base < 128 {
        let row = ML_ROWS[ml_base as usize];
        (row as u8, (row >> 8) & 0xFF, ml_base - (row >> 16))
    } else {
        let high_bit = 31 - ml_base.leading_zeros();
        (high_bit as u8 + 36, high_bit, ml_base - (1 << high_bit))
    }
}

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

    const KNUTH: u32 = 0x9E37_79B1;
    const POLICY: BlockPolicy = BlockPolicy {
        custom_tables: true,
        max_literal_entropy_fp8: u32::MAX,
    };

    /// Bytes skewed toward low symbols (about 5 bits per byte) with almost no
    /// repeated strings.
    fn skewed_literals(len: usize) -> Vec<u8> {
        (0..len as u32)
            .map(|i| {
                let r = i.wrapping_mul(KNUTH).rotate_left(13).wrapping_mul(KNUTH);
                ((r >> 26) & (r >> 20) & 63) as u8 + b' '
            })
            .collect()
    }

    fn block_header(out: &[u8]) -> (bool, u32, usize) {
        let h = u32::from(out[0]) | (u32::from(out[1]) << 8) | (u32::from(out[2]) << 16);
        (h & 1 == 1, (h >> 1) & 3, (h >> 3) as usize)
    }

    #[test]
    fn block_without_sequences_is_huffman_coded() {
        let src = skewed_literals(64 * 1024);
        let mut out = Vec::new();
        let mut ws = BlockEncodeWorkspace::new();
        let mut rep = [1, 4, 8];
        encode_compressed_block(&src, &[], &mut rep, true, &mut out, &mut ws, POLICY).unwrap();

        let (last, block_type, size) = block_header(&out);
        assert!(last);
        assert_eq!(block_type, 2, "compressed block");
        assert_eq!(size, out.len() - 3);
        assert!(out.len() * 10 < src.len() * 9, "{} bytes", out.len());
        assert_eq!(out[3] & 3, 2, "Huffman literals with a tree");
        assert_eq!(out.last(), Some(&0), "empty sequence section");
        assert_eq!(rep, [1, 4, 8]);
        assert!(ws.prev_huffman.is_some());
    }

    #[test]
    fn block_without_sequences_falls_back_to_raw_for_dense_bytes() {
        // Uniform bytes: Huffman cannot beat raw storage.
        let src: Vec<u8> = (0..4096u32)
            .map(|i| (i.wrapping_mul(KNUTH) >> 24) as u8)
            .collect();
        let mut out = Vec::new();
        let mut ws = BlockEncodeWorkspace::new();
        encode_compressed_block(&src, &[], &mut [1, 4, 8], false, &mut out, &mut ws, POLICY)
            .unwrap();
        let (last, block_type, size) = block_header(&out);
        assert!(!last);
        assert_eq!(block_type, 0, "raw block");
        assert_eq!(size, src.len());
        assert!(ws.prev_huffman.is_none());
    }

    #[test]
    fn fresh_table_replaces_one_that_cannot_code_new_symbols() {
        let mut ws = BlockEncodeWorkspace::new();
        let first = skewed_literals(16 * 1024);
        let mut out = Vec::new();
        encode_compressed_block(
            &first,
            &[],
            &mut [1, 4, 8],
            false,
            &mut out,
            &mut ws,
            POLICY,
        )
        .unwrap();
        assert!(ws.prev_huffman.is_some());

        // Same shape, shifted to byte values the first table has no code for.
        let second: Vec<u8> = first.iter().map(|&b| b + 128).collect();
        let mut out = Vec::new();
        encode_compressed_block(
            &second,
            &[],
            &mut [1, 4, 8],
            true,
            &mut out,
            &mut ws,
            POLICY,
        )
        .unwrap();
        let (_, block_type, _) = block_header(&out);
        assert_eq!(block_type, 2);
        assert_eq!(out[3] & 3, 2, "new tree, not treeless reuse");
    }

    #[test]
    fn previous_table_is_reused_for_the_same_distribution() {
        let mut ws = BlockEncodeWorkspace::new();
        let data = skewed_literals(32 * 1024);
        let mut out = Vec::new();
        encode_compressed_block(
            &data[..16 * 1024],
            &[],
            &mut [1, 4, 8],
            false,
            &mut out,
            &mut ws,
            POLICY,
        )
        .unwrap();
        let mut out = Vec::new();
        encode_compressed_block(
            &data[16 * 1024..],
            &[],
            &mut [1, 4, 8],
            true,
            &mut out,
            &mut ws,
            POLICY,
        )
        .unwrap();
        assert_eq!(out[3] & 3, 3, "treeless literals");
    }

    #[test]
    fn dense_literals_stay_raw_under_an_entropy_limit() {
        // About 7 bits per byte: Huffman saves roughly 12%.
        let src: Vec<u8> = (0..16_384u32)
            .map(|i| (i.wrapping_mul(KNUTH) >> 25) as u8)
            .collect();
        let limited = BlockPolicy {
            custom_tables: true,
            max_literal_entropy_fp8: 6 * 256,
        };
        let mut out = Vec::new();
        let mut ws = BlockEncodeWorkspace::new();
        encode_compressed_block(&src, &[], &mut [1, 4, 8], true, &mut out, &mut ws, limited)
            .unwrap();
        assert_eq!(block_header(&out).1, 0, "raw block under the limit");

        let mut out = Vec::new();
        let mut ws = BlockEncodeWorkspace::new();
        encode_compressed_block(&src, &[], &mut [1, 4, 8], true, &mut out, &mut ws, POLICY)
            .unwrap();
        assert_eq!(block_header(&out).1, 2, "Huffman-coded without a limit");
    }

    #[test]
    fn sequence_codes_follow_the_zstd_tables() {
        use zrip_core::fse::{LL_BASELINE_TABLE, LL_BITS_TABLE, ML_BASELINE_TABLE, ML_BITS_TABLE};
        for ll in 0..(1 << 17) {
            let (code, nb, extra) = ll_split(ll);
            let c = usize::from(code);
            assert_eq!(nb, u32::from(LL_BITS_TABLE[c]), "ll {ll}");
            assert_eq!(extra, ll - LL_BASELINE_TABLE[c], "ll {ll}");
            assert!(extra < 1 << nb, "ll {ll}");
        }
        for ml in 3..(1 << 17) {
            let (code, nb, extra) = ml_split(ml);
            let c = usize::from(code);
            assert_eq!(nb, u32::from(ML_BITS_TABLE[c]), "ml {ml}");
            assert_eq!(extra, ml - ML_BASELINE_TABLE[c], "ml {ml}");
            assert!(extra < 1 << nb, "ml {ml}");
        }
        assert_eq!(ll_split(63).0, 24);
        assert_eq!(ll_split(64).0, 25);
        assert_eq!(ml_split(131).0, 43);
        assert_eq!(of_code(1), 0);
        assert_eq!(of_code(4), 2);
        assert_eq!(of_code(1 << 20), 20);
    }
}