zexc 1.1.0

zex native lossless compressor — CLI zexc, library zexc, files *.zex
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
//! # ZEX Native Codec — original algorithm (not LZ4, not Zstd)
//!
//! ## Speed (SIMD)
//! - Wide 16-byte match length via [`crate::utils::simd`]
//! - Adaptive skip on incompressible data
//!
//! ## Ratio tuning (levels 1–22)
//! - Hash **chain** (not single-slot only) at mid/high levels
//! - **Lazy** matching (prefer longer match one byte later)
//! - **Dual hash** (4-byte + 5-byte) for fewer false negatives
//! - Optional Huffman on literals when it shrinks the block
//! - `min_gain` filter: skip short matches that waste tokens
//!
//! ## Dictionary history
//!
//! Optional dictionary bytes are a **virtual prefix** before each block:
//! ```text
//! [ dictionary | block content … ]
//! ```
//! Matches may point into the dictionary (same model as Zstd dict prefix).
//! Dictionary itself is never written into the block; both sides must share it.

use crate::format::block::BlockType;
use crate::utils::bitstream::{BitReader, BitWriter};
use crate::utils::entropy::{build_encoder, decoder_from_lengths};
use crate::utils::security::{
    check_block_sizes, check_match_with_history, MAX_MATCH_LEN, MAX_OFFSET, MIN_MATCH,
};
use crate::utils::fse::{
    decode_u32_array, decode_u32_array_auto, encode_u32_array, encode_u32_array_compact,
    encode_ll, encode_ml, encode_off_log2,
    decode_ll, decode_ml, decode_off_log2,
};
use crate::utils::simd::{self, copy_match_with_history};
use crate::{Error, Result};

// ─── Level → search parameters (ratio / speed tradeoff) ──────────────────────

#[derive(Clone, Copy, Debug)]
struct LevelParams {
    hash_log: u32,
    /// Chain table log (0 = no chain, single slot).
    chain_log: u32,
    /// Max chain probes per position.
    searches: u32,
    /// Acceleration: how fast skip grows on misses.
    accel: u32,
    /// Window size (bytes).
    window: usize,
    /// Huffman-pack literals when beneficial.
    entropy: bool,
    /// Try match at ip+1 (lazy).
    lazy: bool,
    /// Also index/search with 5-byte hash.
    dual_hash: bool,
    /// Reject matches shorter than this unless very close offset.
    min_match_accept: usize,
    /// Sufficient match length to stop searching.
    good_enough: usize,
}

fn params_for_level(level: u8) -> LevelParams {
    let level = level.clamp(1, 22);
    match level {
        1 => LevelParams {
            hash_log: 12,
            chain_log: 0,
            searches: 1,
            accel: 6,
            window: 64 * 1024,
            entropy: false,
            lazy: false,
            dual_hash: false,
            min_match_accept: MIN_MATCH,
            good_enough: 32,
        },
        2 => LevelParams {
            hash_log: 13,
            chain_log: 0,
            searches: 1,
            accel: 4,
            window: 64 * 1024,
            entropy: false,
            lazy: false,
            dual_hash: false,
            min_match_accept: MIN_MATCH,
            good_enough: 48,
        },
        3 | 4 => LevelParams {
            hash_log: 14,
            chain_log: 12,
            searches: 4,
            accel: 3,
            window: 128 * 1024,
            entropy: false,
            lazy: true,
            dual_hash: false,
            min_match_accept: MIN_MATCH,
            good_enough: 64,
        },
        5 | 6 => LevelParams {
            hash_log: 15,
            chain_log: 13,
            searches: 12,
            accel: 2,
            window: 256 * 1024,
            entropy: false,
            lazy: true,
            dual_hash: true,
            min_match_accept: MIN_MATCH,
            good_enough: 96,
        },
        7..=9 => LevelParams {
            hash_log: 16,
            chain_log: 14,
            searches: 32,
            accel: 1,
            window: 512 * 1024,
            entropy: true,
            lazy: true,
            dual_hash: true,
            min_match_accept: MIN_MATCH,
            good_enough: 128,
        },
        10..=12 => LevelParams {
            hash_log: 17,
            chain_log: 15,
            searches: 64,
            accel: 1,
            window: 1024 * 1024,
            entropy: true,
            lazy: true,
            dual_hash: true,
            min_match_accept: MIN_MATCH,
            good_enough: 192,
        },
        13..=16 => LevelParams {
            hash_log: 17,
            chain_log: 16,
            searches: 128,
            accel: 1,
            window: 2 * 1024 * 1024,
            entropy: true,
            lazy: true,
            dual_hash: true,
            min_match_accept: MIN_MATCH,
            good_enough: 256,
        },
        _ => LevelParams {
            hash_log: 18,
            chain_log: 17,
            searches: 512,
            accel: 1,
            window: MAX_OFFSET,
            entropy: true,
            lazy: true,
            dual_hash: true,
            min_match_accept: MIN_MATCH,
            good_enough: 512,
        },
    }
}

// ─── Match finder with optional hash chain + dual hash ───────────────────────

struct MatchFinder {
    hash_log: u32,
    chain_log: u32,
    hash_table: Vec<u32>,
    /// Second table for 5-byte hash (dual).
    hash5_table: Vec<u32>,
    chain: Vec<u32>,
    dual: bool,
    window: usize,
}

