euv-docs 0.48.1

Cross-platform documentation viewer and static site generator powered by euv and euv-ui.
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
use super::*;

/// Encodes an unsigned 64-bit integer using unsigned LEB128 varint encoding.
///
/// # Arguments
///
/// - `&mut Vec<u8>` - Destination byte vector.
/// - `u64` - Integer value to encode.
fn write_varint(out: &mut Vec<u8>, mut value: u64) {
    loop {
        let mut byte: u8 = (value as u8) & CODEC_VARINT_PAYLOAD_MASK;
        value >>= 7;
        if value != 0 {
            byte |= CODEC_VARINT_CONTINUE;
        }
        out.push(byte);
        if value == 0 {
            break;
        }
    }
}

/// Decodes an unsigned LEB128 varint from `input` starting at `*pos`.
///
/// # Arguments
///
/// - `&[u8]` - Source byte slice.
/// - `&mut usize` - Read cursor advanced past the decoded varint.
///
/// # Returns
///
/// - `Result<u64, DocsCodecError>` - Decoded integer or truncation error.
fn read_varint(input: &[u8], pos: &mut usize) -> Result<u64, DocsCodecError> {
    let mut result: u64 = 0;
    let mut shift: u32 = 0;
    loop {
        if *pos >= input.len() || shift > CODEC_VARINT_MAX_SHIFT {
            return Err(DocsCodecError::Truncated);
        }
        let byte: u8 = input[*pos];
        *pos += 1;
        let payload: u64 = (byte & CODEC_VARINT_PAYLOAD_MASK) as u64;
        result |= payload
            .checked_shl(shift)
            .ok_or(DocsCodecError::Truncated)?;
        if (byte & CODEC_VARINT_CONTINUE) == 0 {
            return Ok(result);
        }
        shift += 7;
    }
}

/// Reverses the lowest `bit_len` bits of `code` for LSB-first canonical Huffman streaming.
///
/// # Arguments
///
/// - `u32` - MSB-first canonical Huffman code.
/// - `u32` - Bit length in `1..=CODEC_MAX_CODE_BITS`.
///
/// # Returns
///
/// - `u32` - Bit-reversed code ready for LSB-first emission.
fn reverse_bits(code: u32, bit_len: u32) -> u32 {
    if bit_len == 0 {
        return 0;
    }
    code.reverse_bits() >> (32 - bit_len)
}

/// Maps a match length in `3..=258` to its length code index, extra bit value, and extra bit count.
///
/// # Arguments
///
/// - `usize` - Match length in bytes.
///
/// # Returns
///
/// - `(usize, u32, u32)` - Tuple of `(length_code_index, extra_bits_value, extra_bits_count)`.
fn length_to_code(length: usize) -> (usize, u32, u32) {
    let idx: usize = CODEC_LEN_BASE
        .partition_point(|base: &u16| (*base as usize) <= length)
        .saturating_sub(1);
    let extra_val: u32 = (length - (CODEC_LEN_BASE[idx] as usize)) as u32;
    let extra_bits: u32 = CODEC_LEN_EXTRA[idx] as u32;
    (idx, extra_val, extra_bits)
}

/// Maps a back-reference distance in `1..=CODEC_WINDOW_SIZE` to its distance code index and extra bits.
///
/// # Arguments
///
/// - `usize` - Match distance in bytes.
///
/// # Returns
///
/// - `(usize, u32, u32)` - Tuple of `(dist_code_index, extra_bits_value, extra_bits_count)`.
fn distance_to_code(distance: usize) -> (usize, u32, u32) {
    let idx: usize = CODEC_DIST_BASE
        .partition_point(|base: &u32| (*base as usize) <= distance)
        .saturating_sub(1);
    let extra_val: u32 = (distance - (CODEC_DIST_BASE[idx] as usize)) as u32;
    let extra_bits: u32 = CODEC_DIST_EXTRA[idx] as u32;
    (idx, extra_val, extra_bits)
}

