zstd-pure-rs 0.2.0

Pure-Rust port of the Zstandard (zstd) compression library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
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
//! Scaffolding for `ZSTD_MatchState_t` — the big compressor state
//! struct from `lib/compress/zstd_compress_internal.h`. Upstream packs
//! window-buffer bookkeeping, hash tables, chain tables, a per-row
//! cache, dictionary match state, the optimal-parser state, and the
//! active `ZSTD_compressionParameters` into one place.
//!
//! We port a cut-down shape first. Fields arrive as needed — the
//! `zstd_fast` port only touches `hashTable`, `nextToUpdate`,
//! `window.base`, and `cParams.{hashLog, minMatch}`.
//! Later ticks add rows / chains / optimal state / dictionary
//! linkage incrementally.

#![allow(non_snake_case)]

/// Port of the public `ZSTD_compressionParameters` from `zstd.h`.
#[derive(Debug, Clone, Copy, Default)]
pub struct ZSTD_compressionParameters {
    pub windowLog: u32,
    pub chainLog: u32,
    pub hashLog: u32,
    pub searchLog: u32,
    pub minMatch: u32,
    pub targetLength: u32,
    /// Upstream `ZSTD_strategy` enum (1..=9). Stored as u32 here; the
    /// full enum will arrive with the top-level `ZSTD_compress` port.
    pub strategy: u32,
}

/// Port of `ZSTD_window_t`. Upstream stores raw `BYTE*` base pointers
/// alongside u32 indices. The Rust port keeps the indices (they're
/// compared and used as offsets) and moves the byte buffer one level
/// up — the match state borrows `&[u8]` at call time rather than
/// stashing a pointer.
#[derive(Debug, Clone, Copy, Default)]
pub struct ZSTD_window_t {
    /// Index one-past the last processed byte. Upstream computes this
    /// as `nextSrc - base`; the Rust port stores that index directly.
    pub nextSrc: u32,
    /// Index assigned to `src[0]` for the current contiguous prefix.
    /// Match finders convert between a source-slice position and an
    /// upstream index with `base_offset + pos`.
    pub base_offset: u32,
    /// Index assigned to `dictContent[0]` for the external-dictionary
    /// segment. Indexes below `dictLimit` look in this region.
    pub dictBase_offset: u32,
    /// Below this index, the caller must consult the ext-dict.
    pub dictLimit: u32,
    /// Below this, no valid data exists.
    pub lowLimit: u32,
    /// Diagnostic counter.
    pub nbOverflowCorrections: u32,
}

pub const ZSTD_WINDOW_START_INDEX: u32 = 2;

/// Port of `ZSTD_dictMode_e`. Tells block compressors how to treat
/// the match state's dictionary linkage:
///   - `ZSTD_noDict`: no dictionary in play.
///   - `ZSTD_extDict`: ext-dict bytes sit below `window.lowLimit`.
///   - `ZSTD_dictMatchState`: a CDict's match state is attached via
///     `ms.dictMatchState` — search both the current window and the
///     dict's precomputed tables.
///   - `ZSTD_dedicatedDictSearch`: DDSS variant of dictMatchState —
///     dict tables use bucketed hash layout for wider probing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ZSTD_dictMode_e {
    #[default]
    ZSTD_noDict = 0,
    ZSTD_extDict = 1,
    ZSTD_dictMatchState = 2,
    ZSTD_dedicatedDictSearch = 3,
}

/// Port of `ZSTD_matchState_dictMode`. Inspects the match state and
/// returns the mode the block compressor should use.
///
pub fn ZSTD_matchState_dictMode(ms: &ZSTD_MatchState_t) -> ZSTD_dictMode_e {
    if ZSTD_window_hasExtDict(&ms.window) {
        return ZSTD_dictMode_e::ZSTD_extDict;
    }
    if let Some(dict_ms) = ms.dictMatchState.as_ref() {
        if dict_ms.dedicatedDictSearch != 0 {
            return ZSTD_dictMode_e::ZSTD_dedicatedDictSearch;
        }
        return ZSTD_dictMode_e::ZSTD_dictMatchState;
    }
    ZSTD_dictMode_e::ZSTD_noDict
}

/// Upstream `ZSTD_CURRENT_MAX` (zstd_compress_internal.h:1031). Upper
/// limit on `nextSrc` before we must fold the index space back to
/// zero via overflow correction. 64-bit target: `3500 * (1 << 20)`
/// bytes (~3.67 GB) — leaves 512 MB margin below 4 GB for the
/// maximum job size. 32-bit target: `2000 * (1 << 20)` (~2 GB) to
/// avoid crossing the signed-index midpoint. Previously our port used
/// `(3 << 29) + 1` (~1.6 GB) — wrong by ~2 GB; never visibly broke
/// anything because overflow correction rarely triggers in v0.1's
/// roundtrips, but would cut history window capacity by ~half.
pub const ZSTD_CURRENT_MAX: u32 = if crate::common::mem::MEM_32bits() != 0 {
    2000u32 * (1u32 << 20)
} else {
    3500u32 * (1u32 << 20)
};

/// Upstream `ZSTD_CHUNKSIZE_MAX` (zstd_compress_internal.h:1033).
/// Maximum chunk size before overflow correction needs to be called
/// again: `u32::MAX - ZSTD_CURRENT_MAX`.
pub const ZSTD_CHUNKSIZE_MAX: u32 = u32::MAX - ZSTD_CURRENT_MAX;

/// Port of `ZSTD_dictTooBig` (zstd_compress.c:2113). A loaded dict
/// bigger than one chunk-max can't be represented without triggering
/// overflow correction mid-load — upstream uses this gate to decide
/// whether to attach vs copy the dict tables.
#[inline]
pub const fn ZSTD_dictTooBig(loadedDictSize: usize) -> bool {
    loadedDictSize > ZSTD_CHUNKSIZE_MAX as usize
}

/// Port of `ZSTD_INDEXOVERFLOW_MARGIN` (zstd_compress.c:2102).
/// 16 MB safety margin below `ZSTD_CURRENT_MAX` — the threshold
/// below which we can ignore overflow-correction for small inputs.
pub const ZSTD_INDEXOVERFLOW_MARGIN: u32 = 16 * (1 << 20);

/// Port of `ZSTD_indexTooCloseToMax` (zstd_compress.c:2103). Returns
/// true when the window's `nextSrc` index is within
/// `ZSTD_INDEXOVERFLOW_MARGIN` of `ZSTD_CURRENT_MAX` — upstream uses
/// this gate to decide whether small-input compressions can skip the
/// normally-mandatory overflow check. In our port the window stores
/// indices directly (no base pointer), so we compute
/// `nextSrc - base` as the absolute index.
#[inline]
pub fn ZSTD_indexTooCloseToMax(w: &ZSTD_window_t) -> bool {
    // `nextSrc - base` in the pointer world maps to `nextSrc` itself
    // in the index world (both are offsets relative to base).
    w.nextSrc as u64 > (ZSTD_CURRENT_MAX - ZSTD_INDEXOVERFLOW_MARGIN) as u64
}

/// Upstream `ZSTD_DUBT_UNSORTED_MARK`. For `btlazy2`, an index of 1
/// means "still in unsorted queue" — the reducer must preserve it
/// across overflow correction so sorting picks back up correctly.
pub const ZSTD_DUBT_UNSORTED_MARK: u32 = 1;

/// Upstream `ZSTD_ROWSIZE`. Hash-table reducer walks in
/// `ZSTD_ROWSIZE`-wide strides for auto-vectorization; table sizes
/// must be a multiple.
pub const ZSTD_ROWSIZE: usize = 16;
pub const ZSTD_ROW_HASH_CACHE_SIZE: usize = 8;

/// Port of `ZSTD_reduceTable_internal`. Shifts every hash-table entry
/// down by `reducerValue` (floor 0), optionally preserving the
/// `ZSTD_DUBT_UNSORTED_MARK` sentinel intact.
///
/// Table length must be a multiple of `ZSTD_ROWSIZE` (upstream
/// enforces via `assert`).
pub fn ZSTD_reduceTable_internal(table: &mut [u32], reducerValue: u32, preserveMark: bool) {
    let size = table.len();
    debug_assert_eq!(size & (ZSTD_ROWSIZE - 1), 0);
    debug_assert!(size < (1usize << 31));

    // Protect index values below ZSTD_WINDOW_START_INDEX from wrapping.
    let reducerThreshold = reducerValue.wrapping_add(ZSTD_WINDOW_START_INDEX);

    for cell in table.iter_mut() {
        *cell = if preserveMark && *cell == ZSTD_DUBT_UNSORTED_MARK {
            ZSTD_DUBT_UNSORTED_MARK
        } else if *cell < reducerThreshold {
            0
        } else {
            cell.wrapping_sub(reducerValue)
        };
    }
}

/// Port of `ZSTD_reduceTable`. Non-preserving variant — used by fast
/// / dfast / lazy strategies.
#[inline]
pub fn ZSTD_reduceTable(table: &mut [u32], reducerValue: u32) {
    ZSTD_reduceTable_internal(table, reducerValue, false);
}

/// Port of `ZSTD_reduceTable_btlazy2`. Preserves the unsorted-mark
/// sentinel (index 1) across the reduce — required so the btlazy2
/// sorter can still identify queued-but-unsorted nodes.
#[inline]
pub fn ZSTD_reduceTable_btlazy2(table: &mut [u32], reducerValue: u32) {
    ZSTD_reduceTable_internal(table, reducerValue, true);
}

/// Port of `ZSTD_rowMatchFinderSupported`. Only `greedy`/`lazy`/`lazy2`
/// can opt into the row-based matchfinder.
#[inline]
pub fn ZSTD_rowMatchFinderSupported(strategy: u32) -> bool {
    // ZSTD_greedy = 3, ZSTD_lazy2 = 5 in upstream enum.
    (3..=5).contains(&strategy)
}

/// Port of `ZSTD_resolveRowMatchFinderMode`. Converts an auto/enable/
/// disable setting plus cParams into a concrete enable/disable
/// decision. Upstream's normal build uses the 14-bit windowLog floor;
/// the 17-bit floor is specific to the Linux-kernel port.
pub fn ZSTD_resolveRowMatchFinderMode(
    mode: crate::compress::zstd_ldm::ZSTD_ParamSwitch_e,
    cParams: &ZSTD_compressionParameters,
) -> crate::compress::zstd_ldm::ZSTD_ParamSwitch_e {
    use crate::compress::zstd_ldm::ZSTD_ParamSwitch_e;
    const K_WINDOW_LOG_LOWER_BOUND: u32 = 14;
    if mode != ZSTD_ParamSwitch_e::ZSTD_ps_auto {
        return mode;
    }
    if !ZSTD_rowMatchFinderSupported(cParams.strategy) {
        return ZSTD_ParamSwitch_e::ZSTD_ps_disable;
    }
    if cParams.windowLog > K_WINDOW_LOG_LOWER_BOUND {
        ZSTD_ParamSwitch_e::ZSTD_ps_enable
    } else {
        ZSTD_ParamSwitch_e::ZSTD_ps_disable
    }
}