impl MatchFinder {
    fn new(p: &LevelParams, total_len: usize) -> Self {
        let hash_size = 1usize << p.hash_log;
        let chain_size = if p.chain_log > 0 {
            1usize << p.chain_log
        } else {
            0
        };
        Self {
            hash_log: p.hash_log,
            chain_log: p.chain_log,
            hash_table: vec![0; hash_size],
            hash5_table: if p.dual_hash {
                vec![0; hash_size]
            } else {
                Vec::new()
            },
            chain: vec![0; chain_size],
            dual: p.dual_hash,
            window: p.window.min(MAX_OFFSET).min(total_len.max(1)),
        }
    }

    /// Index dictionary (or any prefix) so matches can reference it as history.
    fn seed_history(&mut self, data: &[u8], end: usize) {
        let end = end.min(data.len().saturating_sub(MIN_MATCH));
        // Sparse seed for large dicts (speed); denser for small dicts
        let step = if end > 64 * 1024 { 3 } else { 1 };
        let mut pos = 0usize;
        while pos < end {
            self.insert(data, pos);
            pos += step;
        }
        // Always index the last window edge for short-dict quality
        if end > 0 {
            let last = end.saturating_sub(1);
            if last % step != 0 {
                self.insert(data, last);
            }
        }
    }

    #[inline]
    fn hash4(&self, v: u32) -> usize {
        (v.wrapping_mul(0x9E37_79B1) >> (32 - self.hash_log)) as usize
    }

    #[inline]
    fn hash5(data: &[u8], pos: usize, hash_log: u32) -> usize {
        // 5-byte mix
        let v = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap())
            ^ (u32::from(data[pos + 4]) << 24);
        (v.wrapping_mul(0x85EB_CA77) >> (32 - hash_log)) as usize
    }

    #[inline]
    fn insert(&mut self, data: &[u8], pos: usize) {
        if pos + 4 > data.len() {
            return;
        }
        let h = self.hash4(read_u32(data, pos));
        let prev = self.hash_table[h];
        self.hash_table[h] = (pos as u32).wrapping_add(1);
        if self.chain_log > 0 {
            let mask = (1u32 << self.chain_log) - 1;
            self.chain[(pos as u32 & mask) as usize] = prev;
        }
        if self.dual && pos + 5 <= data.len() {
            let h5 = Self::hash5(data, pos, self.hash_log);
            self.hash5_table[h5] = (pos as u32).wrapping_add(1);
        }
    }

    /// Best match at `pos` → (offset, match_len).
    fn find(
        &self,
        data: &[u8],
        pos: usize,
        max_len: usize,
        searches: u32,
        good_enough: usize,
    ) -> Option<(usize, usize)> {
        if pos + MIN_MATCH > data.len() || max_len < MIN_MATCH {
            return None;
        }
        let v = read_u32(data, pos);
        let h = self.hash4(v);
        let mut best_len = MIN_MATCH - 1;
        let mut best_off = 0usize;
        let low = pos.saturating_sub(self.window);

        let try_cand = |cand: u32, best_len: &mut usize, best_off: &mut usize| -> bool {
            if cand == 0 {
                return false;
            }
            let cpos = (cand as usize).wrapping_sub(1);
            if cpos >= pos || cpos < low {
                return false;
            }
            let off = pos - cpos;
            if off == 0 || off > self.window {
                return false;
            }
            if read_u32(data, cpos) != v {
                return true; // continue chain
            }
            let ml = MIN_MATCH
                + simd::match_len(
                    &data[cpos + MIN_MATCH..],
                    &data[pos + MIN_MATCH..],
                    (max_len - MIN_MATCH).min(MAX_MATCH_LEN - MIN_MATCH),
                );
            if ml > *best_len {
                *best_len = ml;
                *best_off = off;
                if ml >= good_enough {
                    return false; // stop
                }
            }
            true
        };

        // Primary hash chain
        let mut cand = self.hash_table[h];
        let mut probes = 0u32;
        while cand != 0 && probes < searches {
            probes += 1;
            if !try_cand(cand, &mut best_len, &mut best_off) {
                break;
            }
            if best_len >= good_enough {
                break;
            }
            if self.chain_log > 0 {
                let mask = (1u32 << self.chain_log) - 1;
                let cpos = (cand as usize).wrapping_sub(1);
                cand = self.chain[(cpos as u32 & mask) as usize];
            } else {
                break;
            }
        }

        // Dual-hash seed (one extra head)
        if self.dual && pos + 5 <= data.len() && best_len < good_enough {
            let h5 = Self::hash5(data, pos, self.hash_log);
            let c5 = self.hash5_table[h5];
            let _ = try_cand(c5, &mut best_len, &mut best_off);
        }

        if best_len >= MIN_MATCH && best_off > 0 {
            Some((best_off, best_len))
        } else {
            None
        }
    }
}

#[inline]
fn read_u32(data: &[u8], pos: usize) -> u32 {
    u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap())
}

// ─── Wire helpers ────────────────────────────────────────────────────────────

#[inline]
fn put_varint(out: &mut Vec<u8>, mut v: u32) {
    while v >= 0x80 {
        out.push((v as u8) | 0x80);
        v >>= 7;
    }
    out.push(v as u8);
}