/// Computes length-limited canonical Huffman code lengths (`<= max_bits`) from symbol frequencies.
///
/// # Arguments
///
/// - `&[u32]` - Non-negative frequency table indexed by symbol id.
/// - `u32` - Maximum permitted code length in bits.
///
/// # Returns
///
/// - `Vec<u8>` - Code length per symbol (`0` for symbols with frequency `0`).
fn build_code_lengths(freqs: &[u32], max_bits: u32) -> Vec<u8> {
    let sym_count: usize = freqs.len();
    let mut lens: Vec<u8> = vec![0u8; sym_count];
    let mut active: Vec<usize> = Vec::new();
    for (sym, &freq) in freqs.iter().enumerate() {
        if freq > 0 {
            active.push(sym);
        }
    }
    if active.is_empty() {
        return lens;
    }
    if active.len() == 1 {
        lens[active[0]] = 1;
        return lens;
    }
    let mut heap: BinaryHeap<Reverse<(u64, usize)>> = BinaryHeap::with_capacity(active.len());
    let mut parent: Vec<usize> = vec![usize::MAX; sym_count * 2];
    for &sym in active.iter() {
        heap.push(Reverse((freqs[sym] as u64, sym)));
    }
    let mut next_node: usize = sym_count;
    while heap.len() > 1 {
        let Some(Reverse((w1, n1))) = heap.pop() else {
            break;
        };
        let Some(Reverse((w2, n2))) = heap.pop() else {
            break;
        };
        let merged: usize = next_node;
        next_node += 1;
        if merged >= parent.len() {
            parent.resize(merged + 1, usize::MAX);
        }
        parent[n1] = merged;
        parent[n2] = merged;
        heap.push(Reverse((w1.saturating_add(w2), merged)));
    }
    let max_bits_u8: u8 = max_bits as u8;
    let mut kraft: u64 = 0;
    let limit: u64 = 1u64 << max_bits;
    for &sym in active.iter() {
        let mut depth: u32 = 0;
        let mut cur: usize = sym;
        while parent[cur] != usize::MAX {
            depth += 1;
            cur = parent[cur];
        }
        let clamped: u8 = depth.clamp(1, max_bits) as u8;
        lens[sym] = clamped;
        kraft += 1u64 << (max_bits - (clamped as u32));
    }
    while kraft > limit {
        let mut candidate: Option<usize> = None;
        for &sym in active.iter() {
            let cur_len: u8 = lens[sym];
            if cur_len < max_bits_u8 {
                let replace: bool = match candidate {
                    None => true,
                    Some(prev) => {
                        cur_len > lens[prev] || (cur_len == lens[prev] && freqs[sym] < freqs[prev])
                    }
                };
                if replace {
                    candidate = Some(sym);
                }
            }
        }
        let Some(sym) = candidate else {
            break;
        };
        lens[sym] += 1;
        kraft -= 1u64 << (max_bits - (lens[sym] as u32));
    }
    while kraft < limit {
        let mut candidate: Option<usize> = None;
        for &sym in active.iter() {
            let cur_len: u8 = lens[sym];
            if cur_len > 1 {
                let delta: u64 = 1u64 << (max_bits - (cur_len as u32));
                if kraft + delta <= limit {
                    let replace: bool = match candidate {
                        None => true,
                        Some(prev) => freqs[sym] > freqs[prev],
                    };
                    if replace {
                        candidate = Some(sym);
                    }
                }
            }
        }
        let Some(sym) = candidate else {
            break;
        };
        let delta: u64 = 1u64 << (max_bits - (lens[sym] as u32));
        lens[sym] -= 1;
        kraft += delta;
    }
    lens
}

/// Derives LSB-first canonical Huffman codes from per-symbol bit lengths.
///
/// # Arguments
///
/// - `&[u8]` - Code length per symbol (`0..=CODEC_MAX_CODE_BITS`).
///
/// # Returns
///
/// - `Result<Vec<u32>, DocsCodecError>` - Bit-reversed canonical code per symbol, or an error if over-subscribed.
fn build_canonical_codes(lens: &[u8]) -> Result<Vec<u32>, DocsCodecError> {
    let mut bl_count: [u32; 16] = [0u32; 16];
    let mut kraft: u32 = 0;
    let limit: u32 = 1u32 << CODEC_MAX_CODE_BITS;
    for &len_u8 in lens.iter() {
        let len: usize = len_u8 as usize;
        if len > CODEC_MAX_CODE_BITS as usize {
            return Err(DocsCodecError::InvalidCodeLengths);
        }
        if len > 0 {
            bl_count[len] += 1;
            kraft = kraft.saturating_add(1u32 << (CODEC_MAX_CODE_BITS - (len as u32)));
        }
    }
    if kraft == 0 || kraft > limit {
        return Err(DocsCodecError::InvalidCodeLengths);
    }
    let mut next_code: [u32; 16] = [0u32; 16];
    let mut code: u32 = 0;
    for bits in 1..=(CODEC_MAX_CODE_BITS as usize) {
        code = (code + bl_count[bits - 1]) << 1;
        next_code[bits] = code;
    }
    let mut codes: Vec<u32> = vec![0u32; lens.len()];
    for (sym, &len_u8) in lens.iter().enumerate() {
        if len_u8 > 0 {
            let len_idx: usize = len_u8 as usize;
            let raw: u32 = next_code[len_idx];
            next_code[len_idx] += 1;
            codes[sym] = reverse_bits(raw, len_u8 as u32);
        }
    }
    Ok(codes)
}