/// Port of `ZSTD_resolveBlockSplitterMode`. Block splitter is auto-
/// enabled for `btopt` and up with windowLog ≥ 17.
pub fn ZSTD_resolveBlockSplitterMode(
    mode: crate::compress::zstd_ldm::ZSTD_ParamSwitch_e,
    cParams: &ZSTD_compressionParameters,
) -> crate::compress::zstd_ldm::ZSTD_ParamSwitch_e {
    use crate::compress::zstd_ldm::ZSTD_ParamSwitch_e;
    if mode != ZSTD_ParamSwitch_e::ZSTD_ps_auto {
        return mode;
    }
    // ZSTD_btopt = 7.
    if cParams.strategy >= 7 && cParams.windowLog >= 17 {
        ZSTD_ParamSwitch_e::ZSTD_ps_enable
    } else {
        ZSTD_ParamSwitch_e::ZSTD_ps_disable
    }
}

/// Port of `ZSTD_resolveEnableLdm`. Long-distance matcher auto-enables
/// for `btopt` and up with windowLog ≥ 27.
pub fn ZSTD_resolveEnableLdm(
    mode: crate::compress::zstd_ldm::ZSTD_ParamSwitch_e,
    cParams: &ZSTD_compressionParameters,
) -> crate::compress::zstd_ldm::ZSTD_ParamSwitch_e {
    use crate::compress::zstd_ldm::ZSTD_ParamSwitch_e;
    if mode != ZSTD_ParamSwitch_e::ZSTD_ps_auto {
        return mode;
    }
    if cParams.strategy >= 7 && cParams.windowLog >= 27 {
        ZSTD_ParamSwitch_e::ZSTD_ps_enable
    } else {
        ZSTD_ParamSwitch_e::ZSTD_ps_disable
    }
}

/// Port of `ZSTD_resolveMaxBlockSize`. Returns `ZSTD_BLOCKSIZE_MAX` on
/// a zero default, caller's value otherwise.
#[inline]
pub fn ZSTD_resolveMaxBlockSize(maxBlockSize: usize) -> usize {
    use crate::decompress::zstd_decompress_block::ZSTD_BLOCKSIZE_MAX;
    if maxBlockSize == 0 {
        ZSTD_BLOCKSIZE_MAX
    } else {
        maxBlockSize
    }
}

/// Port of `ZSTD_resolveExternalSequenceValidation`. Identity — the
/// user-supplied validation flag is passed through unchanged.
#[inline]
pub fn ZSTD_resolveExternalSequenceValidation(mode: i32) -> i32 {
    mode
}

/// Port of `ZSTD_resolveExternalRepcodeSearch`. On `auto`, enables
/// external repcode search for high compression levels (≥ 10).
pub fn ZSTD_resolveExternalRepcodeSearch(
    value: crate::compress::zstd_ldm::ZSTD_ParamSwitch_e,
    cLevel: i32,
) -> crate::compress::zstd_ldm::ZSTD_ParamSwitch_e {
    use crate::compress::zstd_ldm::ZSTD_ParamSwitch_e;
    if value != ZSTD_ParamSwitch_e::ZSTD_ps_auto {
        return value;
    }
    if cLevel < 10 {
        ZSTD_ParamSwitch_e::ZSTD_ps_disable
    } else {
        ZSTD_ParamSwitch_e::ZSTD_ps_enable
    }
}

/// Port of `ZSTD_CDictIndicesAreTagged`. True for fast/dfast strategies
/// — CDict hashtables carry short-cache tags only for those.
#[inline]
pub fn ZSTD_CDictIndicesAreTagged(cParams: &ZSTD_compressionParameters) -> bool {
    // ZSTD_fast = 1, ZSTD_dfast = 2.
    cParams.strategy == 1 || cParams.strategy == 2
}

/// Port of `ZSTD_rowMatchFinderUsed`. True when the row matchfinder
/// is both supported and explicitly enabled — `mode` must be a
/// resolved enable/disable, never auto.
#[inline]
pub fn ZSTD_rowMatchFinderUsed(
    strategy: u32,
    mode: crate::compress::zstd_ldm::ZSTD_ParamSwitch_e,
) -> bool {
    use crate::compress::zstd_ldm::ZSTD_ParamSwitch_e;
    debug_assert!(mode != ZSTD_ParamSwitch_e::ZSTD_ps_auto);
    ZSTD_rowMatchFinderSupported(strategy) && mode == ZSTD_ParamSwitch_e::ZSTD_ps_enable
}

/// Port of `ZSTD_allocateChainTable`. Gatekeeper for which strategies
/// actually need a `chainTable`: DDS-dict mode always allocates;
/// `fast` never allocates; the row-based matchfinder replaces the
/// chain entirely, so row-enabled strategies don't need one either.
#[inline]
pub fn ZSTD_allocateChainTable(
    strategy: u32,
    useRowMatchFinder: crate::compress::zstd_ldm::ZSTD_ParamSwitch_e,
    forDDSDict: u32,
) -> bool {
    // ZSTD_fast = 1.
    forDDSDict != 0 || (strategy != 1 && !ZSTD_rowMatchFinderUsed(strategy, useRowMatchFinder))
}

/// Port of `ZSTD_bitmix`. XXH3-style 64-bit bit mixer — used by
/// `ZSTD_advanceHashSalt` to blend the row-hash salt with the caller-
/// supplied entropy on each reset.
#[inline]
pub fn ZSTD_bitmix(mut val: u64, len: u64) -> u64 {
    use crate::common::bits::ZSTD_rotateRight_U64;
    val ^= ZSTD_rotateRight_U64(val, 49) ^ ZSTD_rotateRight_U64(val, 24);
    val = val.wrapping_mul(0x9FB21C651E98DF25u64);
    val ^= (val >> 35) + len;
    val = val.wrapping_mul(0x9FB21C651E98DF25u64);
    val ^ (val >> 28)
}

/// Port of `ZSTD_advanceHashSalt`. Reseeds `ms.hashSalt` by mixing in
/// `ms.hashSaltEntropy` — run on each CCtx reset so reused row-hash
/// tables don't collide across compressions.
#[inline]
pub fn ZSTD_advanceHashSalt(ms: &mut ZSTD_MatchState_t) {
    ms.hashSalt = ZSTD_bitmix(ms.hashSalt, 8) ^ ZSTD_bitmix(ms.hashSaltEntropy as u64, 4);
}

/// Port of `ZSTD_invalidateMatchState`. Clears window state, rewinds
/// `nextToUpdate` to the dictLimit, and invalidates any loaded dict
/// end. Upstream also resets `opt.litLengthSum`; this port now mirrors
/// that and clears the attached `dictMatchState` as well.
pub fn ZSTD_invalidateMatchState(ms: &mut ZSTD_MatchState_t) {
    ZSTD_window_clear(&mut ms.window);
    ms.nextToUpdate = ms.window.dictLimit;
    ms.dictMatchState = None;
    ms.loadedDictEnd = 0;
    ms.opt.litLengthSum = 0;
}

/// Port of `ZSTD_reduceIndex`. Walks the match-state's owned hash /
/// chain / 3-byte-hash tables and applies `ZSTD_reduceTable` to each
/// after an overflow correction so every stored index is rebased.
///
/// The btlazy2 chain table is special-cased to preserve the
/// `ZSTD_DUBT_UNSORTED_MARK` sentinel.
///
/// Upstream takes `ZSTD_CCtx_params*` to look up `useRowMatchFinder`;
/// `dedicatedDictSearch` lives on the match state itself.
pub fn ZSTD_reduceIndex(
    ms: &mut ZSTD_MatchState_t,
    useRowMatchFinder: crate::compress::zstd_ldm::ZSTD_ParamSwitch_e,
    reducerValue: u32,
) {
    let hSize = 1usize << ms.cParams.hashLog;
    ZSTD_reduceTable(&mut ms.hashTable[..hSize], reducerValue);

    if ZSTD_allocateChainTable(
        ms.cParams.strategy,
        useRowMatchFinder,
        ms.dedicatedDictSearch,
    ) && !ms.chainTable.is_empty()
    {
        let chainSize = 1usize << ms.cParams.chainLog;
        // ZSTD_btlazy2 = 6.
        if ms.cParams.strategy == 6 {
            ZSTD_reduceTable_btlazy2(&mut ms.chainTable[..chainSize], reducerValue);
        } else {
            ZSTD_reduceTable(&mut ms.chainTable[..chainSize], reducerValue);
        }
    }

    if ms.hashLog3 > 0 && !ms.hashTable3.is_empty() {
        let h3Size = 1usize << ms.hashLog3;
        ZSTD_reduceTable(&mut ms.hashTable3[..h3Size], reducerValue);
    }
}

/// Upstream `ZSTD_SHORT_CACHE_TAG_BITS`. Width of the tag packed into
/// the low bits of `hashTable` entries when dictionary matchers use
/// the short-cache optimization.
pub const ZSTD_SHORT_CACHE_TAG_BITS: u32 = 8;

/// Upstream `ZSTD_SHORT_CACHE_TAG_MASK`. Isolates the low-tag bits.
pub const ZSTD_SHORT_CACHE_TAG_MASK: u32 = (1u32 << ZSTD_SHORT_CACHE_TAG_BITS) - 1;

/// Port of `ZSTD_index_overlap_check`. Returns true (upstream returns 1)
/// when `repIndex` does NOT overlap the prefix-boundary guard band
/// immediately below `prefixLowestIndex`.
///
/// Upstream relies on intentional unsigned underflow — we replicate via
/// `wrapping_sub` in the same u32 arithmetic space.
#[inline]
pub fn ZSTD_index_overlap_check(prefixLowestIndex: u32, repIndex: u32) -> bool {
    prefixLowestIndex.wrapping_sub(1).wrapping_sub(repIndex) >= 3
}

/// Port of `ZSTD_writeTaggedIndex`. Unpacks `hashAndTag` into
/// `(hash, tag)`, then packs `(index, tag)` back into the hash table.
/// Used by the short-cache matchfinder in CDict table fills.
#[inline]
pub fn ZSTD_writeTaggedIndex(hashTable: &mut [u32], hashAndTag: usize, index: u32) {
    let hash = hashAndTag >> ZSTD_SHORT_CACHE_TAG_BITS;
    let tag = (hashAndTag as u32) & ZSTD_SHORT_CACHE_TAG_MASK;
    debug_assert!(
        index >> (32 - ZSTD_SHORT_CACHE_TAG_BITS) == 0,
        "index must fit below the tag bits",
    );
    hashTable[hash] = (index << ZSTD_SHORT_CACHE_TAG_BITS) | tag;
}