#[inline]
fn get_varint(src: &[u8], ip: &mut usize) -> Result<u32> {
    let mut result = 0u32;
    let mut shift = 0u32;
    loop {
        if *ip >= src.len() {
            return Err(Error::Decompression("zex: truncated varint".into()));
        }
        let b = src[*ip];
        *ip += 1;
        result |= u32::from(b & 0x7F) << shift;
        if b & 0x80 == 0 {
            return Ok(result);
        }
        shift += 7;
        if shift > 28 {
            return Err(Error::Decompression("zex: varint overflow".into()));
        }
    }
}

const FLAG_HUFF: u8 = 1;
const FLAG_OFF3: u8 = 2; // legacy: fixed 2/3-byte offsets (no repeat codes)
/// Sequences use repeat-offset codes (uvarint): 0..2 = recent, ≥3 → offset-3.
const FLAG_REP: u8 = 4;
/// lit_len / match_len / offset_code arrays are rANS/FSE packed.
const FLAG_FSE: u8 = 8;
/// Zstd-style code tables: LL/ML/OFF use base+extra-bits codes, compact FSE.
const FLAG_CODETAB: u8 = 0x10;

/// Convert real match offset → wire code using 3 recent offsets (Zstd-style).
fn encode_offset_code(offset: u32, lit_len: u32, reps: &mut [u32; 3]) -> u32 {
    // codes 0,1,2 → reps[0],reps[1],reps[2]
    if offset == reps[0] {
        return 0;
    }
    if offset == reps[1] {
        // swap into front
        reps[1] = reps[0];
        reps[0] = offset;
        return 1;
    }
    if offset == reps[2] {
        reps[2] = reps[1];
        reps[1] = reps[0];
        reps[0] = offset;
        return 2;
    }
    // new offset
    let code = offset.saturating_add(3);
    // Zstd special: when lit_len==0, rep handling differs slightly — keep simple
    let _ = lit_len;
    reps[2] = reps[1];
    reps[1] = reps[0];
    reps[0] = offset;
    code
}

/// Wire code → real offset; update rep table.
fn decode_offset_code(code: u32, lit_len: u32, reps: &mut [u32; 3]) -> Result<u32> {
    let offset = if code < 3 {
        let idx = code as usize;
        let mut off = reps[idx];
        // Zstd: if lit_len==0 and code==3-ish — we only have 0..2
        if lit_len == 0 && code == 0 {
            // force use of rep slightly shifted is overkill; keep direct
        }
        if idx != 0 {
            // rotate selected into front
            let selected = off;
            for i in (1..=idx).rev() {
                reps[i] = reps[i - 1];
            }
            reps[0] = selected;
            off = selected;
        }
        if off == 0 {
            return Err(Error::Decompression("rep offset is 0".into()));
        }
        off
    } else {
        let off = code - 3;
        if off == 0 {
            return Err(Error::Decompression("raw offset code maps to 0".into()));
        }
        reps[2] = reps[1];
        reps[1] = reps[0];
        reps[0] = off;
        off
    };
    Ok(offset)
}

/// Compress one independent block (no dictionary).
pub fn compress(src: &[u8], level: u8) -> Result<Vec<u8>> {
    let mut out = Vec::with_capacity(src.len().saturating_add(64));
    compress_into(src, &mut out, level, None)?;
    Ok(out)
}

/// Compress with optional dictionary as prefix history.
pub fn compress_with_history(src: &[u8], level: u8, dict: Option<&[u8]>) -> Result<Vec<u8>> {
    let mut out = Vec::with_capacity(src.len().saturating_add(64));
    compress_into(src, &mut out, level, dict)?;
    Ok(out)
}

/// Append compressed block to `out`.
///
/// `dict` — optional prefix history (not emitted; decoder must use the same bytes).
pub fn compress_into(
    src: &[u8],
    out: &mut Vec<u8>,
    level: u8,
    dict: Option<&[u8]>,
) -> Result<()> {
    if src.is_empty() {
        out.push(0);
        out.extend_from_slice(&0u32.to_le_bytes());
        out.extend_from_slice(&0u32.to_le_bytes());
        return Ok(());
    }

    let dict = dict.unwrap_or(&[]);
    // Cap dictionary size for window safety
    let dict = if dict.len() > MAX_OFFSET {
        &dict[dict.len() - MAX_OFFSET..]
    } else {
        dict
    };
    let dlen = dict.len();
    let p = params_for_level(level);

    // High levels: optimal parse (no dict) for better sequence choice
    let (literals, seqs) = if crate::algorithms::optimal::should_use(level) && dlen == 0 {
        crate::algorithms::optimal::parse(src)
    } else {
        greedy_parse(src, dict, &p)
    };

    emit_payload(out, level, p.entropy, &literals, &seqs)
}