/// Builds a flat `2^15`-entry O(1) lookup table for canonical Huffman decoding.
///
/// # Arguments
///
/// - `&[u8]` - Code length per symbol (`0..=CODEC_MAX_CODE_BITS`).
///
/// # Returns
///
/// - `Result<Vec<u16>, DocsCodecError>` - Packed lookup table where each entry encodes `(symbol << 4) | bit_len`.
fn build_decode_table(lens: &[u8]) -> Result<Vec<u16>, DocsCodecError> {
    let codes: Vec<u32> = build_canonical_codes(lens)?;
    let mut table: Vec<u16> = vec![0u16; CODEC_TABLE_SIZE];
    for (sym, &len_u8) in lens.iter().enumerate() {
        if len_u8 > 0 {
            let step: usize = 1usize << (len_u8 as u32);
            let entry: u16 = ((sym as u16) << CODEC_TABLE_LEN_BITS) | (len_u8 as u16);
            let mut idx: usize = codes[sym] as usize;
            while idx < CODEC_TABLE_SIZE {
                table[idx] = entry;
                idx += step;
            }
        }
    }
    Ok(table)
}

/// Computes a 3-byte multiplicative hash index for the LZ77 hash chain.
///
/// # Arguments
///
/// - `&[u8]` - Input byte slice.
/// - `usize` - Starting index (must have at least 3 bytes remaining).
///
/// # Returns
///
/// - `usize` - Hash bucket index in `0..(1 << CODEC_HASH_BITS)`.
fn hash3(data: &[u8], pos: usize) -> usize {
    let packed: u32 =
        (data[pos] as u32) | ((data[pos + 1] as u32) << 8) | ((data[pos + 2] as u32) << 16);
    ((packed.wrapping_mul(CODEC_HASH_MULTIPLIER)) >> (32 - CODEC_HASH_BITS)) as usize
}

/// Searches the hash chain at `pos` for the longest back-reference within `CODEC_WINDOW_SIZE`.
///
/// # Arguments
///
/// - `&[u8]` - Input byte slice.
/// - `usize` - Current input position.
/// - `u32` - Head position recorded for `hash3(data, pos)`.
/// - `&[u32]` - Ring-buffered chain pointers indexed by `pos & (CODEC_WINDOW_SIZE - 1)`.
///
/// # Returns
///
/// - `(usize, usize)` - Best `(length, distance)` pair, or `(0, 0)` when no `>= 3`-byte match exists.
fn find_best_match(data: &[u8], pos: usize, head_pos: u32, prev: &[u32]) -> (usize, usize) {
    let max_len: usize = (data.len() - pos).min(CODEC_MAX_MATCH);
    if max_len < CODEC_MIN_MATCH {
        return (0, 0);
    }
    let window_mask: usize = CODEC_WINDOW_SIZE - 1;
    let mut best_len: usize = CODEC_MIN_MATCH - 1;
    let mut best_dist: usize = 0;
    let mut cur: u32 = head_pos;
    let mut steps: usize = 0;
    while cur != CODEC_HASH_EMPTY && steps < CODEC_MAX_CHAIN {
        let cur_idx: usize = cur as usize;
        if cur_idx >= pos {
            break;
        }
        let dist: usize = pos - cur_idx;
        if dist > CODEC_WINDOW_SIZE {
            break;
        }
        if data[cur_idx + best_len] == data[pos + best_len] && data[cur_idx] == data[pos] {
            let mut matched: usize = 0;
            while matched < max_len && data[cur_idx + matched] == data[pos + matched] {
                matched += 1;
            }
            if matched > best_len {
                best_len = matched;
                best_dist = dist;
                if best_len >= CODEC_NICE_MATCH || best_len == max_len {
                    break;
                }
            }
        }
        let next: u32 = prev[cur_idx & window_mask];
        if next >= cur {
            break;
        }
        cur = next;
        steps += 1;
    }
    if best_len >= CODEC_MIN_MATCH {
        (best_len, best_dist)
    } else {
        (0, 0)
    }
}