/// Port of `ZSTD_comparePackedTags`. Returns true when the low tag
/// bits of both packed values match — lets the short-cache matchfinder
/// skip the expensive memory fetch on a tag mismatch.
#[inline]
pub fn ZSTD_comparePackedTags(packedTag1: usize, packedTag2: usize) -> bool {
    let t1 = (packedTag1 as u32) & ZSTD_SHORT_CACHE_TAG_MASK;
    let t2 = (packedTag2 as u32) & ZSTD_SHORT_CACHE_TAG_MASK;
    t1 == t2
}

/// Port of `ZSTD_window_clear`. Collapses `dictLimit` / `lowLimit`
/// down to the current end-of-window — effectively wiping any
/// ext-dict / history knowledge while keeping the base index intact.
pub fn ZSTD_window_clear(window: &mut ZSTD_window_t) {
    let end = window.nextSrc;
    window.lowLimit = end;
    window.dictLimit = end;
}

/// Port of `ZSTD_window_update`. Appends a new segment onto the
/// logical window, rotating the previous prefix into ext-dict mode
/// when the segment is non-contiguous.
///
/// In the pointer-based C code `src` is a raw pointer; in this index-
/// based Rust port the caller supplies the new segment's index in the
/// same coordinate space as `window.nextSrc`. On the non-contiguous
/// branch, upstream rebases the new segment so its first byte keeps
/// the old current index; `src_abs` is only used for the contiguous
/// fast path and for detecting that the branch is needed.
///
/// Returns `true` when the segment is contiguous, `false` when the
/// window had to pivot into ext-dict mode.
pub fn ZSTD_window_update(
    window: &mut ZSTD_window_t,
    src_abs: u32,
    srcSize: usize,
    forceNonContiguous: bool,
) -> bool {
    let mut contiguous = true;
    if srcSize == 0 {
        return contiguous;
    }

    let mut segmentStartIndex = src_abs;
    if src_abs != window.nextSrc || forceNonContiguous {
        let distanceFromBase = window.nextSrc;
        window.lowLimit = window.dictLimit;
        window.dictLimit = distanceFromBase;
        window.dictBase_offset = window.base_offset;
        window.base_offset = distanceFromBase;
        segmentStartIndex = distanceFromBase;
        if window.dictLimit.wrapping_sub(window.lowLimit)
            < crate::compress::zstd_fast::HASH_READ_SIZE as u32
        {
            window.lowLimit = window.dictLimit;
        }
        contiguous = false;
    }

    let src_end_for_overlap = src_abs.wrapping_add(srcSize as u32);
    let src_end_abs = segmentStartIndex.wrapping_add(srcSize as u32);
    window.nextSrc = src_end_abs;

    if src_end_for_overlap > window.lowLimit && src_abs < window.dictLimit {
        window.lowLimit = src_end_for_overlap.min(window.dictLimit);
    }

    contiguous
}

/// Port of `ZSTD_window_isEmpty`. True on a freshly initialized
/// window — all three bookkeeping values still sit at their starting
/// sentinel.
///
/// In our Rust encoding `nextSrc` already stores upstream's
/// `nextSrc - base`, so the `nextSrc - base == ZSTD_WINDOW_START_INDEX`
/// check from upstream collapses to a direct comparison here.
#[inline]
pub fn ZSTD_window_isEmpty(window: &ZSTD_window_t) -> bool {
    window.dictLimit == ZSTD_WINDOW_START_INDEX
        && window.lowLimit == ZSTD_WINDOW_START_INDEX
        && window.nextSrc == ZSTD_WINDOW_START_INDEX
}

/// Port of `ZSTD_window_hasExtDict`. Non-zero when the window has a
/// non-empty ext-dict region (an earlier prefix that moved out of
/// direct reach).
#[inline]
pub fn ZSTD_window_hasExtDict(window: &ZSTD_window_t) -> bool {
    window.lowLimit < window.dictLimit
}

/// Port of `ZSTD_window_canOverflowCorrect`. Returns true when the
/// index space has grown large enough that overflow correction can
/// run without hurting compression ratio (dictionary already shifted
/// out of reach) AND we've pushed past the adjusted minimum threshold.
///
/// `src_abs` is the absolute-index value of the current cursor — in
/// upstream pointer arithmetic `(src - window.base)`, translated here
/// to an explicit u32 (since our Rust `window` stores only indices,
/// not pointers).
pub fn ZSTD_window_canOverflowCorrect(
    window: &ZSTD_window_t,
    cycleLog: u32,
    maxDist: u32,
    loadedDictEnd: u32,
    src_abs: u32,
) -> bool {
    let cycleSize = 1u32 << cycleLog;
    let curr = src_abs;
    let minIndexToOverflowCorrect = cycleSize
        .wrapping_add(maxDist.max(cycleSize))
        .wrapping_add(ZSTD_WINDOW_START_INDEX);

    // Wraparound is intentional: upstream multiplies in U32 and clamps
    // the wrapped result back up to the minimum threshold.
    let adjustment = window.nbOverflowCorrections + 1;
    let adjustedIndex = minIndexToOverflowCorrect
        .wrapping_mul(adjustment)
        .max(minIndexToOverflowCorrect);
    let indexLargeEnough = curr > adjustedIndex;

    // Only worth correcting early if the dictionary is already
    // invalidated, so we don't lose useful history.
    let dictionaryInvalidated = curr > maxDist.wrapping_add(loadedDictEnd);

    indexLargeEnough && dictionaryInvalidated
}

/// Port of `ZSTD_window_correctOverflow`. Reduces every bookkeeping
/// index by a single correction value so indices stay in range for
/// power-of-two hash tables without corrupting the `cycleLog`
/// alignment that chains / binary trees rely on.
///
/// `src_abs` is the current cursor's absolute index (upstream's
/// `src - window.base`). The returned correction value must be
/// subtracted from every hash-table / chain-table entry by the caller.
///
/// Preserves the invariant `(newCurrent & cycleMask) == (curr & cycleMask)`
/// so already-rooted tree nodes still address the same cycle slot.
pub fn ZSTD_window_correctOverflow(
    window: &mut ZSTD_window_t,
    cycleLog: u32,
    maxDist: u32,
    src_abs: u32,
) -> u32 {
    let cycleSize = 1u32 << cycleLog;
    let cycleMask = cycleSize - 1;
    let curr = src_abs;
    let currentCycle = curr & cycleMask;
    // Keep `newCurrent - maxDist >= ZSTD_WINDOW_START_INDEX` even
    // when currentCycle is tiny.
    let currentCycleCorrection = if currentCycle < ZSTD_WINDOW_START_INDEX {
        cycleSize.max(ZSTD_WINDOW_START_INDEX)
    } else {
        0
    };
    let newCurrent = currentCycle + currentCycleCorrection + maxDist.max(cycleSize);
    let correction = curr - newCurrent;

    debug_assert!(maxDist & (maxDist - 1) == 0, "maxDist must be power of two");
    debug_assert_eq!(curr & cycleMask, newCurrent & cycleMask);
    debug_assert!(curr > newCurrent);

    // Upstream advances `base` / `dictBase` pointers, so every
    // `ptr - base` index decreases by `correction`. In the Rust
    // encoding `base_offset + buffer_pos` is that index, so rebase the
    // offsets downward in the same index space.
    window.base_offset = window.base_offset.wrapping_sub(correction);
    window.dictBase_offset = window.dictBase_offset.wrapping_sub(correction);
    window.nextSrc = window.nextSrc.wrapping_sub(correction);
    let correctionThreshold = correction.wrapping_add(ZSTD_WINDOW_START_INDEX);
    window.lowLimit = if window.lowLimit < correctionThreshold {
        ZSTD_WINDOW_START_INDEX
    } else {
        window.lowLimit.wrapping_sub(correction)
    };
    window.dictLimit = if window.dictLimit < correctionThreshold {
        ZSTD_WINDOW_START_INDEX
    } else {
        window.dictLimit.wrapping_sub(correction)
    };

    debug_assert!(newCurrent >= maxDist);
    debug_assert!(newCurrent - maxDist >= ZSTD_WINDOW_START_INDEX);
    debug_assert!(window.lowLimit <= newCurrent);
    debug_assert!(window.dictLimit <= newCurrent);

    window.nbOverflowCorrections += 1;
    correction
}

/// Port of `ZSTD_window_init`. Sets up the starting-sentinel values
/// so a fresh window compares equal to every other fresh window and
/// so index 0/1 aren't used (they collide with DUBT sentinels).
pub fn ZSTD_window_init(window: &mut ZSTD_window_t) {
    *window = ZSTD_window_t::default();
    window.base_offset = ZSTD_WINDOW_START_INDEX;
    window.dictBase_offset = ZSTD_WINDOW_START_INDEX;
    window.dictLimit = ZSTD_WINDOW_START_INDEX;
    window.lowLimit = ZSTD_WINDOW_START_INDEX;
    window.nextSrc = ZSTD_WINDOW_START_INDEX;
}

/// Port of `ZSTD_window_enforceMaxDist`. Advances `window.lowLimit`
/// so every valid index stays within `maxDist` bytes of `blockEnd_abs`,
/// invalidating any loaded dictionary when input has moved past it.
///
/// `blockEnd_abs` is the absolute-index value of the end of the
/// current block (upstream's `blockEnd - window.base`).
///
/// `loadedDictEnd` is in/out: reset to 0 when the dictionary is
/// invalidated. Pass `&mut 0` when no dictionary is in use. Returns
/// true when dictionary state was invalidated, so callers that carry
/// a `dictMatchState` pointer can clear it in lockstep.
///
pub fn ZSTD_window_enforceMaxDist(
    window: &mut ZSTD_window_t,
    blockEnd_abs: u32,
    maxDist: u32,
    loadedDictEnd: &mut u32,
) -> bool {
    let blockEndIdx = blockEnd_abs;
    let loadedEnd = *loadedDictEnd;

    if blockEndIdx > maxDist.wrapping_add(loadedEnd) {
        let newLowLimit = blockEndIdx.wrapping_sub(maxDist);
        if window.lowLimit < newLowLimit {
            window.lowLimit = newLowLimit;
        }
        if window.dictLimit < window.lowLimit {
            window.dictLimit = window.lowLimit;
        }
        *loadedDictEnd = 0;
        return true;
    }
    false
}