/// Greedy / lazy match-finder parse (default path).
fn greedy_parse(
    src: &[u8],
    dict: &[u8],
    p: &LevelParams,
) -> (Vec<u8>, Vec<(u32, u32, u32)>) {
    use crate::algorithms::ldm::{LdmTable, LDM_MIN_MATCH};

    let dlen = dict.len();
    let mut combined = Vec::with_capacity(dlen + src.len());
    combined.extend_from_slice(dict);
    combined.extend_from_slice(src);
    let total = combined.len();
    let base = dlen;
    let end_src = total;

    let mut mf = MatchFinder::new(p, total);
    if dlen >= MIN_MATCH {
        mf.seed_history(&combined, dlen);
    }

    // LDM: active for eligible levels + block sizes.
    let use_ldm = LdmTable::should_use(
        // Recover level from params. LDM needs level ≥ 5.
        // `p` doesn't store level directly; check via entropy + searches.
        // Simpler: check window — levels ≥ 5 have window ≥ 256KB.
        if p.window >= 256 * 1024 { 5 } else { 1 },
        src.len(),
    );
    let mut ldm = if use_ldm {
        let mut t = LdmTable::new();
        t.seed(&combined, base, end_src);
        Some(t)
    } else {
        None
    };

    let mut literals = Vec::with_capacity(src.len() / 2 + 16);
    let mut seqs: Vec<(u32, u32, u32)> = Vec::new();

    let mut anchor = base;
    let mut ip = base;
    let limit = end_src.saturating_sub(MIN_MATCH + 1);
    let mut miss = 0u32;

    while ip < limit {
        // Lookup *before* inserting current pos (classic LZ order).
        let remain = end_src - ip;
        let found = mf.find(&combined, ip, remain, p.searches, p.good_enough);
        mf.insert(&combined, ip);

        let (mut off, mut mlen, mut at) = match found {
            Some((o, m)) if m >= p.min_match_accept => (o, m, ip),
            _ => {
                // Main match finder missed — try LDM as fallback.
                if let Some(ref ldm_table) = ldm {
                    if let Some((ldm_off, ldm_ml)) = ldm_table.find(&combined, ip, remain) {
                        if ldm_ml >= LDM_MIN_MATCH {
                            // Accept the LDM match.
                            let at = ip;
                            let off = ldm_off;
                            let mlen = ldm_ml.min(remain);

                            debug_assert!(at >= base && anchor >= base);
                            let lit_len = (at - anchor) as u32;
                            literals.extend_from_slice(&combined[anchor..at]);
                            seqs.push((lit_len, mlen as u32, off as u32));

                            let match_end = at + mlen;
                            // Sparse insert through match
                            let mut pcur = at + 2;
                            while pcur < match_end && pcur + 4 <= end_src {
                                mf.insert(&combined, pcur);
                                pcur += 4; // Sparse for long LDM matches
                            }

                            ip = match_end;
                            anchor = match_end;
                            miss = 0;
                            continue;
                        }
                    }
                }

                miss = miss.saturating_add(1);
                let step = if miss > 16 {
                    (1 + ((miss as usize - 16) >> p.accel.max(1) as usize)).min(32)
                } else {
                    1
                };
                ip += step;

                // Periodically insert into LDM on sampling boundaries.
                if let Some(ref mut ldm_table) = ldm {
                    if ip % 512 == 0 {
                        ldm_table.insert(&combined, ip);
                    }
                }
                continue;
            }
        };

        // Lazy matching
        if p.lazy && at + 1 < limit {
            let found2 = mf.find(&combined, at + 1, end_src - (at + 1), p.searches, p.good_enough);
            mf.insert(&combined, at + 1);
            if let Some((o2, m2)) = found2 {
                if m2 > mlen && (m2 >= mlen + 1) {
                    at += 1;
                    off = o2;
                    mlen = m2;
                } else if m2 == mlen + 1 && o2 < off {
                    at += 1;
                    off = o2;
                    mlen = m2;
                }
            }
        }

        // Do not let match extend past end of source
        if at + mlen > end_src {
            mlen = end_src - at;
        }
        if mlen < MIN_MATCH {
            ip = at + 1;
            continue;
        }

        // Gain filter: very short match with huge offset is often a loss
        if mlen == MIN_MATCH && off > 4096 {
            ip = at + 1;
            continue;
        }

        debug_assert!(at >= base && anchor >= base);
        let lit_len = (at - anchor) as u32;
        literals.extend_from_slice(&combined[anchor..at]);
        seqs.push((lit_len, mlen as u32, off as u32));

        let match_end = at + mlen;
        let insert_step = if p.accel >= 4 { 2 } else { 1 };
        let mut pcur = at + insert_step;
        while pcur < match_end && pcur + 4 <= end_src {
            mf.insert(&combined, pcur);
            pcur += insert_step;
        }

        ip = match_end;
        anchor = match_end;
        miss = 0;
    }

    if anchor < end_src {
        let lit_len = (end_src - anchor) as u32;
        literals.extend_from_slice(&combined[anchor..end_src]);
        seqs.push((lit_len, 0, 0));
    } else if seqs.is_empty() {
        literals.extend_from_slice(src);
        seqs.push((src.len() as u32, 0, 0));
    }

    (literals, seqs)
}