/// Tokenizes `data` into packed LZ77 literal and match tokens using a 1 MiB lazy-matching window.
///
/// # Arguments
///
/// - `&[u8]` - Uncompressed input byte slice.
///
/// # Returns
///
/// - `Vec<u32>` - Packed token stream (literals `< 256`; matches flagged with `CODEC_MATCH_FLAG`).
fn lz77_tokenize(data: &[u8]) -> Vec<u32> {
    let table_len: usize = 1usize << CODEC_HASH_BITS;
    let mut head: Vec<u32> = vec![CODEC_HASH_EMPTY; table_len];
    let mut prev: Vec<u32> = vec![CODEC_HASH_EMPTY; CODEC_WINDOW_SIZE];
    let window_mask: usize = CODEC_WINDOW_SIZE - 1;
    let mut tokens: Vec<u32> = Vec::with_capacity(data.len() / 2);
    let mut pos: usize = 0;
    while pos < data.len() {
        if pos + CODEC_MIN_MATCH > data.len() {
            tokens.push(data[pos] as u32);
            pos += 1;
            continue;
        }
        let h: usize = hash3(data, pos);
        let prev_head: u32 = head[h];
        prev[pos & window_mask] = prev_head;
        head[h] = pos as u32;
        let (mut best_len, mut best_dist): (usize, usize) =
            find_best_match(data, pos, prev_head, &prev);
        if (CODEC_MIN_MATCH..CODEC_LAZY_LIMIT).contains(&best_len)
            && pos + 1 + CODEC_MIN_MATCH <= data.len()
        {
            let next_pos: usize = pos + 1;
            let h2: usize = hash3(data, next_pos);
            let prev_head2: u32 = head[h2];
            prev[next_pos & window_mask] = prev_head2;
            head[h2] = next_pos as u32;
            let (next_len, next_dist): (usize, usize) =
                find_best_match(data, next_pos, prev_head2, &prev);
            if next_len > best_len + 1 {
                tokens.push(data[pos] as u32);
                pos = next_pos;
                best_len = next_len;
                best_dist = next_dist;
            }
        }
        if best_len >= CODEC_MIN_MATCH {
            let packed: u32 = CODEC_MATCH_FLAG
                | (((best_len - CODEC_MIN_MATCH) as u32) << CODEC_MATCH_LEN_SHIFT)
                | ((best_dist - 1) as u32);
            tokens.push(packed);
            let end: usize = pos + best_len;
            let mut cur: usize = pos + 1;
            while cur < end && cur + CODEC_MIN_MATCH <= data.len() {
                let hc: usize = hash3(data, cur);
                let prev_c: u32 = head[hc];
                if prev_c != cur as u32 {
                    prev[cur & window_mask] = prev_c;
                    head[hc] = cur as u32;
                }
                cur += 1;
            }
            pos = end;
        } else {
            tokens.push(data[pos] as u32);
            pos += 1;
        }
    }
    tokens
}