/// Match-state wrapper for `ZSTD_window_enforceMaxDist` which mirrors
/// upstream's `dictMatchState**` invalidation.
pub fn ZSTD_matchState_enforceMaxDist(
    ms: &mut ZSTD_MatchState_t,
    blockEnd_abs: u32,
    maxDist: u32,
) -> bool {
    let invalidated =
        ZSTD_window_enforceMaxDist(&mut ms.window, blockEnd_abs, maxDist, &mut ms.loadedDictEnd);
    if invalidated {
        ms.dictMatchState = None;
    }
    invalidated
}

/// Port of `ZSTD_checkDictValidity`. Invalidates `loadedDictEnd` once
/// the current block has moved beyond the window — either past
/// `loadedDictEnd + maxDist`, or after a non-contiguous jump flagged
/// by `loadedDictEnd != window.dictLimit`.
///
/// Returns true when dictionary state was invalidated, so callers that
/// carry a `dictMatchState` pointer can clear it in lockstep.
pub fn ZSTD_checkDictValidity(
    window: &ZSTD_window_t,
    blockEnd_abs: u32,
    maxDist: u32,
    loadedDictEnd: &mut u32,
) -> bool {
    let loadedEnd = *loadedDictEnd;
    // Prefix dictionaries can sit before the current tiny block in the
    // Rust absolute-index model, so `loadedDictEnd` may be greater than
    // `blockEnd_abs`. Release behavior already preserves the dictionary
    // in that case; don't make debug builds stricter than runtime.
    if blockEnd_abs > loadedEnd.wrapping_add(maxDist) || loadedEnd != window.dictLimit {
        *loadedDictEnd = 0;
        return true;
    }
    false
}

/// Match-state wrapper for `ZSTD_checkDictValidity` which mirrors
/// upstream's `dictMatchState**` invalidation.
pub fn ZSTD_matchState_checkDictValidity(
    ms: &mut ZSTD_MatchState_t,
    blockEnd_abs: u32,
    maxDist: u32,
) -> bool {
    let invalidated =
        ZSTD_checkDictValidity(&ms.window, blockEnd_abs, maxDist, &mut ms.loadedDictEnd);
    if invalidated {
        ms.dictMatchState = None;
    }
    invalidated
}

/// Port of `ZSTD_window_needOverflowCorrection`. Returns true when
/// indices have grown large enough that we must correct now — either
/// we've crossed `ZSTD_CURRENT_MAX`, or we're in "correct-frequently"
/// diagnostic mode (not exposed here) and canOverflowCorrect agrees.
///
/// `srcEnd_abs` is the absolute-index value of the end of the current
/// chunk (upstream `srcEnd - window.base`).
pub fn ZSTD_window_needOverflowCorrection(
    _window: &ZSTD_window_t,
    _cycleLog: u32,
    _maxDist: u32,
    _loadedDictEnd: u32,
    _src_abs: u32,
    srcEnd_abs: u32,
) -> bool {
    // We don't compile in `ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY`
    // (fuzz-only diagnostic), so the canOverflowCorrect early-return
    // is inert — collapse to the ZSTD_CURRENT_MAX check.
    srcEnd_abs > ZSTD_CURRENT_MAX
}

/// Port of `ZSTD_overflowCorrectIfNeeded` (`zstd_compress.c:4550`).
/// Checks whether the window has accumulated enough absolute-index
/// distance to risk a u32 wrap (`> ZSTD_CURRENT_MAX`); if so, runs
/// `ZSTD_window_correctOverflow` to shift indices down and applies
/// the same correction to every hash/chain table entry via
/// `ZSTD_reduceIndex`. Also forces `nextToUpdate` and `loadedDictEnd`
/// to match the new index space.
///
/// Upstream takes `ZSTD_cwksp*` to mark tables dirty/clean around the
/// reduce; our Rust port owns tables as `Vec` and doesn't need that
/// transactional marking — the reduce is in-place.
///
/// `src_abs` is the current cursor's absolute index; `srcEnd_abs` is
/// the end of the current chunk (upstream's `iend - window.base`).
pub fn ZSTD_overflowCorrectIfNeeded(
    ms: &mut ZSTD_MatchState_t,
    useRowMatchFinder: crate::compress::zstd_ldm::ZSTD_ParamSwitch_e,
    _dedicatedDictSearch: u32,
    windowLog: u32,
    chainLog: u32,
    strategy: u32,
    src_abs: u32,
    srcEnd_abs: u32,
) {
    let cycleLog = crate::compress::zstd_compress::ZSTD_cycleLog(chainLog, strategy);
    let maxDist: u32 = 1u32 << windowLog;
    if ZSTD_window_needOverflowCorrection(
        &ms.window,
        cycleLog,
        maxDist,
        ms.loadedDictEnd,
        src_abs,
        srcEnd_abs,
    ) {
        let correction = ZSTD_window_correctOverflow(&mut ms.window, cycleLog, maxDist, src_abs);
        ZSTD_reduceIndex(ms, useRowMatchFinder, correction);
        if ms.nextToUpdate < correction {
            ms.nextToUpdate = 0;
        } else {
            ms.nextToUpdate -= correction;
        }
        // Invalidate loaded dict on overflow correction.
        ms.loadedDictEnd = 0;
        ms.dictMatchState = None;
    }
}

/// Cut-down `ZSTD_MatchState_t`. Covers the primary hash table, the
/// `hashTable3` short-hash leg, and the `chainTable` used by
/// `zstd_lazy` / `zstd_opt`. Row-hash scratch fields are live for the
/// greedy/lazy/lazy2 matchfinders, which matches this upstream
/// snapshot's strategy coverage.
#[derive(Debug, Clone)]
pub struct ZSTD_MatchState_t {
    pub window: ZSTD_window_t,

    /// Optional entropy-table seed for first-block optimal-parser
    /// pricing. Callers stash the prior block or dictionary entropy
    /// here before invoking `zstd_opt`.
    pub entropySeed: Option<crate::compress::zstd_compress::ZSTD_entropyCTables_t>,

    /// Upstream `ldmSeqStore`. When set, the optimal parser considers
    /// long-distance matcher sequences as candidate matches.
    pub ldmSeqStore: Option<crate::compress::zstd_ldm::RawSeqStore_t>,

    /// Upstream `dictMatchState`. When present, points at the loaded
    /// dictionary's match-state tables for DMS / DDSS search modes.
    pub dictMatchState: Option<Box<ZSTD_MatchState_t>>,

    /// Upstream `dedicatedDictSearch`. Set on attached dictionary
    /// match states whose tables use the dedicated-dictionary-search
    /// layout.
    pub dedicatedDictSearch: u32,

    /// Raw dictionary bytes associated with this match state. This is
    /// separate from `dictMatchState`: ext-dict modes dereference the
    /// local state's external dictionary bytes, while dictMatchState
    /// modes dereference the attached dictionary state's bytes.
    pub dictContent: Vec<u8>,

    /// Upstream `loadedDictEnd`. Non-zero while a dictionary is in
    /// use.
    pub loadedDictEnd: u32,

    /// Upstream `forceNonContiguous`. When set, the next
    /// `ZSTD_window_update()` must pivot into the non-contiguous
    /// branch even if the incoming source would otherwise look
    /// contiguous in the index space.
    pub forceNonContiguous: bool,

    /// Next index (into the `base`-relative position space) that
    /// `ZSTD_fillHashTable` still needs to insert.
    pub nextToUpdate: u32,

    /// Owned hash table sized `1 << (cParams.hashLog +
    /// ZSTD_SHORT_CACHE_TAG_BITS)` for the tagged-cache variant;
    /// `zstd_fast` uses the untagged `1 << cParams.hashLog`.
    pub hashTable: Vec<u32>,

    /// Secondary hash for 3-byte matches (used by `zstd_double_fast`
    /// and opt paths). Zero-sized until allocated.
    pub hashTable3: Vec<u32>,

    /// Upstream `hashLog3`. Log2 size of `hashTable3`; zero when the
    /// table isn't allocated.
    pub hashLog3: u32,

    /// Upstream `rowHashLog`. Log2 number of rows in the row-hash table.
    pub rowHashLog: u32,

    /// Upstream `tagTable`. Row-hash tags plus per-row head slot.
    pub tagTable: Vec<u8>,

    /// Upstream `hashCache`. Small rolling cache for row-hash updates.
    pub hashCache: [u32; ZSTD_ROW_HASH_CACHE_SIZE],

    /// Row-hash matcher salt — reseeded via `ZSTD_advanceHashSalt`
    /// so reused tables don't collide across compressions.
    pub hashSalt: u64,

    /// Entropy mixed into `hashSalt` on each reset.
    pub hashSaltEntropy: u32,

    /// Upstream `lazySkipping`. Non-zero tells lazy matchfinders to
    /// stop inserting every intermediate position.
    pub lazySkipping: u32,

    /// Chain table for `zstd_lazy` / `zstd_opt`. Zero-sized until
    /// allocated.
    pub chainTable: Vec<u32>,

    /// Upstream `opt`. Persistent optimal-parser pricing state.
    pub opt: crate::compress::zstd_opt::optState_t,

    /// Active compression parameters.
    pub cParams: ZSTD_compressionParameters,

    /// Upstream `prefetchCDictTables`. When true, the dictMatchState
    /// matchers prefetch the attached CDict's hash/chain tables into
    /// cache before each probe. Propagated from
    /// `ZSTD_CCtx_params::prefetchCDictTables` in
    /// `ZSTD_resetCCtx_internal` (mirrors `zstd_compress.c:2217`).
    pub prefetchCDictTables: bool,
}

impl ZSTD_MatchState_t {
    /// Fresh state with the given compression parameters. Hash tables
    /// are sized from `cParams.hashLog`; chain / tag tables stay empty
    /// until the matcher actually needs them.
    pub fn new(cParams: ZSTD_compressionParameters) -> Self {
        let hashSize = 1usize << cParams.hashLog;
        Self {
            window: ZSTD_window_t {
                base_offset: ZSTD_WINDOW_START_INDEX,
                nextSrc: ZSTD_WINDOW_START_INDEX,
                dictBase_offset: ZSTD_WINDOW_START_INDEX,
                dictLimit: ZSTD_WINDOW_START_INDEX,
                lowLimit: ZSTD_WINDOW_START_INDEX,
                nbOverflowCorrections: 0,
            },
            entropySeed: None,
            ldmSeqStore: None,
            dictMatchState: None,
            dedicatedDictSearch: 0,
            dictContent: Vec::new(),
            loadedDictEnd: 0,
            forceNonContiguous: false,
            nextToUpdate: ZSTD_WINDOW_START_INDEX,
            hashTable: vec![0u32; hashSize],
            hashTable3: Vec::new(),
            hashLog3: 0,
            rowHashLog: 0,
            tagTable: Vec::new(),
            hashCache: [0; ZSTD_ROW_HASH_CACHE_SIZE],
            hashSalt: 0,
            hashSaltEntropy: 0,
            lazySkipping: 0,
            chainTable: Vec::new(),
            opt: crate::compress::zstd_opt::optState_t::default(),
            cParams,
            prefetchCDictTables: false,
        }
    }

