compcol 0.1.0

A no_std collection of compression algorithms behind a uniform streaming trait, gated per-algorithm by Cargo features.
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
//! Integration tests for the Brotli (RFC 7932) codec.
//!
//! This build implements only the uncompressed subset of the format:
//! the encoder emits a 1-bit WBITS header, then chunks input into
//! uncompressed meta-blocks followed by an empty-last terminator; the
//! decoder parses any combination of uncompressed and metadata
//! meta-blocks plus the empty-last terminator. Compressed meta-blocks
//! are intentionally rejected with `Error::Unsupported`.

#![cfg(feature = "brotli")]

use std::io::Write;
use std::process::{Command, Stdio};

use compcol::brotli::{Decoder, Encoder};
use compcol::{Decoder as _, Encoder as _, Error};

/// Parse a hex string into a byte vector.
fn hex(s: &str) -> Vec<u8> {
    (0..s.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
        .collect()
}

/// Encode `input` in one shot using `in_chunk`-sized input and
/// `out_chunk`-sized output buffers. Returns the full encoded stream.
fn encode_chunked(input: &[u8], in_chunk: usize, out_chunk: usize) -> Result<Vec<u8>, Error> {
    let mut enc = Encoder::new();
    let mut out = Vec::new();
    let mut buf = vec![0u8; out_chunk.max(1)];
    let mut i = 0;
    while i < input.len() {
        let end = (i + in_chunk).min(input.len());
        let chunk = &input[i..end];
        let mut consumed_total = 0;
        // Drive the encoder until either the chunk is fully consumed or
        // we make no further progress on it (output buffer full).
        loop {
            let p = enc.encode(&chunk[consumed_total..], &mut buf)?;
            out.extend_from_slice(&buf[..p.written]);
            consumed_total += p.consumed;
            if consumed_total == chunk.len() && p.written == 0 {
                break;
            }
            if p.consumed == 0 && p.written == 0 {
                break;
            }
        }
        i = end;
    }
    loop {
        let p = enc.finish(&mut buf)?;
        out.extend_from_slice(&buf[..p.written]);
        if p.done {
            break;
        }
        if p.written == 0 {
            panic!("encoder finish stalled");
        }
    }
    Ok(out)
}

/// Decode `encoded` with chunked input/output buffers.
fn decode_chunked(encoded: &[u8], in_chunk: usize, out_chunk: usize) -> Result<Vec<u8>, Error> {
    let mut dec = Decoder::new();
    let mut out = Vec::new();
    let mut buf = vec![0u8; out_chunk.max(1)];
    let mut i = 0;
    while i < encoded.len() {
        let end = (i + in_chunk).min(encoded.len());
        let chunk = &encoded[i..end];
        let mut consumed_in_chunk = 0;
        loop {
            let p = dec.decode(&chunk[consumed_in_chunk..], &mut buf)?;
            out.extend_from_slice(&buf[..p.written]);
            consumed_in_chunk += p.consumed;
            if p.consumed == 0 && p.written == 0 {
                break;
            }
        }
        i = end;
    }
    loop {
        let p = dec.finish(&mut buf)?;
        out.extend_from_slice(&buf[..p.written]);
        if p.done {
            break;
        }
        if p.written == 0 {
            panic!("decoder finish stalled");
        }
    }
    Ok(out)
}

/// Convenience: one-shot encode then decode and check we got the input
/// back. Also verifies the encoded output is at least the minimum size
/// the format demands.
fn roundtrip(input: &[u8]) {
    let encoded = encode_chunked(input, input.len().max(1), input.len().max(1) + 32).unwrap();
    let decoded = decode_chunked(&encoded, encoded.len().max(1), input.len().max(1)).unwrap();
    assert_eq!(decoded, input);
}

#[test]
fn empty_stream_round_trip() {
    roundtrip(b"");
}

#[test]
fn empty_stream_exact_bytes() {
    // WBITS=16 (1 bit = 0), ISLAST=1, ISLASTEMPTY=1, pad: bits 0,1,1
    // packed LSB-first = 0b00000110 = 0x06.
    let encoded = encode_chunked(b"", 1, 16).unwrap();
    assert_eq!(encoded, [0x06]);
}

#[test]
fn short_round_trip() {
    roundtrip(b"hello");
    roundtrip(b"a");
    roundtrip(b"hello world");
    roundtrip(b"The quick brown fox jumps over the lazy dog.");
}

#[test]
fn binary_round_trip() {
    let input: Vec<u8> = (0..=255u8).collect();
    roundtrip(&input);
}

#[test]
fn large_round_trip() {
    // Exceeds the encoder's 64 KiB per-block cap, so multiple meta-blocks
    // are emitted.
    let input: Vec<u8> = (0..200_000).map(|i| (i * 31) as u8).collect();
    roundtrip(&input);
}

#[test]
fn exact_block_boundary_round_trip() {
    // 65 536 bytes — exactly one full max-size meta-block. Then 65 537
    // — one full block plus one byte of tail.
    let input: Vec<u8> = (0..65_536).map(|i| (i % 251) as u8).collect();
    roundtrip(&input);
    let input: Vec<u8> = (0..65_537).map(|i| (i % 251) as u8).collect();
    roundtrip(&input);
    // And 2 * 65_536 — two full blocks, empty tail.
    let input: Vec<u8> = (0..131_072).map(|i| (i % 251) as u8).collect();
    roundtrip(&input);
}

#[test]
fn structured_round_trip() {
    let mut input = Vec::new();
    for _ in 0..1000 {
        input.extend_from_slice(b"the quick brown fox jumps over the lazy dog\n");
    }
    roundtrip(&input);
}

#[test]
fn pseudo_random_round_trip() {
    // Simple xorshift to avoid pulling a dep.
    let mut x: u32 = 0xdead_beef;
    let mut input = vec![0u8; 70_000];
    for slot in &mut input {
        x ^= x << 13;
        x ^= x >> 17;
        x ^= x << 5;
        *slot = x as u8;
    }
    roundtrip(&input);
}

#[test]
fn one_byte_input_one_byte_output_round_trip() {
    let input = b"hello world from brotli";
    let encoded = encode_chunked(input, 1, 1).unwrap();
    let decoded = decode_chunked(&encoded, 1, 1).unwrap();
    assert_eq!(decoded, input);
}

#[test]
fn one_byte_streaming_large_round_trip() {
    let input: Vec<u8> = (0..3000).map(|i| (i * 17 + 5) as u8).collect();
    let encoded = encode_chunked(&input, 1, 1).unwrap();
    let decoded = decode_chunked(&encoded, 1, 1).unwrap();
    assert_eq!(decoded, input);
}

#[test]
fn decode_handcrafted_hello_uncompressed() {
    // Hand-built brotli stream containing a single uncompressed meta-block
    // carrying "hello", followed by the empty-last terminator.
    //
    // Bits in emission order (LSB-first within each byte):
    //
    //   WBITS=16        : 0
    //   ISLAST=0        : 0
    //   MNIBBLES=4 nib  : 0 0
    //   MLEN-1 = 4      : 0 0 1 0   0 0 0 0   0 0 0 0   0 0 0 0   (16 bits)
    //   ISUNCOMPRESSED  : 1
    //   pad to byte     : 0 0 0      (3 zero bits)
    //   payload         : "hello"
    //   ISLAST=1        : 1
    //   ISLASTEMPTY=1   : 1
    //   pad to byte     : 0 0 0 0 0 0
    //
    // Packed byte-by-byte:
    //   byte 0: bits 0..7  = 0,0,0,0, 0,0,1,0  -> 0b01000000 = 0x40
    //   byte 1: bits 8..15 = 0,0,0,0, 0,0,0,0  -> 0x00
    //   byte 2: bits 16..23= 0,0,0,0, 1,0,0,0  -> 0b00010000 = 0x10
    //   byte 3: 'h' = 0x68
    //   byte 4: 'e' = 0x65
    //   byte 5: 'l' = 0x6c
    //   byte 6: 'l' = 0x6c
    //   byte 7: 'o' = 0x6f
    //   byte 8: 1,1,0,0,0,0,0,0 -> 0b00000011 = 0x03
    let stream = hex("40001068656c6c6f03");
    let decoded = decode_chunked(&stream, 1024, 1024).unwrap();
    assert_eq!(decoded, b"hello");
}

#[test]
fn decode_rejects_unsupported_large_window_flag() {
    // The "large window" flag uses WBITS preamble: first bit = 1, next
    // 3 bits = 0, next 3 bits = 1. Packed LSB-first as bits 1,0,0,0,1,0,0
    // -> 0b00010001 = 0x11. Decoder must reject as Unsupported.
    let stream = [0x11u8];
    let mut dec = Decoder::new();
    let mut buf = [0u8; 32];
    let err = dec.decode(&stream, &mut buf).unwrap_err();
    assert_eq!(err, Error::Unsupported);
}

#[test]
fn decode_rejects_truncated_stream() {
    // Valid prefix: just WBITS + ISLAST=0 + half of MLEN. finish() should
    // report UnexpectedEnd.
    let stream = [0x00];
    let mut dec = Decoder::new();
    let mut buf = [0u8; 32];
    let _ = dec.decode(&stream, &mut buf).unwrap();
    let err = dec.finish(&mut buf).unwrap_err();
    assert_eq!(err, Error::UnexpectedEnd);
}

#[test]
fn reset_allows_reuse() {
    let mut enc = Encoder::new();
    let mut buf = [0u8; 64];
    let p = enc.encode(b"hi", &mut buf).unwrap();
    assert_eq!(p.consumed, 2);
    enc.reset();
    let p1 = enc.encode(b"bye", &mut buf).unwrap();
    assert_eq!(p1.consumed, 3);
    let mut total = Vec::new();
    total.extend_from_slice(&buf[..p1.written]);
    loop {
        let p2 = enc.finish(&mut buf).unwrap();
        total.extend_from_slice(&buf[..p2.written]);
        if p2.done {
            break;
        }
        if p2.written == 0 {
            panic!("stalled");
        }
    }
    let decoded = decode_chunked(&total, 1024, 1024).unwrap();
    assert_eq!(decoded, b"bye");
}

// ─── cross-validation against the reference `brotli` CLI ────────────────

/// Returns Some(brotli_path) if the `brotli` binary is on PATH and
/// runs, otherwise None.
fn brotli_cli_available() -> Option<String> {
    let path = "brotli";
    let r = Command::new(path)
        .arg("--version")
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status();
    match r {
        Ok(s) if s.success() => Some(path.to_string()),
        _ => None,
    }
}

/// Pipe `data` through `brotli -d -c` and return the decoded output.
fn brotli_decode(brotli: &str, data: &[u8]) -> Vec<u8> {
    let mut child = Command::new(brotli)
        .args(["-d", "-c"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn brotli");
    child
        .stdin
        .as_mut()
        .unwrap()
        .write_all(data)
        .expect("write stdin");
    let out = child.wait_with_output().expect("wait brotli");
    assert!(
        out.status.success(),
        "brotli -d failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    out.stdout
}

/// Pipe `data` through `brotli -c` and return the encoded output.
fn brotli_encode(brotli: &str, data: &[u8]) -> Vec<u8> {
    let mut child = Command::new(brotli)
        .args(["-c"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn brotli");
    child
        .stdin
        .as_mut()
        .unwrap()
        .write_all(data)
        .expect("write stdin");
    let out = child.wait_with_output().expect("wait brotli");
    assert!(out.status.success(), "brotli encode failed");
    out.stdout
}

#[test]
fn cross_validate_with_reference_decoder() {
    let Some(brotli) = brotli_cli_available() else {
        eprintln!("skipping: brotli CLI not available");
        return;
    };
    for input in [
        b"".to_vec(),
        b"a".to_vec(),
        b"hello world".to_vec(),
        (0..=255u8).collect::<Vec<_>>(),
        (0..70_000usize).map(|i| (i * 37) as u8).collect::<Vec<_>>(),
    ] {
        let encoded = encode_chunked(&input, input.len().max(1), input.len().max(1) + 32).unwrap();
        let decoded = brotli_decode(&brotli, &encoded);
        assert_eq!(decoded, input, "reference decoder mismatch");
    }
}

#[test]
fn cross_validate_compressed_input_round_trips() {
    // The reference encoder produces a real compressed stream. Our
    // decoder should recover the original bytes.
    let Some(brotli) = brotli_cli_available() else {
        eprintln!("skipping: brotli CLI not available");
        return;
    };
    let input = b"the quick brown fox jumps over the lazy dog. this is repetitive enough that the encoder will pick compressed format.";
    let encoded = brotli_encode(&brotli, input);
    let decoded = decode_chunked(&encoded, encoded.len(), input.len()).unwrap();
    assert_eq!(decoded, input);
}

#[test]
fn cross_validate_compressed_hello_world() {
    let Some(brotli) = brotli_cli_available() else {
        eprintln!("skipping: brotli CLI not available");
        return;
    };
    let input = b"hello world\n";
    let encoded = brotli_encode(&brotli, input);
    let decoded = decode_chunked(&encoded, encoded.len(), input.len()).unwrap();
    assert_eq!(decoded, input);
}

#[test]
fn cross_validate_compressed_4k_ascii() {
    let Some(brotli) = brotli_cli_available() else {
        eprintln!("skipping: brotli CLI not available");
        return;
    };
    // 4 KiB of structured ASCII text.
    let mut input = Vec::with_capacity(4096);
    while input.len() < 4096 {
        input.extend_from_slice(b"The quick brown fox jumps over the lazy dog.\n");
    }
    input.truncate(4096);
    let encoded = brotli_encode(&brotli, &input);
    let decoded = decode_chunked(&encoded, encoded.len(), input.len()).unwrap();
    assert_eq!(decoded, input);
}

#[test]
fn cross_validate_compressed_16k_lorem() {
    let Some(brotli) = brotli_cli_available() else {
        eprintln!("skipping: brotli CLI not available");
        return;
    };
    let lorem: &[u8] = b"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ";
    let mut input = Vec::with_capacity(16 * 1024);
    while input.len() < 16 * 1024 {
        input.extend_from_slice(lorem);
    }
    input.truncate(16 * 1024);
    let encoded = brotli_encode(&brotli, &input);
    let decoded = decode_chunked(&encoded, encoded.len(), input.len()).unwrap();
    assert_eq!(decoded, input);
}

#[test]
fn cross_validate_compressed_dictionary_phrase() {
    // "the time has come" — the words "the", "time", "has", "come" all
    // exist verbatim in the static dictionary (length 4). This exercises
    // the static-dictionary back-reference path.
    let Some(brotli) = brotli_cli_available() else {
        eprintln!("skipping: brotli CLI not available");
        return;
    };
    let input = b"the time has come";
    let encoded = brotli_encode(&brotli, input);
    eprintln!(
        "encoded: {} bytes: {:?}",
        encoded.len(),
        encoded
            .iter()
            .map(|b| format!("{:02x}", b))
            .collect::<Vec<_>>()
            .join("")
    );
    let decoded = decode_chunked(&encoded, encoded.len(), input.len() + 32).unwrap();
    assert_eq!(decoded, input);
}

#[test]
fn cross_validate_compressed_empty() {
    let Some(brotli) = brotli_cli_available() else {
        eprintln!("skipping: brotli CLI not available");
        return;
    };
    let input: &[u8] = b"";
    let encoded = brotli_encode(&brotli, input);
    let decoded = decode_chunked(&encoded, encoded.len().max(1), 16).unwrap();
    assert_eq!(decoded, input);
}

/// Helper: decode one shot, no chunking, returns the bytes.
fn decode_one_shot(stream: &[u8]) -> Vec<u8> {
    let mut dec = Decoder::new();
    let mut out = vec![0u8; stream.len() * 16 + 4096];
    let p = dec.decode(stream, &mut out).expect("decode");
    out.truncate(p.written);
    out
}

/// Bench of hand-picked reference streams generated with the brotli
/// CLI at default settings. Verifies the decoder copes with the full
/// range of features exercised by realistic input — complex prefix
/// codes, dictionary references with transforms, ring-buffer reuse,
/// and back-references. Doesn't depend on the brotli CLI being
/// available at test time.
#[test]
fn decode_fixed_reference_streams() {
    // Each entry: (hex stream, expected decoded bytes).
    let cases: &[(&str, &[u8])] = &[
        // Eight 'a's, compressed (uses NSYM=1 literal+IC+dist trees).
        ("1f0700f825c242840000", b"aaaaaaaa"),
        // 14 'a's, also NSYM=1.
        ("1f0d00f825c2e2850000", b"aaaaaaaaaaaaaa"),
        // 40 'a's — block of repeated literals via back-refs.
        (
            "1f2700f825c2a28c00c0",
            b"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        ),
        // Phrase whose words "the", "time", "has", "come" all live in
        // the static dictionary — exercises the dictionary path with
        // transforms applied.
        (
            "1f1000f8a541c2d0e69428c0d429203d343906",
            b"the time has come",
        ),
        // Short phrase mixing literal and dict references.
        ("1f0d00f825004a9042ea16999e2200", b"this is a test"),
        // 43 chars: complex prefix codes for literal/IC trees + dict.
        (
            "1f2a00889c09364ea87737bc2433a34b9033bc427b4b90b23998c881435ba0f7dea7150ee90b4789ea0c1be0563506",
            b"the quick brown fox jumps over the lazy dog",
        ),
        // 75 chars including punctuation; exercises both back-refs and
        // dict references.
        (
            "1f4a00a014a1d2d56da92ea4c77e70ea41b8e8101536e080bd05f617fd00b5e7947aa93a819311a5e685e00dc00fff0f259bd5b15d9c5428ceec103d",
            b"the quick brown fox jumps over the lazy dog. this is repetitive enough that",
        ),
        // 116 chars: complete sentence with many dict references and
        // back-refs. This case exercises the "static-dict reference
        // does not push to the ring buffer" rule.
        (
            "1f7300e045b779bd3b2ecf3f68a550182651e9e40ecc7fd4965cf212ce2df084052db0c8db379508510f9ae617e0bd617b47f90fd5bbdcc4bee0625ada219e1c75aa68e600388b1d6a0eb3004b01",
            b"the quick brown fox jumps over the lazy dog. this is repetitive enough that the encoder will pick compressed format.",
        ),
    ];
    for (hex_s, expected) in cases {
        let stream = hex(hex_s);
        let got = decode_one_shot(&stream);
        assert_eq!(
            got,
            *expected,
            "mismatch for stream {hex_s}: got {:?}",
            String::from_utf8_lossy(&got)
        );
    }
}

// ─── compressed-encoder coverage ────────────────────────────────────────

/// Generate a 16 KiB Lorem ipsum sample.
fn lorem_16k() -> Vec<u8> {
    let lorem: &[u8] = b"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ";
    let mut input = Vec::with_capacity(16 * 1024);
    while input.len() < 16 * 1024 {
        input.extend_from_slice(lorem);
    }
    input.truncate(16 * 1024);
    input
}

/// Verify our encoder's output decodes correctly through our own
/// decoder for the four "shape" inputs from the task description.
#[test]
fn compressed_encoder_internal_round_trip_shapes() {
    let cases: &[(&str, Vec<u8>)] = &[
        ("empty", Vec::new()),
        ("single byte", b"a".to_vec()),
        ("hello world", b"hello world\n".to_vec()),
        ("4k lorem", {
            let mut v = Vec::with_capacity(4096);
            while v.len() < 4096 {
                v.extend_from_slice(b"The quick brown fox jumps over the lazy dog.\n");
            }
            v.truncate(4096);
            v
        }),
        ("16k lorem", lorem_16k()),
    ];
    for (name, input) in cases {
        let encoded = encode_chunked(input, input.len().max(1), input.len().max(1) + 64).unwrap();
        let decoded =
            decode_chunked(&encoded, encoded.len().max(1), input.len().max(1) + 64).unwrap();
        assert_eq!(decoded, *input, "internal round-trip failed for {name}");
    }
}

/// Streaming round-trip with 1-byte-on-both-sides buffers. The encoder
/// must flush meta-blocks as input arrives, and the decoder must
/// stream output back one byte at a time.
#[test]
fn compressed_encoder_streaming_one_byte() {
    let cases: &[(&str, Vec<u8>)] = &[
        ("hello world", b"hello world\n".to_vec()),
        ("alphabet", (0..=255u8).collect()),
        ("structured", {
            let mut v = Vec::new();
            for _ in 0..100 {
                v.extend_from_slice(b"the quick brown fox jumps over the lazy dog\n");
            }
            v
        }),
    ];
    for (name, input) in cases {
        let encoded = encode_chunked(input, 1, 1).unwrap();
        let decoded = decode_chunked(&encoded, 1, 1).unwrap();
        assert_eq!(decoded, *input, "streaming round-trip failed for {name}");
    }
}

/// Cross-validate our compressed-encoder output against the reference
/// `brotli -d` CLI. Skipped when the CLI is unavailable.
#[cfg(unix)]
#[test]
fn compressed_encoder_cross_validate_reference() {
    let Some(brotli) = brotli_cli_available() else {
        eprintln!("skipping: brotli CLI not available");
        return;
    };
    let cases: &[(&str, Vec<u8>)] = &[
        ("empty", Vec::new()),
        ("single byte", b"a".to_vec()),
        ("hello world", b"hello world\n".to_vec()),
        ("4k lorem", {
            let mut v = Vec::with_capacity(4096);
            while v.len() < 4096 {
                v.extend_from_slice(b"The quick brown fox jumps over the lazy dog.\n");
            }
            v.truncate(4096);
            v
        }),
        ("16k lorem", lorem_16k()),
        ("binary 0..255", (0..=255u8).collect()),
        ("pseudo random 70k", {
            let mut x: u32 = 0xdead_beef;
            let mut v = vec![0u8; 70_000];
            for slot in &mut v {
                x ^= x << 13;
                x ^= x >> 17;
                x ^= x << 5;
                *slot = x as u8;
            }
            v
        }),
    ];
    for (name, input) in cases {
        let encoded = encode_chunked(input, input.len().max(1), input.len().max(1) + 64).unwrap();
        let decoded = brotli_decode(&brotli, &encoded);
        assert_eq!(
            decoded, *input,
            "system brotli -d returned the wrong bytes for {name}"
        );
    }
}

/// Verify a stream that spans multiple compressed meta-blocks (one
/// non-final block followed by the final). 200 000 bytes of repeated
/// text exceeds the encoder's 64 KiB per-block cap.
#[test]
fn compressed_encoder_multi_block_round_trip() {
    let mut input = Vec::with_capacity(200_000);
    while input.len() < 200_000 {
        input.extend_from_slice(
            b"The quick brown fox jumps over the lazy dog. Pack my box with five dozen liquor jugs. ",
        );
    }
    input.truncate(200_000);
    let encoded = encode_chunked(&input, input.len(), input.len() + 64).unwrap();
    let decoded = decode_chunked(&encoded, encoded.len(), input.len() + 64).unwrap();
    assert_eq!(decoded, input);
    // Also cross-check via the reference decoder.
    if let Some(brotli) = brotli_cli_available() {
        let ref_decoded = brotli_decode(&brotli, &encoded);
        assert_eq!(ref_decoded, input);
    }
}

/// Edge cases that exercise the encoder's degenerate-tree paths
/// (NSYM=1 / NSYM=2 simple prefix codes vs the complex code path).
#[test]
fn compressed_encoder_degenerate_alphabets() {
    let cases: &[(&str, Vec<u8>)] = &[
        // Single distinct literal — literal tree degenerates to NSYM=1.
        ("all zeros 4k", vec![0u8; 4096]),
        ("all 0xff 16k", vec![0xffu8; 16384]),
        ("repeating 'a' 1k", vec![b'a'; 1024]),
        // Two distinct literals.
        ("ab × 500", b"ab".repeat(500)),
        (
            "0 / 1 alternating",
            (0..2048).map(|i| (i & 1) as u8).collect(),
        ),
        // Three distinct literals.
        ("abc × 300", b"abc".repeat(300)),
    ];
    for (name, input) in cases {
        let encoded = encode_chunked(input, input.len(), input.len() + 64).unwrap();
        let decoded = decode_chunked(&encoded, encoded.len(), input.len() + 64).unwrap();
        assert_eq!(decoded, *input, "internal round-trip failed for {name}");
        if let Some(brotli) = brotli_cli_available() {
            let ref_decoded = brotli_decode(&brotli, &encoded);
            assert_eq!(ref_decoded, *input, "reference decoder failed for {name}");
        }
    }
}

/// Mixed structured + binary inputs that exercise both real LZ77
/// match-finding and the literal path.
#[test]
fn compressed_encoder_mixed_inputs() {
    let cases: &[(&str, Vec<u8>)] = &[
        // Highly repetitive text.
        ("repetitive sentence", b"This is a test. ".repeat(500)),
        // A "file-like" mix.
        (
            "html-ish",
            b"<html><head><title>x</title></head><body>".repeat(200),
        ),
        // Mix of structure and noise.
        ("alpha + count", {
            let mut v = Vec::new();
            for i in 0..2000 {
                v.extend_from_slice(format!("line {i}: hello world\n").as_bytes());
            }
            v
        }),
        // Zero-prefixed binary.
        ("zeros + pattern", {
            let mut v = vec![0u8; 1024];
            v.extend_from_slice(b"the quick brown fox");
            v.extend_from_slice(&vec![0u8; 1024]);
            v
        }),
    ];
    for (name, input) in cases {
        let encoded = encode_chunked(input, input.len(), input.len() + 64).unwrap();
        let decoded = decode_chunked(&encoded, encoded.len(), input.len() + 64).unwrap();
        assert_eq!(decoded, *input, "internal round-trip failed for {name}");
        if let Some(brotli) = brotli_cli_available() {
            let ref_decoded = brotli_decode(&brotli, &encoded);
            assert_eq!(ref_decoded, *input, "ref decode failed for {name}");
        }
    }
}

/// Fuzz: random inputs at varying lengths, all of which must
/// internally round-trip and (when the CLI is available) decode
/// correctly through the reference `brotli -d`.
#[test]
fn compressed_encoder_fuzz_round_trip() {
    let mut state: u64 = 0x1234_5678_9abc_def0;
    let brotli = brotli_cli_available();
    for round in 0..80 {
        // Pick a length in [0, 8192].
        state = state
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        let len = ((state >> 33) as usize) & 0x1FFF;
        let mut input = vec![0u8; len];
        for slot in input.iter_mut() {
            state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            *slot = ((state >> 32) & 0xFF) as u8;
        }
        let encoded = encode_chunked(&input, len.max(1), len.max(1) + 64).unwrap();
        let decoded = decode_chunked(&encoded, encoded.len().max(1), len.max(1) + 64).unwrap();
        assert_eq!(
            decoded, input,
            "internal round-trip failed at round {round}"
        );
        if let Some(ref bin) = brotli {
            let ref_decoded = brotli_decode(bin, &encoded);
            assert_eq!(ref_decoded, input, "ref decode failed at round {round}");
        }
    }
}

/// Sanity: report our encoder's compression ratio on a few inputs.
/// Not a strict assertion — only checks we don't catastrophically
/// expand structured text. The floor+walls tier should at least beat
/// "uncompressed" for non-trivial repetitive input.
#[test]
fn compressed_encoder_ratio_sanity() {
    let lorem = lorem_16k();
    let encoded = encode_chunked(&lorem, lorem.len(), lorem.len() + 64).unwrap();
    eprintln!(
        "compcol-brotli 16k lorem: {}{} bytes ({:.1}%)",
        lorem.len(),
        encoded.len(),
        100.0 * encoded.len() as f64 / lorem.len() as f64
    );
    // Lorem ipsum repeats every 446 bytes; back-references should
    // compress it considerably below the input size.
    assert!(
        encoded.len() < lorem.len(),
        "encoder expanded structured text: {} ≥ {}",
        encoded.len(),
        lorem.len()
    );
    // Report on a few other shapes too.
    let cases: &[(&str, Vec<u8>)] = &[
        ("all zeros 16k", vec![0u8; 16384]),
        ("repetitive sentence 8k", b"This is a test. ".repeat(500)),
        ("alphabet ×64", (0..=255u8).collect::<Vec<_>>().repeat(64)),
    ];
    for (name, input) in cases {
        let encoded = encode_chunked(input, input.len(), input.len() + 64).unwrap();
        eprintln!(
            "compcol-brotli {}: {}{} bytes ({:.1}%)",
            name,
            input.len(),
            encoded.len(),
            100.0 * encoded.len() as f64 / input.len() as f64
        );
    }
}