/// Encodes one token chunk as a dynamic Canonical Huffman block into `writer`.
///
/// # Arguments
///
/// - `&mut CodecBitWriter` - Active bit writer.
/// - `&[u32]` - Token chunk for this block.
/// - `bool` - Whether this block is the final block in the stream.
fn encode_huffman_block(writer: &mut CodecBitWriter, chunk: &[u32], is_final: bool) {
    let mut lit_freqs: [u32; CODEC_LITLEN_SYMBOLS] = [0u32; CODEC_LITLEN_SYMBOLS];
    let mut dist_freqs: [u32; CODEC_DIST_SYMBOLS] = [0u32; CODEC_DIST_SYMBOLS];
    let mut has_matches: bool = false;
    for &tok in chunk.iter() {
        if (tok & CODEC_MATCH_FLAG) == 0 {
            lit_freqs[tok as usize] += 1;
        } else {
            has_matches = true;
            let length: usize = (((tok >> CODEC_MATCH_LEN_SHIFT) & CODEC_MATCH_LEN_MASK) as usize)
                + CODEC_MIN_MATCH;
            let distance: usize = ((tok & CODEC_MATCH_DIST_MASK) as usize) + 1;
            let (lcode, _, _): (usize, u32, u32) = length_to_code(length);
            let (dcode, _, _): (usize, u32, u32) = distance_to_code(distance);
            lit_freqs[CODEC_LENGTH_SYMBOL_BASE + lcode] += 1;
            dist_freqs[dcode] += 1;
        }
    }
    lit_freqs[CODEC_END_OF_BLOCK] = 1;
    let lit_lens: Vec<u8> = build_code_lengths(&lit_freqs, CODEC_MAX_CODE_BITS);
    let lit_codes: Vec<u32> = build_canonical_codes(&lit_lens).unwrap_or_default();
    let dist_lens: Vec<u8> = if has_matches {
        build_code_lengths(&dist_freqs, CODEC_MAX_CODE_BITS)
    } else {
        Vec::new()
    };
    let dist_codes: Vec<u32> = if has_matches {
        build_canonical_codes(&dist_lens).unwrap_or_default()
    } else {
        Vec::new()
    };
    writer.write_bits(u64::from(is_final), 1);
    writer.write_bits(u64::from(has_matches), 1);
    for &len_u8 in lit_lens.iter() {
        writer.write_bits(len_u8 as u64, CODEC_CODE_LEN_FIELD_BITS);
    }
    if has_matches {
        for &len_u8 in dist_lens.iter() {
            writer.write_bits(len_u8 as u64, CODEC_CODE_LEN_FIELD_BITS);
        }
    }
    for &tok in chunk.iter() {
        if (tok & CODEC_MATCH_FLAG) == 0 {
            let sym: usize = tok as usize;
            writer.write_bits(lit_codes[sym] as u64, lit_lens[sym] as u32);
        } else {
            let length: usize = (((tok >> CODEC_MATCH_LEN_SHIFT) & CODEC_MATCH_LEN_MASK) as usize)
                + CODEC_MIN_MATCH;
            let distance: usize = ((tok & CODEC_MATCH_DIST_MASK) as usize) + 1;
            let (lcode, lextra, lbits): (usize, u32, u32) = length_to_code(length);
            let (dcode, dextra, dbits): (usize, u32, u32) = distance_to_code(distance);
            let lsym: usize = CODEC_LENGTH_SYMBOL_BASE + lcode;
            writer.write_bits(lit_codes[lsym] as u64, lit_lens[lsym] as u32);
            writer.write_bits(lextra as u64, lbits);
            writer.write_bits(dist_codes[dcode] as u64, dist_lens[dcode] as u32);
            writer.write_bits(dextra as u64, dbits);
        }
    }
    writer.write_bits(
        lit_codes[CODEC_END_OF_BLOCK] as u64,
        lit_lens[CODEC_END_OF_BLOCK] as u32,
    );
}

/// Decodes a single canonical Huffman symbol from `reader` using `table`.
///
/// # Arguments
///
/// - `&mut CodecBitReader<'_>` - Active bit reader.
/// - `&[u16]` - Flat `2^15`-entry canonical decode table.
///
/// # Returns
///
/// - `Result<usize, DocsCodecError>` - Decoded symbol id or stream/table error.
fn decode_symbol(reader: &mut CodecBitReader<'_>, table: &[u16]) -> Result<usize, DocsCodecError> {
    if reader.get_bit_count() < CODEC_MAX_CODE_BITS {
        reader.refill();
    }
    let idx: usize = (reader.get_bit_buf() as usize) & (CODEC_TABLE_SIZE - 1);
    let entry: u16 = table[idx];
    let bit_len: u32 = (entry as u32) & CODEC_TABLE_LEN_MASK;
    if bit_len == 0 {
        return Err(DocsCodecError::InvalidSymbol);
    }
    if reader.get_bit_count() < bit_len {
        return Err(DocsCodecError::Truncated);
    }
    reader.consume(bit_len);
    Ok((entry >> CODEC_TABLE_LEN_BITS) as usize)
}