/// Pack literals + sequences into on-wire block payload.
fn emit_payload(
    out: &mut Vec<u8>,
    level: u8,
    entropy: bool,
    literals: &[u8],
    seqs: &[(u32, u32, u32)],
) -> Result<()> {
    let mut flags = FLAG_REP;

    let mut reps = [1u32, 4u32, 8u32];
    let mut lls = Vec::with_capacity(seqs.len());
    let mut mls = Vec::with_capacity(seqs.len());
    let mut ofs = Vec::with_capacity(seqs.len());
    for &(lit_len, match_len, offset) in seqs {
        lls.push(lit_len);
        mls.push(match_len);
        if match_len > 0 {
            let code = encode_offset_code(offset, lit_len, &mut reps);
            ofs.push(code);
        } else {
            ofs.push(0);
        }
    }

    let huff_min = if level >= 15 { 64 } else { 128 };
    let mut freq = [0u32; 256];
    for &b in literals {
        freq[b as usize] += 1;
    }
    let huff = if entropy && literals.len() >= huff_min {
        build_encoder(&freq).and_then(|enc| {
            let mut bits = 0u64;
            for (s, &f) in freq.iter().enumerate() {
                if f > 0 {
                    bits += u64::from(f) * u64::from(enc.lengths()[s]);
                }
            }
            let est = 256 + 4 + 4 + ((bits + 7) / 8) as usize;
            if est + 4 < literals.len() {
                Some(enc)
            } else {
                None
            }
        })
    } else {
        None
    };

    let lit_payload: Vec<u8> = if let Some(ref enc) = huff {
        flags |= FLAG_HUFF;
        let mut buf = Vec::with_capacity(literals.len() + 8);
        buf.extend_from_slice(&(literals.len() as u32).to_le_bytes());
        enc.write_table(&mut buf);
        let mut bw = BitWriter::with_capacity(literals.len());
        for &b in literals {
            enc.encode(&mut bw, b);
        }
        let bits = bw.finish();
        buf.extend_from_slice(&(bits.len() as u32).to_le_bytes());
        buf.extend_from_slice(&bits);
        buf
    } else {
        literals.to_vec()
    };

    // ── Try code-table encoding (levels ≥ 5, enough sequences) ────────────
    let use_codetab = seqs.len() >= 8 && level >= 5;
    let mut seq_blob = Vec::new();
    let mut used_codetab = false;

    if use_codetab {
        // Transform raw LL/ML/OFF values into code symbols + extra bits.
        let mut ll_codes: Vec<u8> = Vec::with_capacity(seqs.len());
        let mut ml_codes: Vec<u8> = Vec::with_capacity(seqs.len());
        let mut off_codes: Vec<u8> = Vec::with_capacity(seqs.len());
        let mut extra_bw = BitWriter::with_capacity(seqs.len() * 4);

        for i in 0..seqs.len() {
            let (llc, lle, lleb) = encode_ll(lls[i]);
            ll_codes.push(llc);
            if lleb > 0 {
                extra_bw.write_bits(lle, lleb as u32);
            }

            let (mlc, mle, mleb) = encode_ml(mls[i]);
            ml_codes.push(mlc);
            if mleb > 0 {
                extra_bw.write_bits(mle, mleb as u32);
            }

            if mls[i] > 0 {
                let (ofc, ofe, ofeb) = encode_off_log2(ofs[i]);
                off_codes.push(ofc);
                if ofeb > 0 {
                    extra_bw.write_bits(ofe, ofeb as u32);
                }
            } else {
                off_codes.push(0);
            }
        }

        let extra_bytes = extra_bw.finish();

        // rANS the code symbols (small alphabet → compact tables save big).
        let ll_u32: Vec<u32> = ll_codes.iter().map(|&c| c as u32).collect();
        let ml_u32: Vec<u32> = ml_codes.iter().map(|&c| c as u32).collect();
        let of_u32: Vec<u32> = off_codes.iter().map(|&c| c as u32).collect();

        let e_ll = encode_u32_array_compact(&ll_u32)?;
        let e_ml = encode_u32_array_compact(&ml_u32)?;
        let e_of = encode_u32_array_compact(&of_u32)?;
        let ct_size = e_ll.len() + e_ml.len() + e_of.len() + 4 + extra_bytes.len();

        // Compare against raw varint estimate.
        let mut raw_est = 0usize;
        for i in 0..seqs.len() {
            raw_est += 1 + (lls[i] as usize / 128) + 1 + (mls[i] as usize / 128);
            if mls[i] > 0 {
                raw_est += 1 + (ofs[i] as usize / 128);
            }
        }

        if ct_size < raw_est {
            flags |= FLAG_CODETAB | FLAG_FSE;
            seq_blob.extend_from_slice(&e_ll);
            seq_blob.extend_from_slice(&e_ml);
            seq_blob.extend_from_slice(&e_of);
            seq_blob.extend_from_slice(&(extra_bytes.len() as u32).to_le_bytes());
            seq_blob.extend_from_slice(&extra_bytes);
            used_codetab = true;
        }
    }

    // ── Fallback: legacy FSE path (levels 3–4 or when codetab didn't help) ──
    if !used_codetab {
        let use_fse = seqs.len() >= 8 && level >= 3;
        if use_fse {
            let e_ll = encode_u32_array(&lls)?;
            let e_ml = encode_u32_array(&mls)?;
            let e_of = encode_u32_array(&ofs)?;
            let fse_size = e_ll.len() + e_ml.len() + e_of.len();
            let mut raw_est = 0usize;
            for i in 0..seqs.len() {
                raw_est += 1 + (lls[i] as usize / 128) + 1 + (mls[i] as usize / 128);
                if mls[i] > 0 {
                    raw_est += 1 + (ofs[i] as usize / 128);
                }
            }
            if fse_size + 8 < raw_est.saturating_mul(2).max(raw_est + 16) && fse_size < raw_est {
                flags |= FLAG_FSE;
                seq_blob.extend_from_slice(&e_ll);
                seq_blob.extend_from_slice(&e_ml);
                seq_blob.extend_from_slice(&e_of);
            }
        }
        if flags & FLAG_FSE == 0 {
            for i in 0..seqs.len() {
                put_varint(&mut seq_blob, lls[i]);
                put_varint(&mut seq_blob, mls[i]);
                if mls[i] > 0 {
                    put_varint(&mut seq_blob, ofs[i]);
                }
            }
        }
    }

    out.push(flags);
    out.extend_from_slice(&(lit_payload.len() as u32).to_le_bytes());
    out.extend_from_slice(&(seqs.len() as u32).to_le_bytes());
    out.extend_from_slice(&lit_payload);
    out.extend_from_slice(&seq_blob);

    Ok(())
}