    /// Reset the match state, keeping allocations.
    pub fn reset(&mut self) {
        self.window = ZSTD_window_t {
            base_offset: ZSTD_WINDOW_START_INDEX,
            nextSrc: ZSTD_WINDOW_START_INDEX,
            dictBase_offset: ZSTD_WINDOW_START_INDEX,
            dictLimit: ZSTD_WINDOW_START_INDEX,
            lowLimit: ZSTD_WINDOW_START_INDEX,
            nbOverflowCorrections: 0,
        };
        self.entropySeed = None;
        self.ldmSeqStore = None;
        self.dictMatchState = None;
        self.dedicatedDictSearch = 0;
        self.dictContent.clear();
        self.loadedDictEnd = 0;
        self.forceNonContiguous = false;
        self.nextToUpdate = ZSTD_WINDOW_START_INDEX;
        for c in self.hashTable.iter_mut() {
            *c = 0;
        }
        for c in self.hashTable3.iter_mut() {
            *c = 0;
        }
        for c in self.tagTable.iter_mut() {
            *c = 0;
        }
        for c in self.chainTable.iter_mut() {
            *c = 0;
        }
        self.rowHashLog = 0;
        self.hashCache = [0; ZSTD_ROW_HASH_CACHE_SIZE];
        self.hashSalt = 0;
        self.hashSaltEntropy = 0;
        self.lazySkipping = 0;
        self.opt = crate::compress::zstd_opt::optState_t::default();
    }
}

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

    #[test]
    fn ZSTD_CURRENT_MAX_and_CHUNKSIZE_MAX_match_upstream_formula() {
        // Previously `(3<<29)+1 = 1.6 GB`; upstream is `3500*(1<<20)
        // = 3.67 GB` on 64-bit / `2000*(1<<20) = 2.0 GB` on 32-bit.
        // Pin the fix so the constant can't drift back.
        let expected = if crate::common::mem::MEM_32bits() != 0 {
            2000u32 * (1u32 << 20)
        } else {
            3500u32 * (1u32 << 20)
        };
        assert_eq!(ZSTD_CURRENT_MAX, expected);
        assert_eq!(ZSTD_CHUNKSIZE_MAX, u32::MAX - ZSTD_CURRENT_MAX);
        // And the dictTooBig gate flips at the chunk boundary.
        assert!(!ZSTD_dictTooBig(ZSTD_CHUNKSIZE_MAX as usize));
        assert!(ZSTD_dictTooBig(ZSTD_CHUNKSIZE_MAX as usize + 1));
    }

    #[test]
    fn ZSTD_dictMode_e_discriminants_match_upstream() {
        // Upstream (zstd_compress_internal.h:551-557):
        //   ZSTD_noDict=0, ZSTD_extDict=1, ZSTD_dictMatchState=2,
        //   ZSTD_dedicatedDictSearch=3
        // Block compressors dispatch on this enum via equality
        // checks; reordering would silently route to wrong strategy.
        assert_eq!(ZSTD_dictMode_e::ZSTD_noDict as u32, 0);
        assert_eq!(ZSTD_dictMode_e::ZSTD_extDict as u32, 1);
        assert_eq!(ZSTD_dictMode_e::ZSTD_dictMatchState as u32, 2);
        assert_eq!(ZSTD_dictMode_e::ZSTD_dedicatedDictSearch as u32, 3);
    }

    #[test]
    fn new_state_sizes_hash_table_from_hashlog() {
        let cp = ZSTD_compressionParameters {
            hashLog: 12,
            minMatch: 5,
            ..Default::default()
        };
        let ms = ZSTD_MatchState_t::new(cp);
        assert_eq!(ms.hashTable.len(), 1 << 12);
        assert_eq!(ms.cParams.minMatch, 5);
        // Initial window indices start at ZSTD_WINDOW_START_INDEX so
        // a zero-valued `hashTable[k] == 0` means "never inserted".
        assert_eq!(ms.nextToUpdate, ZSTD_WINDOW_START_INDEX);
        assert_eq!(ms.window.base_offset, ZSTD_WINDOW_START_INDEX);
        assert_eq!(ms.window.dictBase_offset, ZSTD_WINDOW_START_INDEX);
    }

    #[test]
    fn window_isEmpty_true_at_init() {
        let w = ZSTD_window_t {
            nextSrc: ZSTD_WINDOW_START_INDEX,
            base_offset: ZSTD_WINDOW_START_INDEX,
            dictBase_offset: 0,
            dictLimit: ZSTD_WINDOW_START_INDEX,
            lowLimit: ZSTD_WINDOW_START_INDEX,
            nbOverflowCorrections: 0,
        };
        assert!(ZSTD_window_isEmpty(&w));
    }

    #[test]
    fn window_isEmpty_false_after_nextSrc_advances() {
        let mut w = ZSTD_window_t {
            nextSrc: ZSTD_WINDOW_START_INDEX,
            base_offset: ZSTD_WINDOW_START_INDEX,
            dictBase_offset: 0,
            dictLimit: ZSTD_WINDOW_START_INDEX,
            lowLimit: ZSTD_WINDOW_START_INDEX,
            nbOverflowCorrections: 0,
        };
        w.nextSrc += 1;
        assert!(!ZSTD_window_isEmpty(&w));
    }

    #[test]
    fn window_hasExtDict_tracks_lowLimit_vs_dictLimit() {
        let mut w = ZSTD_window_t::default();
        w.lowLimit = 5;
        w.dictLimit = 10;
        assert!(ZSTD_window_hasExtDict(&w));
        w.lowLimit = 10;
        assert!(!ZSTD_window_hasExtDict(&w));
        w.lowLimit = 11;
        assert!(!ZSTD_window_hasExtDict(&w));
    }

    #[test]
    fn window_clear_collapses_limits_to_nextSrc() {
        let mut w = ZSTD_window_t::default();
        w.nextSrc = 1000;
        w.dictLimit = 50;
        w.lowLimit = 10;
        ZSTD_window_clear(&mut w);
        assert_eq!(w.dictLimit, 1000);
        assert_eq!(w.lowLimit, 1000);
    }

    #[test]
    fn window_update_contiguous_only_advances_nextsrc() {
        let mut w = ZSTD_window_t {
            base_offset: 100,
            dictBase_offset: 80,
            dictLimit: 120,
            lowLimit: 90,
            nextSrc: 150,
            nbOverflowCorrections: 0,
        };
        let contiguous = ZSTD_window_update(&mut w, 150, 20, false);
        assert!(contiguous);
        assert_eq!(w.base_offset, 100);
        assert_eq!(w.dictBase_offset, 80);
        assert_eq!(w.dictLimit, 120);
        assert_eq!(w.lowLimit, 90);
        assert_eq!(w.nextSrc, 170);
    }

    #[test]
    fn window_update_non_contiguous_rotates_prefix_into_extdict() {
        let mut w = ZSTD_window_t {
            base_offset: 100,
            dictBase_offset: 50,
            dictLimit: 110,
            lowLimit: 70,
            nextSrc: 180,
            nbOverflowCorrections: 0,
        };
        let contiguous = ZSTD_window_update(&mut w, 300, 16, true);
        assert!(!contiguous);
        assert_eq!(w.dictBase_offset, 100);
        assert_eq!(w.dictLimit, 180);
        assert_eq!(w.base_offset, 180);
        assert_eq!(w.lowLimit, 110);
        assert_eq!(w.nextSrc, 196);
    }

    #[test]
    fn window_update_non_contiguous_trims_overlapping_prefix() {
        let mut w = ZSTD_window_t {
            base_offset: 100,
            dictBase_offset: 50,
            dictLimit: 110,
            lowLimit: 70,
            nextSrc: 180,
            nbOverflowCorrections: 0,
        };

        let contiguous = ZSTD_window_update(&mut w, 170, 16, true);

        assert!(!contiguous);
        assert_eq!(w.dictBase_offset, 100);
        assert_eq!(w.dictLimit, 180);
        assert_eq!(w.base_offset, 180);
        assert_eq!(w.lowLimit, 180);
        assert_eq!(w.nextSrc, 196);
    }

    #[test]
    fn window_update_first_forced_segment_starts_at_window_start_index() {
        let mut w = ZSTD_window_t::default();
        ZSTD_window_init(&mut w);

        let contiguous = ZSTD_window_update(&mut w, ZSTD_WINDOW_START_INDEX, 64, true);

        assert!(!contiguous);
        assert_eq!(w.base_offset, ZSTD_WINDOW_START_INDEX);
        assert_eq!(w.dictLimit, ZSTD_WINDOW_START_INDEX);
        assert_eq!(w.lowLimit, ZSTD_WINDOW_START_INDEX);
        assert_eq!(w.nextSrc, ZSTD_WINDOW_START_INDEX + 64);
    }

    #[test]
    fn canOverflowCorrect_false_when_curr_too_small() {
        let w = ZSTD_window_t::default();
        // Tiny curr — far below minIndexToOverflowCorrect.
        assert!(!ZSTD_window_canOverflowCorrect(&w, 10, 1 << 20, 0, 1000));
    }

    #[test]
    fn canOverflowCorrect_requires_dict_invalidation() {
        let w = ZSTD_window_t::default();
        let cycleLog = 10;
        let cycleSize = 1u32 << cycleLog;
        let maxDist = 1u32 << 20;
        let minIdx = cycleSize + maxDist.max(cycleSize) + ZSTD_WINDOW_START_INDEX;
        let curr = minIdx + 100;
        // With loadedDictEnd = curr - 100, curr > maxDist + loadedDictEnd
        // only if curr - loadedDictEnd > maxDist, i.e. 100 > 1<<20 → false.
        let loaded = curr - 100;
        assert!(!ZSTD_window_canOverflowCorrect(
            &w, cycleLog, maxDist, loaded, curr
        ));
        // But with loadedDictEnd = 0 the dict is already invalidated.
        assert!(ZSTD_window_canOverflowCorrect(
            &w, cycleLog, maxDist, 0, curr
        ));
    }

    #[test]
    fn canOverflowCorrect_wraps_backoff_multiply_then_clamps() {
        let cycleLog = 10;
        let cycleSize = 1u32 << cycleLog;
        let maxDist = 1u32 << 20;
        let minIdx = cycleSize
            .wrapping_add(maxDist.max(cycleSize))
            .wrapping_add(ZSTD_WINDOW_START_INDEX);
        let adjustment = u32::MAX / minIdx + 1;
        let wrappedAdjusted = minIdx.wrapping_mul(adjustment);
        assert!(wrappedAdjusted < minIdx);

        let w = ZSTD_window_t {
            nbOverflowCorrections: adjustment - 1,
            ..Default::default()
        };

        assert!(ZSTD_window_canOverflowCorrect(
            &w,
            cycleLog,
            maxDist,
            0,
            minIdx + 1
        ));
    }

    #[test]
    fn needOverflowCorrection_tracks_ZSTD_CURRENT_MAX() {
        let w = ZSTD_window_t::default();
        assert!(!ZSTD_window_needOverflowCorrection(
            &w,
            10,
            1 << 20,
            0,
            0,
            1000
        ));
        assert!(!ZSTD_window_needOverflowCorrection(
            &w,
            10,
            1 << 20,
            0,
            0,
            ZSTD_CURRENT_MAX
        ));
        assert!(ZSTD_window_needOverflowCorrection(
            &w,
            10,
            1 << 20,
            0,
            0,
            ZSTD_CURRENT_MAX + 1,
        ));
    }

    #[test]
    fn correctOverflow_preserves_cycle_alignment() {
        let mut w = ZSTD_window_t::default();
        w.dictLimit = 1 << 24;
        w.lowLimit = 1 << 20;
        let cycleLog = 16;
        let maxDist = 1u32 << 20;
        let src_abs: u32 = ZSTD_CURRENT_MAX + 1000;
        let correction = ZSTD_window_correctOverflow(&mut w, cycleLog, maxDist, src_abs);
        // newCurrent = curr - correction; they must share cycle bits.
        let cycleMask = (1u32 << cycleLog) - 1;
        let newCurrent = src_abs - correction;
        assert_eq!(src_abs & cycleMask, newCurrent & cycleMask);
        assert_eq!(w.nbOverflowCorrections, 1);
        assert!(newCurrent >= maxDist);
    }

    #[test]
    fn correctOverflow_floors_lowLimit_when_small() {
        let mut w = ZSTD_window_t::default();
        // lowLimit smaller than correction → gets pinned at START_INDEX.
        w.lowLimit = 5;
        w.dictLimit = 1 << 24;
        let src_abs: u32 = ZSTD_CURRENT_MAX + 500;
        ZSTD_window_correctOverflow(&mut w, 16, 1u32 << 20, src_abs);
        assert_eq!(w.lowLimit, ZSTD_WINDOW_START_INDEX);
    }

    #[test]
    fn correctOverflow_returns_positive_correction() {
        let mut w = ZSTD_window_t::default();
        w.dictLimit = 1 << 24;
        let src_abs: u32 = ZSTD_CURRENT_MAX + 42;
        let c = ZSTD_window_correctOverflow(&mut w, 16, 1u32 << 20, src_abs);
        // Upstream asserts correction > 1<<28 outside frequent-correct
        // mode — verify we land in that ballpark.
        assert!(c > (1u32 << 28));
    }

    #[test]
    fn correctOverflow_rebases_offsets_downward() {
        let src_abs: u32 = ZSTD_CURRENT_MAX + 4096;
        let mut w = ZSTD_window_t {
            base_offset: src_abs - 1024,
            dictBase_offset: src_abs - 8192,
            dictLimit: src_abs - 4096,
            lowLimit: src_abs - (1 << 20),
            nextSrc: src_abs,
            nbOverflowCorrections: 0,
        };
        let old_base = w.base_offset;
        let old_dict_base = w.dictBase_offset;
        let old_next_src = w.nextSrc;
        let correction = ZSTD_window_correctOverflow(&mut w, 16, 1u32 << 20, src_abs);

        assert_eq!(w.base_offset, old_base.wrapping_sub(correction));
        assert_eq!(w.dictBase_offset, old_dict_base.wrapping_sub(correction));
        assert_eq!(w.nextSrc, old_next_src.wrapping_sub(correction));
    }

    #[test]
    fn window_init_sets_all_sentinels() {
        let mut w = ZSTD_window_t {
            nextSrc: 999,
            base_offset: 42,
            dictBase_offset: 17,
            dictLimit: 500,
            lowLimit: 400,
            nbOverflowCorrections: 5,
        };
        ZSTD_window_init(&mut w);
        assert_eq!(w.nextSrc, ZSTD_WINDOW_START_INDEX);
        assert_eq!(w.base_offset, ZSTD_WINDOW_START_INDEX);
        assert_eq!(w.dictBase_offset, ZSTD_WINDOW_START_INDEX);
        assert_eq!(w.dictLimit, ZSTD_WINDOW_START_INDEX);
        assert_eq!(w.lowLimit, ZSTD_WINDOW_START_INDEX);
        assert_eq!(w.nbOverflowCorrections, 0);
        assert!(ZSTD_window_isEmpty(&w));
    }

    #[test]
    fn enforceMaxDist_noop_when_within_dist() {
        let mut w = ZSTD_window_t::default();
        w.lowLimit = 5;
        w.dictLimit = 10;
        let mut dictEnd = 0u32;
        // blockEnd 50, maxDist 100: still within range, no update.
        assert!(!ZSTD_window_enforceMaxDist(&mut w, 50, 100, &mut dictEnd));
        assert_eq!(w.lowLimit, 5);
        assert_eq!(w.dictLimit, 10);
    }

    #[test]
    fn enforceMaxDist_advances_lowLimit_and_invalidates_dict() {
        let mut w = ZSTD_window_t::default();
        w.lowLimit = 5;
        w.dictLimit = 10;
        let mut dictEnd = 50u32;
        // blockEnd = 1200, maxDist = 100, loaded = 50 → 1200 > 150 → shift.
        // newLowLimit = 1100. dictLimit (10) < newLowLimit, so dictLimit = 1100.
        assert!(ZSTD_window_enforceMaxDist(&mut w, 1200, 100, &mut dictEnd));
        assert_eq!(w.lowLimit, 1100);
        assert_eq!(w.dictLimit, 1100);
        assert_eq!(dictEnd, 0);
    }

    #[test]
    fn enforceMaxDist_uses_wrapping_loaded_end_distance() {
        let mut w = ZSTD_window_t::default();
        w.lowLimit = 5;
        w.dictLimit = 10;
        let maxDist = 100;
        let mut dictEnd = u32::MAX - 50;

        assert!(ZSTD_window_enforceMaxDist(
            &mut w,
            60,
            maxDist,
            &mut dictEnd
        ));
        assert_eq!(w.lowLimit, 60u32.wrapping_sub(maxDist));
        assert_eq!(w.dictLimit, w.lowLimit);
        assert_eq!(dictEnd, 0);
    }

    #[test]
    fn matchState_enforceMaxDist_clears_dictMatchState() {
        let cp = ZSTD_compressionParameters::default();
        let mut ms = ZSTD_MatchState_t::new(cp);
        ms.window.lowLimit = 5;
        ms.window.dictLimit = 10;
        ms.loadedDictEnd = 50;
        ms.dictMatchState = Some(Box::new(ZSTD_MatchState_t::new(cp)));

        assert!(ZSTD_matchState_enforceMaxDist(&mut ms, 1200, 100));

        assert_eq!(ms.loadedDictEnd, 0);
        assert!(ms.dictMatchState.is_none());
    }

    #[test]
    fn checkDictValidity_invalidates_past_window() {
        let w = ZSTD_window_t {
            dictLimit: 100,
            ..Default::default()
        };
        let mut dictEnd = 100u32;
        // blockEnd = 500, maxDist = 100, loaded = 100 → 500 > 200 → invalidate.
        assert!(ZSTD_checkDictValidity(&w, 500, 100, &mut dictEnd));
        assert_eq!(dictEnd, 0);
    }

    #[test]
    fn checkDictValidity_uses_wrapping_loaded_end_distance() {
        let loadedEnd = u32::MAX - 50;
        let w = ZSTD_window_t {
            dictLimit: loadedEnd,
            ..Default::default()
        };
        let mut dictEnd = loadedEnd;

        assert!(ZSTD_checkDictValidity(&w, 60, 100, &mut dictEnd));
        assert_eq!(dictEnd, 0);
    }

    #[test]
    fn checkDictValidity_invalidates_on_noncontig_jump() {
        let w = ZSTD_window_t {
            dictLimit: 100,
            ..Default::default()
        };
        let mut dictEnd = 80u32; // != dictLimit
        assert!(ZSTD_checkDictValidity(&w, 150, 1000, &mut dictEnd));
        assert_eq!(dictEnd, 0);
    }

    #[test]
    fn matchState_checkDictValidity_clears_dictMatchState() {
        let cp = ZSTD_compressionParameters::default();
        let mut ms = ZSTD_MatchState_t::new(cp);
        ms.window.dictLimit = 100;
        ms.loadedDictEnd = 80;
        ms.dictMatchState = Some(Box::new(ZSTD_MatchState_t::new(cp)));

        assert!(ZSTD_matchState_checkDictValidity(&mut ms, 150, 1000));

        assert_eq!(ms.loadedDictEnd, 0);
        assert!(ms.dictMatchState.is_none());
    }

    #[test]
    fn index_overlap_check_reports_non_overlap() {
        // prefixLowestIndex=100, repIndex=50 → (99 - 50) = 49 ≥ 3 → true.
        assert!(ZSTD_index_overlap_check(100, 50));
    }

    #[test]
    fn index_overlap_check_detects_guardband_overlap() {
        // repIndex inside the 3-byte guard below prefixLowestIndex.
        // prefixLowestIndex=100, repIndex=98 → (99 - 98) = 1 < 3 → false.
        assert!(!ZSTD_index_overlap_check(100, 98));
        assert!(!ZSTD_index_overlap_check(100, 99));
    }

    #[test]
    fn index_overlap_check_pass_when_in_prefix() {
        // repIndex >= prefixLowestIndex: (prefix-1 - repIndex) wraps
        // to a huge u32 ≥ 3 — upstream reads this as non-overlap
        // (repIndex sits in the prefix itself, always valid).
        assert!(ZSTD_index_overlap_check(100, 100));
        assert!(ZSTD_index_overlap_check(100, 500));
    }

    #[test]
    fn writeTaggedIndex_roundtrip() {
        let mut t = vec![0u32; 16];
        // hash=5, tag=0xAB → hashAndTag = (5<<8)|0xAB = 0x5AB.
        let hashAndTag: usize = (5 << ZSTD_SHORT_CACHE_TAG_BITS) | 0xAB;
        ZSTD_writeTaggedIndex(&mut t, hashAndTag, 0x1234);
        // Stored value should be (0x1234 << 8) | 0xAB.
        assert_eq!(t[5], (0x1234u32 << 8) | 0xAB);
    }

    #[test]
    fn comparePackedTags_matches_low_byte_only() {
        let a: usize = (0xDEADBEEF << 8) | 0x42;
        let b: usize = (0x12345678 << 8) | 0x42;
        let c: usize = (0x12345678 << 8) | 0x41;
        assert!(ZSTD_comparePackedTags(a, b));
        assert!(!ZSTD_comparePackedTags(a, c));
    }

    #[test]
    fn reduceTable_shifts_above_threshold_and_floors_below() {
        let mut t = vec![0u32; ZSTD_ROWSIZE];
        t[0] = 100;
        t[1] = 50;
        t[2] = 42;
        t[3] = 2; // just under threshold (reducer=40, threshold=40+2=42)
        ZSTD_reduceTable(&mut t, 40);
        assert_eq!(t[0], 60);
        assert_eq!(t[1], 10);
        assert_eq!(t[2], 2); // 42 >= 42 threshold → 42-40=2
        assert_eq!(t[3], 0); // 2 < threshold → floored
    }

    #[test]
    fn reduceTable_btlazy2_preserves_unsorted_mark() {
        let mut t = vec![0u32; ZSTD_ROWSIZE];
        t[0] = 100;
        t[1] = ZSTD_DUBT_UNSORTED_MARK;
        t[2] = ZSTD_DUBT_UNSORTED_MARK;
        t[3] = 50;
        ZSTD_reduceTable_btlazy2(&mut t, 40);
        assert_eq!(t[0], 60);
        assert_eq!(t[1], ZSTD_DUBT_UNSORTED_MARK); // preserved
        assert_eq!(t[2], ZSTD_DUBT_UNSORTED_MARK); // preserved
        assert_eq!(t[3], 10);
    }

    #[test]
    fn reduceTable_plain_does_not_preserve_unsorted_mark() {
        let mut t = vec![0u32; ZSTD_ROWSIZE];
        t[1] = ZSTD_DUBT_UNSORTED_MARK;
        ZSTD_reduceTable(&mut t, 40);
        // UNSORTED_MARK=1 < threshold=42 → squashed to 0.
        assert_eq!(t[1], 0);
    }

    #[test]
    fn reduceTable_uses_wrapping_u32_arithmetic() {
        let mut t = vec![0u32; ZSTD_ROWSIZE];
        t[0] = 0;
        t[1] = 1;
        t[2] = u32::MAX;

        ZSTD_reduceTable(&mut t, u32::MAX);

        assert_eq!(t[0], 0);
        assert_eq!(t[1], 2);
        assert_eq!(t[2], 0);
    }

    #[test]
    fn rowMatchFinderSupported_only_for_greedy_lazy_lazy2() {
        assert!(!ZSTD_rowMatchFinderSupported(1)); // fast
        assert!(!ZSTD_rowMatchFinderSupported(2)); // dfast
        assert!(ZSTD_rowMatchFinderSupported(3)); // greedy
        assert!(ZSTD_rowMatchFinderSupported(4)); // lazy
        assert!(ZSTD_rowMatchFinderSupported(5)); // lazy2
        assert!(!ZSTD_rowMatchFinderSupported(6)); // btlazy2
        assert!(!ZSTD_rowMatchFinderSupported(7)); // btopt
    }

    #[test]
    fn allocateChainTable_rules() {
        use crate::compress::zstd_ldm::ZSTD_ParamSwitch_e;
        // fast (1) → never allocate (except DDS).
        assert!(!ZSTD_allocateChainTable(
            1,
            ZSTD_ParamSwitch_e::ZSTD_ps_disable,
            0
        ));
        assert!(ZSTD_allocateChainTable(
            1,
            ZSTD_ParamSwitch_e::ZSTD_ps_disable,
            1
        ));
        // dfast (2) → always allocate.
        assert!(ZSTD_allocateChainTable(
            2,
            ZSTD_ParamSwitch_e::ZSTD_ps_disable,
            0
        ));
        // greedy (3) with row matchfinder enabled → skip chain.
        assert!(!ZSTD_allocateChainTable(
            3,
            ZSTD_ParamSwitch_e::ZSTD_ps_enable,
            0
        ));
        // greedy (3) with row matchfinder disabled → allocate.
        assert!(ZSTD_allocateChainTable(
            3,
            ZSTD_ParamSwitch_e::ZSTD_ps_disable,
            0
        ));
        // btlazy2 (6) → row matchfinder not supported, always allocate.
        assert!(ZSTD_allocateChainTable(
            6,
            ZSTD_ParamSwitch_e::ZSTD_ps_enable,
            0
        ));
    }

    #[test]
    fn reduceIndex_touches_hash_chain_and_hash3() {
        use crate::compress::zstd_ldm::ZSTD_ParamSwitch_e;
        let cp = ZSTD_compressionParameters {
            hashLog: 4, // 16 entries → multiple of ZSTD_ROWSIZE
            chainLog: 4,
            strategy: 2, // dfast → chainTable used
            ..Default::default()
        };
        let mut ms = ZSTD_MatchState_t::new(cp);
        ms.chainTable = vec![100u32; 16];
        ms.hashTable3 = vec![100u32; 16];
        ms.hashLog3 = 4;
        for h in ms.hashTable.iter_mut() {
            *h = 100;
        }

        ZSTD_reduceIndex(&mut ms, ZSTD_ParamSwitch_e::ZSTD_ps_disable, 40);

        // All three tables shifted by 40 — entries that were 100 become 60.
        assert!(ms.hashTable.iter().all(|&x| x == 60));
        assert!(ms.chainTable.iter().all(|&x| x == 60));
        assert!(ms.hashTable3.iter().all(|&x| x == 60));
    }

    #[test]
    fn reduceIndex_uses_c_table_sizes_not_vec_tail() {
        use crate::compress::zstd_ldm::ZSTD_ParamSwitch_e;
        let cp = ZSTD_compressionParameters {
            hashLog: 4,
            chainLog: 4,
            strategy: 2,
            ..Default::default()
        };
        let mut ms = ZSTD_MatchState_t::new(cp);
        ms.hashTable.resize(32, 100);
        ms.chainTable = vec![100u32; 32];
        ms.hashTable3 = vec![100u32; 32];
        ms.hashLog3 = 4;
        for h in ms.hashTable.iter_mut() {
            *h = 100;
        }

        ZSTD_reduceIndex(&mut ms, ZSTD_ParamSwitch_e::ZSTD_ps_disable, 40);

        assert!(ms.hashTable[..16].iter().all(|&x| x == 60));
        assert!(ms.hashTable[16..].iter().all(|&x| x == 100));
        assert!(ms.chainTable[..16].iter().all(|&x| x == 60));
        assert!(ms.chainTable[16..].iter().all(|&x| x == 100));
        assert!(ms.hashTable3[..16].iter().all(|&x| x == 60));
        assert!(ms.hashTable3[16..].iter().all(|&x| x == 100));
    }

    #[test]
    fn reduceIndex_skips_chain_table_for_fast_strategy() {
        use crate::compress::zstd_ldm::ZSTD_ParamSwitch_e;
        let cp = ZSTD_compressionParameters {
            hashLog: 4,
            chainLog: 4,
            strategy: 1, // fast → no chain table
            ..Default::default()
        };
        let mut ms = ZSTD_MatchState_t::new(cp);
        ms.chainTable = vec![100u32; 16];

        ZSTD_reduceIndex(&mut ms, ZSTD_ParamSwitch_e::ZSTD_ps_disable, 40);
        // Fast strategy skips chain reduction.
        assert!(ms.chainTable.iter().all(|&x| x == 100));
    }

    #[test]
    fn reduceIndex_uses_match_state_dedicated_dict_search_for_chain_allocation() {
        use crate::compress::zstd_ldm::ZSTD_ParamSwitch_e;
        let cp = ZSTD_compressionParameters {
            hashLog: 4,
            chainLog: 4,
            strategy: 1, // fast normally skips chainTable
            ..Default::default()
        };
        let mut ms = ZSTD_MatchState_t::new(cp);
        ms.dedicatedDictSearch = 1;
        ms.chainTable = vec![100u32; 16];

        ZSTD_reduceIndex(&mut ms, ZSTD_ParamSwitch_e::ZSTD_ps_disable, 40);

        assert!(ms.chainTable.iter().all(|&x| x == 60));
    }

    #[test]
    fn resolveRowMatchFinderMode_respects_explicit_mode() {
        use crate::compress::zstd_ldm::ZSTD_ParamSwitch_e;
        let cp = ZSTD_compressionParameters {
            strategy: 3,
            windowLog: 10,
            ..Default::default()
        };
        assert_eq!(
            ZSTD_resolveRowMatchFinderMode(ZSTD_ParamSwitch_e::ZSTD_ps_enable, &cp),
            ZSTD_ParamSwitch_e::ZSTD_ps_enable,
        );
    }

    #[test]
    fn resolveRowMatchFinderMode_auto_requires_windowLog_above_14() {
        use crate::compress::zstd_ldm::ZSTD_ParamSwitch_e;
        let lower_bound = 14;
        let mut cp = ZSTD_compressionParameters {
            strategy: 3,
            windowLog: lower_bound,
            ..Default::default()
        };
        assert_eq!(
            ZSTD_resolveRowMatchFinderMode(ZSTD_ParamSwitch_e::ZSTD_ps_auto, &cp),
            ZSTD_ParamSwitch_e::ZSTD_ps_disable,
        );
        cp.windowLog = lower_bound + 1;
        assert_eq!(
            ZSTD_resolveRowMatchFinderMode(ZSTD_ParamSwitch_e::ZSTD_ps_auto, &cp),
            ZSTD_ParamSwitch_e::ZSTD_ps_enable,
        );
        // Unsupported strategy → disable regardless.
        cp.strategy = 7;
        assert_eq!(
            ZSTD_resolveRowMatchFinderMode(ZSTD_ParamSwitch_e::ZSTD_ps_auto, &cp),
            ZSTD_ParamSwitch_e::ZSTD_ps_disable,
        );
    }

    #[test]
    fn resolveBlockSplitterMode_auto_gates_on_btopt_and_wlog_17() {
        use crate::compress::zstd_ldm::ZSTD_ParamSwitch_e;
        let cp_lazy = ZSTD_compressionParameters {
            strategy: 3,
            windowLog: 20,
            ..Default::default()
        };
        assert_eq!(
            ZSTD_resolveBlockSplitterMode(ZSTD_ParamSwitch_e::ZSTD_ps_auto, &cp_lazy),
            ZSTD_ParamSwitch_e::ZSTD_ps_disable,
        );
        let cp_btopt_small = ZSTD_compressionParameters {
            strategy: 7,
            windowLog: 16,
            ..Default::default()
        };
        assert_eq!(
            ZSTD_resolveBlockSplitterMode(ZSTD_ParamSwitch_e::ZSTD_ps_auto, &cp_btopt_small),
            ZSTD_ParamSwitch_e::ZSTD_ps_disable,
        );
        let cp_btopt_big = ZSTD_compressionParameters {
            strategy: 7,
            windowLog: 17,
            ..Default::default()
        };
        assert_eq!(
            ZSTD_resolveBlockSplitterMode(ZSTD_ParamSwitch_e::ZSTD_ps_auto, &cp_btopt_big),
            ZSTD_ParamSwitch_e::ZSTD_ps_enable,
        );
    }

    #[test]
    fn resolveEnableLdm_auto_enables_for_btopt_with_large_window() {
        use crate::compress::zstd_ldm::ZSTD_ParamSwitch_e;
        let cp_btopt_small = ZSTD_compressionParameters {
            strategy: 7,
            windowLog: 26,
            ..Default::default()
        };
        assert_eq!(
            ZSTD_resolveEnableLdm(ZSTD_ParamSwitch_e::ZSTD_ps_auto, &cp_btopt_small),
            ZSTD_ParamSwitch_e::ZSTD_ps_disable,
        );
        let cp_btopt_huge = ZSTD_compressionParameters {
            strategy: 9,
            windowLog: 27,
            ..Default::default()
        };
        assert_eq!(
            ZSTD_resolveEnableLdm(ZSTD_ParamSwitch_e::ZSTD_ps_auto, &cp_btopt_huge),
            ZSTD_ParamSwitch_e::ZSTD_ps_enable,
        );
        assert_eq!(
            ZSTD_resolveEnableLdm(ZSTD_ParamSwitch_e::ZSTD_ps_enable, &cp_btopt_huge),
            ZSTD_ParamSwitch_e::ZSTD_ps_enable,
        );
    }

    #[test]
    fn resolveMaxBlockSize_zero_means_default() {
        use crate::decompress::zstd_decompress_block::ZSTD_BLOCKSIZE_MAX;
        assert_eq!(ZSTD_resolveMaxBlockSize(0), ZSTD_BLOCKSIZE_MAX);
        assert_eq!(ZSTD_resolveMaxBlockSize(12345), 12345);
    }

    #[test]
    fn matchState_dictMode_reports_noDict_on_fresh() {
        let cp = ZSTD_compressionParameters::default();
        let ms = ZSTD_MatchState_t::new(cp);
        assert_eq!(ZSTD_matchState_dictMode(&ms), ZSTD_dictMode_e::ZSTD_noDict);
    }

    #[test]
    fn matchState_dictMode_reports_extDict_when_lowLimit_below_dictLimit() {
        let cp = ZSTD_compressionParameters::default();
        let mut ms = ZSTD_MatchState_t::new(cp);
        ms.window.lowLimit = 5;
        ms.window.dictLimit = 10;
        assert_eq!(ZSTD_matchState_dictMode(&ms), ZSTD_dictMode_e::ZSTD_extDict);
    }

    #[test]
    fn matchState_dictMode_reports_dictMatchState_when_attached_with_zero_loadedDictEnd() {
        let cp = ZSTD_compressionParameters::default();
        let mut ms = ZSTD_MatchState_t::new(cp);
        ms.dictMatchState = Some(Box::new(ZSTD_MatchState_t::new(cp)));
        ms.loadedDictEnd = 0;
        assert_eq!(
            ZSTD_matchState_dictMode(&ms),
            ZSTD_dictMode_e::ZSTD_dictMatchState
        );
    }

    #[test]
    fn matchState_dictMode_reports_dedicatedDictSearch_from_attached_state() {
        let cp = ZSTD_compressionParameters::default();
        let mut ms = ZSTD_MatchState_t::new(cp);
        let mut dict_ms = ZSTD_MatchState_t::new(cp);
        dict_ms.dedicatedDictSearch = 1;
        ms.dictMatchState = Some(Box::new(dict_ms));

        assert_eq!(
            ZSTD_matchState_dictMode(&ms),
            ZSTD_dictMode_e::ZSTD_dedicatedDictSearch
        );
    }

    #[test]
    fn matchState_dictMode_prioritizes_extDict_over_dictMatchState() {
        let cp = ZSTD_compressionParameters::default();
        let mut ms = ZSTD_MatchState_t::new(cp);
        ms.dictMatchState = Some(Box::new(ZSTD_MatchState_t::new(cp)));
        ms.loadedDictEnd = 32;
        ms.window.lowLimit = 5;
        ms.window.dictLimit = 10;
        assert_eq!(ZSTD_matchState_dictMode(&ms), ZSTD_dictMode_e::ZSTD_extDict);
    }

    #[test]
    fn matchState_dictMode_prioritizes_extDict_over_dedicatedDictSearch() {
        let cp = ZSTD_compressionParameters::default();
        let mut ms = ZSTD_MatchState_t::new(cp);
        let mut dict_ms = ZSTD_MatchState_t::new(cp);
        dict_ms.dedicatedDictSearch = 1;
        ms.dictMatchState = Some(Box::new(dict_ms));
        ms.window.lowLimit = 5;
        ms.window.dictLimit = 10;

        assert_eq!(ZSTD_matchState_dictMode(&ms), ZSTD_dictMode_e::ZSTD_extDict);
    }

    #[test]
    fn resolveExternalRepcodeSearch_auto_flips_at_level_10() {
        use crate::compress::zstd_ldm::ZSTD_ParamSwitch_e;
        assert_eq!(
            ZSTD_resolveExternalRepcodeSearch(ZSTD_ParamSwitch_e::ZSTD_ps_auto, 9),
            ZSTD_ParamSwitch_e::ZSTD_ps_disable,
        );
        assert_eq!(
            ZSTD_resolveExternalRepcodeSearch(ZSTD_ParamSwitch_e::ZSTD_ps_auto, 10),
            ZSTD_ParamSwitch_e::ZSTD_ps_enable,
        );
        // Explicit values pass through.
        assert_eq!(
            ZSTD_resolveExternalRepcodeSearch(ZSTD_ParamSwitch_e::ZSTD_ps_enable, 1),
            ZSTD_ParamSwitch_e::ZSTD_ps_enable,
        );
    }

    #[test]
    fn CDictIndicesAreTagged_fast_family() {
        assert!(ZSTD_CDictIndicesAreTagged(&ZSTD_compressionParameters {
            strategy: 1,
            ..Default::default()
        }));
        assert!(ZSTD_CDictIndicesAreTagged(&ZSTD_compressionParameters {
            strategy: 2,
            ..Default::default()
        }));
        assert!(!ZSTD_CDictIndicesAreTagged(&ZSTD_compressionParameters {
            strategy: 3,
            ..Default::default()
        }));
        assert!(!ZSTD_CDictIndicesAreTagged(&ZSTD_compressionParameters {
            strategy: 9,
            ..Default::default()
        }));
    }

    #[test]
    fn resolveExternalSequenceValidation_is_identity() {
        assert_eq!(ZSTD_resolveExternalSequenceValidation(0), 0);
        assert_eq!(ZSTD_resolveExternalSequenceValidation(1), 1);
        assert_eq!(ZSTD_resolveExternalSequenceValidation(42), 42);
    }

    #[test]
    fn bitmix_is_non_identity() {
        assert_ne!(ZSTD_bitmix(0xDEADBEEF, 8), 0xDEADBEEF);
        // Determinism.
        assert_eq!(ZSTD_bitmix(42, 8), ZSTD_bitmix(42, 8));
    }

    #[test]
    fn advanceHashSalt_changes_salt() {
        let cp = ZSTD_compressionParameters::default();
        let mut ms = ZSTD_MatchState_t::new(cp);
        ms.hashSaltEntropy = 0x1234;
        let before = ms.hashSalt;
        ZSTD_advanceHashSalt(&mut ms);
        assert_ne!(ms.hashSalt, before);
    }

    #[test]
    fn invalidateMatchState_resets_window_and_nextToUpdate() {
        let cp = ZSTD_compressionParameters::default();
        let mut ms = ZSTD_MatchState_t::new(cp);
        // Pretend we processed a bunch of input.
        ms.window.nextSrc = 500;
        ms.window.dictLimit = 50;
        ms.window.lowLimit = 25;
        ms.nextToUpdate = 400;
        ms.loadedDictEnd = 99;
        ms.dictMatchState = Some(Box::new(ZSTD_MatchState_t::new(cp)));
        ms.opt.litLengthSum = 77;
        ZSTD_invalidateMatchState(&mut ms);
        // window_clear collapses dictLimit/lowLimit to nextSrc = 500.
        assert_eq!(ms.window.dictLimit, 500);
        assert_eq!(ms.window.lowLimit, 500);
        assert_eq!(ms.nextToUpdate, 500); // tracks dictLimit
        assert_eq!(ms.loadedDictEnd, 0);
        assert!(ms.dictMatchState.is_none());
        assert_eq!(ms.opt.litLengthSum, 0);
    }

    #[test]
    fn overflowCorrectIfNeeded_clears_dictMatchState() {
        use crate::compress::zstd_ldm::ZSTD_ParamSwitch_e;

        let cp = ZSTD_compressionParameters {
            hashLog: 4,
            windowLog: 20,
            chainLog: 16,
            strategy: 1,
            ..Default::default()
        };
        let mut ms = ZSTD_MatchState_t::new(cp);
        ms.loadedDictEnd = 99;
        ms.dictMatchState = Some(Box::new(ZSTD_MatchState_t::new(cp)));
        let src_abs = ZSTD_CURRENT_MAX + 4096;

        ZSTD_overflowCorrectIfNeeded(
            &mut ms,
            ZSTD_ParamSwitch_e::ZSTD_ps_disable,
            0,
            cp.windowLog,
            cp.chainLog,
            cp.strategy,
            src_abs,
            src_abs,
        );

        assert_eq!(ms.loadedDictEnd, 0);
        assert!(ms.dictMatchState.is_none());
    }

    #[test]
    fn reset_preserves_allocation_but_zeros_table() {
        let cp = ZSTD_compressionParameters {
            hashLog: 10,
            minMatch: 4,
            ..Default::default()
        };
        let mut ms = ZSTD_MatchState_t::new(cp);
        for c in ms.hashTable.iter_mut().take(16) {
            *c = 0xdead;
        }
        ms.nextToUpdate = 100;
        ms.reset();
        assert!(ms.hashTable.iter().all(|&c| c == 0));
        assert_eq!(ms.nextToUpdate, ZSTD_WINDOW_START_INDEX);
        assert_eq!(ms.window.dictBase_offset, ZSTD_WINDOW_START_INDEX);
        assert_eq!(ms.hashTable.len(), 1 << 10);
    }
}