/// Compresses raw documentation bytes into the zero-dependency `EUVZ` LZ77 + Canonical Huffman format.
///
/// # Arguments
///
/// - `&[u8]` - Uncompressed UTF-8 or binary payload.
///
/// # Returns
///
/// - `Vec<u8>` - Compact compressed byte stream prefixed with `CODEC_MAGIC`.
#[must_use]
pub fn compress_docs_bytes(input: &[u8]) -> Vec<u8> {
    let mut header: Vec<u8> = Vec::with_capacity(16);
    header.extend_from_slice(&CODEC_MAGIC);
    header.push(CODEC_VERSION);
    write_varint(&mut header, input.len() as u64);
    if input.is_empty() {
        return header;
    }
    let tokens: Vec<u32> = lz77_tokenize(input);
    let mut writer: CodecBitWriter = CodecBitWriter::with_capacity(input.len() / 3 + 32);
    writer.get_mut_bytes().extend_from_slice(&header);
    let total_chunks: usize = tokens.len().div_ceil(CODEC_BLOCK_TOKENS);
    for (idx, chunk) in tokens.chunks(CODEC_BLOCK_TOKENS).enumerate() {
        let is_final: bool = idx + 1 == total_chunks;
        encode_huffman_block(&mut writer, chunk, is_final);
    }
    writer.finish()
}

/// Decompresses an `EUVZ` byte stream produced by `compress_docs_bytes` back to the exact original bytes.
///
/// # Arguments
///
/// - `&[u8]` - Compressed `EUVZ` byte stream.
///
/// # Returns
///
/// - `Result<Vec<u8>, DocsCodecError>` - Bit-exact restored byte payload or typed decode error.
pub fn decompress_docs_bytes(compressed: &[u8]) -> Result<Vec<u8>, DocsCodecError> {
    if compressed.len() < CODEC_MAGIC.len() + 1 {
        return Err(DocsCodecError::Truncated);
    }
    if compressed[..CODEC_MAGIC.len()] != CODEC_MAGIC {
        return Err(DocsCodecError::BadMagic);
    }
    let version: u8 = compressed[CODEC_MAGIC.len()];
    if version != CODEC_VERSION {
        return Err(DocsCodecError::UnsupportedVersion(version));
    }
    let mut pos: usize = CODEC_MAGIC.len() + 1;
    let orig_len_u64: u64 = read_varint(compressed, &mut pos)?;
    let orig_len: usize = usize::try_from(orig_len_u64).map_err(|_| DocsCodecError::Truncated)?;
    if orig_len == 0 {
        return Ok(Vec::new());
    }
    let cap_hint: usize = orig_len.min(CODEC_CAPACITY_HINT_LIMIT);
    let mut out: Vec<u8> = Vec::with_capacity(cap_hint);
    let mut reader: CodecBitReader<'_> = CodecBitReader::from_slice(&compressed[pos..]);
    let mut lit_lens: [u8; CODEC_LITLEN_SYMBOLS] = [0u8; CODEC_LITLEN_SYMBOLS];
    let mut dist_lens: [u8; CODEC_DIST_SYMBOLS] = [0u8; CODEC_DIST_SYMBOLS];
    loop {
        let is_final: u32 = reader.read_bits(1)?;
        let has_matches: u32 = reader.read_bits(1)?;
        for slot in lit_lens.iter_mut() {
            *slot = reader.read_bits(CODEC_CODE_LEN_FIELD_BITS)? as u8;
        }
        let lit_table: Vec<u16> = build_decode_table(&lit_lens)?;
        let dist_table: Vec<u16> = if has_matches != 0 {
            for slot in dist_lens.iter_mut() {
                *slot = reader.read_bits(CODEC_CODE_LEN_FIELD_BITS)? as u8;
            }
            build_decode_table(&dist_lens)?
        } else {
            Vec::new()
        };
        loop {
            let sym: usize = decode_symbol(&mut reader, &lit_table)?;
            if sym < CODEC_END_OF_BLOCK {
                if out.len() >= orig_len {
                    return Err(DocsCodecError::LengthMismatch);
                }
                out.push(sym as u8);
            } else if sym == CODEC_END_OF_BLOCK {
                break;
            } else if sym < CODEC_LITLEN_SYMBOLS {
                if dist_table.is_empty() {
                    return Err(DocsCodecError::InvalidSymbol);
                }
                let lcode: usize = sym - CODEC_LENGTH_SYMBOL_BASE;
                let lextra: usize = reader.read_bits(CODEC_LEN_EXTRA[lcode] as u32)? as usize;
                let length: usize = (CODEC_LEN_BASE[lcode] as usize) + lextra;
                let dcode: usize = decode_symbol(&mut reader, &dist_table)?;
                if dcode >= CODEC_DIST_SYMBOLS {
                    return Err(DocsCodecError::InvalidSymbol);
                }
                let dextra: usize = reader.read_bits(CODEC_DIST_EXTRA[dcode] as u32)? as usize;
                let distance: usize = (CODEC_DIST_BASE[dcode] as usize) + dextra;
                if distance == 0 || distance > out.len() {
                    return Err(DocsCodecError::InvalidDistance);
                }
                if out.len().saturating_add(length) > orig_len {
                    return Err(DocsCodecError::LengthMismatch);
                }
                let start: usize = out.len() - distance;
                for offset in 0..length {
                    let byte: u8 = out[start + offset];
                    out.push(byte);
                }
            } else {
                return Err(DocsCodecError::InvalidSymbol);
            }
        }
        if is_final != 0 {
            break;
        }
    }
    if out.len() != orig_len {
        return Err(DocsCodecError::LengthMismatch);
    }
    Ok(out)
}