/// Decompress a native ZEX block (no dictionary).
pub fn decompress(src: &[u8], uncompressed_size: usize) -> Result<Vec<u8>> {
    let mut out = Vec::with_capacity(uncompressed_size);
    decompress_into(src, &mut out, uncompressed_size, None)?;
    Ok(out)
}

/// Decompress with optional dictionary history.
pub fn decompress_with_history(
    src: &[u8],
    uncompressed_size: usize,
    dict: Option<&[u8]>,
) -> Result<Vec<u8>> {
    let mut out = Vec::with_capacity(uncompressed_size);
    decompress_into(src, &mut out, uncompressed_size, dict)?;
    Ok(out)
}

/// Decompress into `dst` (cleared).
///
/// `dict` must match the compressor's dictionary (same bytes / same id at frame level).
pub fn decompress_into(
    src: &[u8],
    dst: &mut Vec<u8>,
    uncompressed_size: usize,
    dict: Option<&[u8]>,
) -> Result<()> {
    dst.clear();
    dst.reserve(uncompressed_size);

    let dict = dict.unwrap_or(&[]);
    let dict = if dict.len() > MAX_OFFSET {
        &dict[dict.len() - MAX_OFFSET..]
    } else {
        dict
    };

    if src.len() < 9 {
        return Err(Error::Decompression("zex: block too short".into()));
    }

    let mut ip = 0usize;
    let flags = src[ip];
    ip += 1;
    let lit_bytes = u32::from_le_bytes(src[ip..ip + 4].try_into().unwrap()) as usize;
    ip += 4;
    let seq_count = u32::from_le_bytes(src[ip..ip + 4].try_into().unwrap()) as usize;
    ip += 4;

    if ip.saturating_add(lit_bytes) > src.len() {
        return Err(Error::Decompression("zex: truncated literals section".into()));
    }
    if seq_count > uncompressed_size.saturating_add(1) {
        return Err(Error::Decompression("zex: seq_count absurd".into()));
    }

    check_block_sizes(src.len(), uncompressed_size)?;

    let lit_section = &src[ip..ip + lit_bytes];
    ip += lit_bytes;

    let use_rep = flags & FLAG_REP != 0;
    let use_fse = flags & FLAG_FSE != 0;
    let use_codetab = flags & FLAG_CODETAB != 0;
    let off3 = flags & FLAG_OFF3 != 0;

    // Parse sequences first when FSE (needed for lit count) — actually FSE is after lits.
    // For HUFF+REP: lit_count is prefixed. For legacy HUFF: dry-run varints.
    let literals: Vec<u8> = if flags & FLAG_HUFF != 0 {
        if use_rep {
            if lit_section.len() < 4 + 256 + 4 {
                return Err(Error::Decompression("zex: truncated huffman(rep)".into()));
            }
            let expected_lits =
                u32::from_le_bytes(lit_section[0..4].try_into().unwrap()) as usize;
            let mut lens = [0u8; 256];
            lens.copy_from_slice(&lit_section[4..260]);
            let bits_len =
                u32::from_le_bytes(lit_section[260..264].try_into().unwrap()) as usize;
            if 264 + bits_len > lit_section.len() {
                return Err(Error::Decompression("zex: truncated huffman bits".into()));
            }
            let dec = decoder_from_lengths(&lens)?;
            let mut br = BitReader::new(&lit_section[264..264 + bits_len]);
            let mut lits = Vec::with_capacity(expected_lits);
            for _ in 0..expected_lits {
                lits.push(dec.decode(&mut br)?);
            }
            lits
        } else {
            if lit_section.len() < 260 {
                return Err(Error::Decompression("zex: truncated huffman table".into()));
            }
            let mut lens = [0u8; 256];
            lens.copy_from_slice(&lit_section[..256]);
            let bits_len =
                u32::from_le_bytes(lit_section[256..260].try_into().unwrap()) as usize;
            if 260 + bits_len > lit_section.len() {
                return Err(Error::Decompression("zex: truncated huffman bits".into()));
            }
            let expected_lits = dry_run_lit_count(&src[ip..], seq_count, flags)?;
            let dec = decoder_from_lengths(&lens)?;
            let mut br = BitReader::new(&lit_section[260..260 + bits_len]);
            let mut lits = Vec::with_capacity(expected_lits);
            for _ in 0..expected_lits {
                lits.push(dec.decode(&mut br)?);
            }
            lits
        }
    } else {
        lit_section.to_vec()
    };

    // Decode sequence fields
    let (lls, mls, ofs): (Vec<u32>, Vec<u32>, Vec<u32>) = if use_codetab && use_fse {
        // ── Code-table path: compact FSE codes + extra bits bitstream ────
        let ll_codes = decode_u32_array_auto(src, &mut ip, seq_count)?;
        let ml_codes = decode_u32_array_auto(src, &mut ip, seq_count)?;
        let off_codes = decode_u32_array_auto(src, &mut ip, seq_count)?;

        // Read extra-bits bitstream
        if ip + 4 > src.len() {
            return Err(Error::Decompression("zex: codetab extra len truncated".into()));
        }
        let extra_len = u32::from_le_bytes(src[ip..ip + 4].try_into().unwrap()) as usize;
        ip += 4;
        if ip + extra_len > src.len() {
            return Err(Error::Decompression("zex: codetab extra bits truncated".into()));
        }
        let mut ebr = BitReader::new(&src[ip..ip + extra_len]);
        ip += extra_len;
        let _ = ip;

        let mut lls = Vec::with_capacity(seq_count);
        let mut mls = Vec::with_capacity(seq_count);
        let mut ofs = Vec::with_capacity(seq_count);

        for i in 0..seq_count {
            let llc = ll_codes[i] as u8;
            let lleb = if (llc as usize) < crate::utils::fse::LL_CODE_TABLE.len() {
                crate::utils::fse::LL_CODE_TABLE[llc as usize].1
            } else {
                return Err(Error::Decompression(format!("bad LL code {llc}")));
            };
            let ll_extra = if lleb > 0 {
                ebr.read_bits(lleb as u32)
                    .ok_or_else(|| Error::Decompression("codetab: LL extra bits truncated".into()))?
            } else {
                0
            };
            lls.push(decode_ll(llc, ll_extra)?);

            let mlc = ml_codes[i] as u8;
            let mleb = if (mlc as usize) < crate::utils::fse::ML_CODE_TABLE.len() {
                crate::utils::fse::ML_CODE_TABLE[mlc as usize].1
            } else {
                return Err(Error::Decompression(format!("bad ML code {mlc}")));
            };
            let ml_extra = if mleb > 0 {
                ebr.read_bits(mleb as u32)
                    .ok_or_else(|| Error::Decompression("codetab: ML extra bits truncated".into()))?
            } else {
                0
            };
            mls.push(decode_ml(mlc, ml_extra)?);

            if mls[i] > 0 {
                let ofc = off_codes[i] as u8;
                let ofeb = if ofc > 0 { (ofc - 1) as u32 } else { 0 };
                let of_extra = if ofeb > 0 {
                    ebr.read_bits(ofeb)
                        .ok_or_else(|| Error::Decompression("codetab: OFF extra bits truncated".into()))?
                } else {
                    0
                };
                ofs.push(decode_off_log2(ofc, of_extra)?);
            } else {
                ofs.push(0);
            }
        }
        (lls, mls, ofs)
    } else if use_fse {
        let lls = decode_u32_array(src, &mut ip, seq_count)?;
        let mls = decode_u32_array(src, &mut ip, seq_count)?;
        let ofs = decode_u32_array(src, &mut ip, seq_count)?;
        (lls, mls, ofs)
    } else if use_rep {
        let mut lls = Vec::with_capacity(seq_count);
        let mut mls = Vec::with_capacity(seq_count);
        let mut ofs = Vec::with_capacity(seq_count);
        for _ in 0..seq_count {
            let ll = get_varint(src, &mut ip)?;
            let ml = get_varint(src, &mut ip)?;
            lls.push(ll);
            mls.push(ml);
            if ml > 0 {
                ofs.push(get_varint(src, &mut ip)?);
            } else {
                ofs.push(0);
            }
        }
        (lls, mls, ofs)
    } else {
        // Legacy path
        let mut lls = Vec::with_capacity(seq_count);
        let mut mls = Vec::with_capacity(seq_count);
        let mut ofs = Vec::with_capacity(seq_count);
        for _ in 0..seq_count {
            let ll = get_varint(src, &mut ip)?;
            let ml = get_varint(src, &mut ip)?;
            lls.push(ll);
            mls.push(ml);
            if ml > 0 {
                let o = if off3 {
                    if ip + 3 > src.len() {
                        return Err(Error::Decompression("zex: truncated offset3".into()));
                    }
                    let o = src[ip] as u32
                        | ((src[ip + 1] as u32) << 8)
                        | ((src[ip + 2] as u32) << 16);
                    ip += 3;
                    o
                } else {
                    if ip + 2 > src.len() {
                        return Err(Error::Decompression("zex: truncated offset2".into()));
                    }
                    let o = src[ip] as u32 | ((src[ip + 1] as u32) << 8);
                    ip += 2;
                    o
                };
                ofs.push(o);
            } else {
                ofs.push(0);
            }
        }
        (lls, mls, ofs)
    };

    let mut lit_pos = 0usize;
    let mut reps = [1u32, 4u32, 8u32];

    for i in 0..seq_count {
        let lit_len = lls[i] as usize;
        let mlen = mls[i] as usize;

        if lit_pos + lit_len > literals.len() {
            return Err(Error::Decompression("zex: literal overrun".into()));
        }
        if dst.len().saturating_add(lit_len) > uncompressed_size {
            return Err(Error::Decompression("zex: output overflow (lits)".into()));
        }
        dst.extend_from_slice(&literals[lit_pos..lit_pos + lit_len]);
        lit_pos += lit_len;

        if mlen == 0 {
            continue;
        }
        if mlen > MAX_MATCH_LEN {
            return Err(Error::Decompression("zex: match too long".into()));
        }

        let offset = if use_rep {
            decode_offset_code(ofs[i], lls[i], &mut reps)? as usize
        } else {
            ofs[i] as usize
        };

        check_match_with_history(offset, mlen, dst.len(), dict.len())?;
        if dst.len().saturating_add(mlen) > uncompressed_size {
            return Err(Error::Decompression("zex: output overflow (match)".into()));
        }
        copy_match_with_history(dst, offset, mlen, dict);
    }

    if lit_pos != literals.len() {
        return Err(Error::Decompression(format!(
            "zex: unused literals {} of {}",
            literals.len() - lit_pos,
            literals.len()
        )));
    }

    if dst.len() != uncompressed_size {
        return Err(Error::SizeMismatch {
            expected: uncompressed_size as u64,
            actual: dst.len() as u64,
        });
    }
    Ok(())
}