/// Splits a `DocSite` into a lightweight plaintext metadata shell and an `EUVZ`-compressed page body blob.
///
/// # Arguments
///
/// - `&DocSite` - Complete parsed documentation site for one locale.
///
/// # Returns
///
/// - `Result<PackedSiteBundle, DocsCodecError>` - Split plaintext shell JSON and compressed body bytes.
pub fn pack_site_bundle(site: &DocSite) -> Result<PackedSiteBundle, DocsCodecError> {
    let mut shell: DocSite = site.clone();
    let mut bodies: Vec<PackedPageBody> = Vec::with_capacity(shell.get_pages().len());
    for page in shell.get_mut_pages().iter_mut() {
        let md: String = take(page.get_mut_markdown_body());
        let raw_blocks: Vec<DocBlock> = take(page.get_mut_blocks());
        let retained_blocks: Vec<DocBlock> = if md.trim().is_empty() {
            raw_blocks
        } else {
            Vec::new()
        };
        bodies.push(PackedPageBody::new(md, retained_blocks));
    }
    let shell_json: String = to_string(&shell)
        .map_err(|err: serde_json::Error| DocsCodecError::InvalidPayload(err.to_string()))?;
    let bodies_json: String = to_string(&bodies)
        .map_err(|err: serde_json::Error| DocsCodecError::InvalidPayload(err.to_string()))?;
    let compressed_bodies: Vec<u8> = compress_docs_bytes(bodies_json.as_bytes());
    Ok(PackedSiteBundle::new(shell_json, compressed_bodies))
}

/// Reconstructs a `DocSite` from its plaintext metadata shell JSON and `EUVZ`-compressed page bodies.
///
/// # Arguments
///
/// - `&str` - Compact plaintext `DocSite` shell JSON.
/// - `&[u8]` - `EUVZ`-compressed `Vec<PackedPageBody>` UTF-8 JSON bytes.
///
/// # Returns
///
/// - `Result<DocSite, DocsCodecError>` - Fully hydrated `DocSite` ready for native rendering and search.
pub fn unpack_site_bundle(
    shell_json: &str,
    compressed_bodies: &[u8],
) -> Result<DocSite, DocsCodecError> {
    let mut site: DocSite = serde_json::from_str::<DocSite>(shell_json)
        .map_err(|err: serde_json::Error| DocsCodecError::InvalidPayload(err.to_string()))?;
    let raw_bodies: Vec<u8> = decompress_docs_bytes(compressed_bodies)?;
    let bodies: Vec<PackedPageBody> = serde_json::from_slice::<Vec<PackedPageBody>>(&raw_bodies)
        .map_err(|err: serde_json::Error| DocsCodecError::InvalidPayload(err.to_string()))?;
    if bodies.len() != site.get_pages().len() {
        return Err(DocsCodecError::PageCountMismatch);
    }
    for (page, mut body) in site.get_mut_pages().iter_mut().zip(bodies) {
        page.set_markdown_body(take(body.get_mut_markdown_body()));
        page.set_blocks(take(body.get_mut_blocks()));
    }
    Ok(site)
}