fn dry_run_lit_count(seq_src: &[u8], seq_count: usize, flags: u8) -> Result<usize> {
    // Legacy sequences only (no FLAG_REP / FLAG_FSE)
    let mut ip = 0usize;
    let mut total = 0usize;
    let off3 = flags & FLAG_OFF3 != 0;
    for _ in 0..seq_count {
        let lit_len = get_varint(seq_src, &mut ip)? as usize;
        let mlen = get_varint(seq_src, &mut ip)? as usize;
        total = total.saturating_add(lit_len);
        if mlen > 0 {
            let step = if off3 { 3 } else { 2 };
            if ip + step > seq_src.len() {
                return Err(Error::Decompression("zex: dry-run truncated".into()));
            }
            ip += step;
        }
    }
    Ok(total)
}

/// Block compressor facade.
pub struct ZexNativeCompressor;

impl crate::algorithms::BlockCompressor for ZexNativeCompressor {
    fn compress_block(&self, src: &[u8], dst: &mut Vec<u8>, level: u8) -> Result<BlockType> {
        dst.clear();
        compress_into(src, dst, level, None)?;
        Ok(BlockType::Zex)
    }
}

/// Block decompressor facade.
pub struct ZexNativeDecompressor;

impl crate::algorithms::BlockDecompressor for ZexNativeDecompressor {
    fn decompress_block(
        &self,
        src: &[u8],
        dst: &mut Vec<u8>,
        uncompressed_size: usize,
    ) -> Result<()> {
        decompress_into(src, dst, uncompressed_size, None)
    }
}

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

    #[test]
    fn roundtrip_text() {
        let src = b"ZEX native algorithm test. ".repeat(50);
        for level in [1u8, 3, 6, 12, 19] {
            let c = compress(&src, level).unwrap();
            let d = decompress(&c, src.len()).unwrap();
            assert_eq!(d, src.as_slice(), "level {level}");
        }
    }

    #[test]
    fn roundtrip_zeros() {
        let src = vec![0u8; 8192];
        let c = compress(&src, 3).unwrap();
        assert!(c.len() < 200, "zeros should pack tiny, got {}", c.len());
        assert_eq!(decompress(&c, src.len()).unwrap(), src);
    }

    #[test]
    fn higher_level_not_worse_on_rep() {
        let src = b"ABCDEFGHIJKLMNOP ".repeat(400);
        let c3 = compress(&src, 3).unwrap();
        let c12 = compress(&src, 12).unwrap();
        // High level should be <= low level size (or close); allow small slack
        assert!(
            c12.len() <= c3.len() + 32,
            "l12={} l3={}",
            c12.len(),
            c3.len()
        );
        assert_eq!(decompress(&c12, src.len()).unwrap(), src.as_slice());
    }

    #[test]
    fn roundtrip_incompressible() {
        let mut src = Vec::with_capacity(10_000);
        let mut x = 0xC0FFEE_u32;
        for _ in 0..10_000 {
            x = x.wrapping_mul(1664525).wrapping_add(1013904223);
            src.push((x >> 24) as u8);
        }
        let c = compress(&src, 1).unwrap();
        assert_eq!(decompress(&c, src.len()).unwrap(), src);
    }

    #[test]
    fn dictionary_history_helps() {
        // Dict holds a common prefix that the message reuses immediately.
        let dict = b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n";
        let msg = b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{\"ok\":true}";

        let plain = compress(msg, 6).unwrap();
        let with_dict = compress_with_history(msg, 6, Some(dict)).unwrap();
        assert!(
            with_dict.len() < plain.len(),
            "dict should help: with={} plain={}",
            with_dict.len(),
            plain.len()
        );

        let d = decompress_with_history(&with_dict, msg.len(), Some(dict)).unwrap();
        assert_eq!(d, msg);

        // Wrong / missing dict must not silently produce wrong data (error or mismatch)
        let bad = decompress_with_history(&with_dict, msg.len(), None);
        // May error (offset into missing history) or succeed only if no dict matches used —
        // with this payload, matches into dict are expected → error.
        assert!(bad.is_err() || bad.unwrap() != msg);
    }

    #[test]
    fn dictionary_roundtrip_only_in_dict() {
        let dict = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        // Message is almost entirely covered by dict matches after first few bytes
        let msg = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCDEF";
        let c = compress_with_history(msg, 5, Some(dict)).unwrap();
        let d = decompress_with_history(&c, msg.len(), Some(dict)).unwrap();
        assert_eq!(d, msg);
    }
}