Skip to main content

euv_docs/codec/
fn.rs

1use super::*;
2
3/// Encodes an unsigned 64-bit integer using unsigned LEB128 varint encoding.
4///
5/// # Arguments
6///
7/// - `&mut Vec<u8>` - Destination byte vector.
8/// - `u64` - Integer value to encode.
9fn write_varint(out: &mut Vec<u8>, mut value: u64) {
10    loop {
11        let mut byte: u8 = (value as u8) & CODEC_VARINT_PAYLOAD_MASK;
12        value >>= 7;
13        if value != 0 {
14            byte |= CODEC_VARINT_CONTINUE;
15        }
16        out.push(byte);
17        if value == 0 {
18            break;
19        }
20    }
21}
22
23/// Decodes an unsigned LEB128 varint from `input` starting at `*pos`.
24///
25/// # Arguments
26///
27/// - `&[u8]` - Source byte slice.
28/// - `&mut usize` - Read cursor advanced past the decoded varint.
29///
30/// # Returns
31///
32/// - `Result<u64, DocsCodecError>` - Decoded integer or truncation error.
33fn read_varint(input: &[u8], pos: &mut usize) -> Result<u64, DocsCodecError> {
34    let mut result: u64 = 0;
35    let mut shift: u32 = 0;
36    loop {
37        if *pos >= input.len() || shift > CODEC_VARINT_MAX_SHIFT {
38            return Err(DocsCodecError::Truncated);
39        }
40        let byte: u8 = input[*pos];
41        *pos += 1;
42        let payload: u64 = (byte & CODEC_VARINT_PAYLOAD_MASK) as u64;
43        result |= payload
44            .checked_shl(shift)
45            .ok_or(DocsCodecError::Truncated)?;
46        if (byte & CODEC_VARINT_CONTINUE) == 0 {
47            return Ok(result);
48        }
49        shift += 7;
50    }
51}
52
53/// Reverses the lowest `bit_len` bits of `code` for LSB-first canonical Huffman streaming.
54///
55/// # Arguments
56///
57/// - `u32` - MSB-first canonical Huffman code.
58/// - `u32` - Bit length in `1..=CODEC_MAX_CODE_BITS`.
59///
60/// # Returns
61///
62/// - `u32` - Bit-reversed code ready for LSB-first emission.
63fn reverse_bits(code: u32, bit_len: u32) -> u32 {
64    if bit_len == 0 {
65        return 0;
66    }
67    code.reverse_bits() >> (32 - bit_len)
68}
69
70/// Maps a match length in `3..=258` to its length code index, extra bit value, and extra bit count.
71///
72/// # Arguments
73///
74/// - `usize` - Match length in bytes.
75///
76/// # Returns
77///
78/// - `(usize, u32, u32)` - Tuple of `(length_code_index, extra_bits_value, extra_bits_count)`.
79fn length_to_code(length: usize) -> (usize, u32, u32) {
80    let idx: usize = CODEC_LEN_BASE
81        .partition_point(|base: &u16| (*base as usize) <= length)
82        .saturating_sub(1);
83    let extra_val: u32 = (length - (CODEC_LEN_BASE[idx] as usize)) as u32;
84    let extra_bits: u32 = CODEC_LEN_EXTRA[idx] as u32;
85    (idx, extra_val, extra_bits)
86}
87
88/// Maps a back-reference distance in `1..=CODEC_WINDOW_SIZE` to its distance code index and extra bits.
89///
90/// # Arguments
91///
92/// - `usize` - Match distance in bytes.
93///
94/// # Returns
95///
96/// - `(usize, u32, u32)` - Tuple of `(dist_code_index, extra_bits_value, extra_bits_count)`.
97fn distance_to_code(distance: usize) -> (usize, u32, u32) {
98    let idx: usize = CODEC_DIST_BASE
99        .partition_point(|base: &u32| (*base as usize) <= distance)
100        .saturating_sub(1);
101    let extra_val: u32 = (distance - (CODEC_DIST_BASE[idx] as usize)) as u32;
102    let extra_bits: u32 = CODEC_DIST_EXTRA[idx] as u32;
103    (idx, extra_val, extra_bits)
104}
105
106/// Computes length-limited canonical Huffman code lengths (`<= max_bits`) from symbol frequencies.
107///
108/// # Arguments
109///
110/// - `&[u32]` - Non-negative frequency table indexed by symbol id.
111/// - `u32` - Maximum permitted code length in bits.
112///
113/// # Returns
114///
115/// - `Vec<u8>` - Code length per symbol (`0` for symbols with frequency `0`).
116fn build_code_lengths(freqs: &[u32], max_bits: u32) -> Vec<u8> {
117    let sym_count: usize = freqs.len();
118    let mut lens: Vec<u8> = vec![0u8; sym_count];
119    let mut active: Vec<usize> = Vec::new();
120    for (sym, &freq) in freqs.iter().enumerate() {
121        if freq > 0 {
122            active.push(sym);
123        }
124    }
125    if active.is_empty() {
126        return lens;
127    }
128    if active.len() == 1 {
129        lens[active[0]] = 1;
130        return lens;
131    }
132    let mut heap: BinaryHeap<Reverse<(u64, usize)>> = BinaryHeap::with_capacity(active.len());
133    let mut parent: Vec<usize> = vec![usize::MAX; sym_count * 2];
134    for &sym in active.iter() {
135        heap.push(Reverse((freqs[sym] as u64, sym)));
136    }
137    let mut next_node: usize = sym_count;
138    while heap.len() > 1 {
139        let Some(Reverse((w1, n1))) = heap.pop() else {
140            break;
141        };
142        let Some(Reverse((w2, n2))) = heap.pop() else {
143            break;
144        };
145        let merged: usize = next_node;
146        next_node += 1;
147        if merged >= parent.len() {
148            parent.resize(merged + 1, usize::MAX);
149        }
150        parent[n1] = merged;
151        parent[n2] = merged;
152        heap.push(Reverse((w1.saturating_add(w2), merged)));
153    }
154    let max_bits_u8: u8 = max_bits as u8;
155    let mut kraft: u64 = 0;
156    let limit: u64 = 1u64 << max_bits;
157    for &sym in active.iter() {
158        let mut depth: u32 = 0;
159        let mut cur: usize = sym;
160        while parent[cur] != usize::MAX {
161            depth += 1;
162            cur = parent[cur];
163        }
164        let clamped: u8 = depth.clamp(1, max_bits) as u8;
165        lens[sym] = clamped;
166        kraft += 1u64 << (max_bits - (clamped as u32));
167    }
168    while kraft > limit {
169        let mut candidate: Option<usize> = None;
170        for &sym in active.iter() {
171            let cur_len: u8 = lens[sym];
172            if cur_len < max_bits_u8 {
173                let replace: bool = match candidate {
174                    None => true,
175                    Some(prev) => {
176                        cur_len > lens[prev] || (cur_len == lens[prev] && freqs[sym] < freqs[prev])
177                    }
178                };
179                if replace {
180                    candidate = Some(sym);
181                }
182            }
183        }
184        let Some(sym) = candidate else {
185            break;
186        };
187        lens[sym] += 1;
188        kraft -= 1u64 << (max_bits - (lens[sym] as u32));
189    }
190    while kraft < limit {
191        let mut candidate: Option<usize> = None;
192        for &sym in active.iter() {
193            let cur_len: u8 = lens[sym];
194            if cur_len > 1 {
195                let delta: u64 = 1u64 << (max_bits - (cur_len as u32));
196                if kraft + delta <= limit {
197                    let replace: bool = match candidate {
198                        None => true,
199                        Some(prev) => freqs[sym] > freqs[prev],
200                    };
201                    if replace {
202                        candidate = Some(sym);
203                    }
204                }
205            }
206        }
207        let Some(sym) = candidate else {
208            break;
209        };
210        let delta: u64 = 1u64 << (max_bits - (lens[sym] as u32));
211        lens[sym] -= 1;
212        kraft += delta;
213    }
214    lens
215}
216
217/// Derives LSB-first canonical Huffman codes from per-symbol bit lengths.
218///
219/// # Arguments
220///
221/// - `&[u8]` - Code length per symbol (`0..=CODEC_MAX_CODE_BITS`).
222///
223/// # Returns
224///
225/// - `Result<Vec<u32>, DocsCodecError>` - Bit-reversed canonical code per symbol, or an error if over-subscribed.
226fn build_canonical_codes(lens: &[u8]) -> Result<Vec<u32>, DocsCodecError> {
227    let mut bl_count: [u32; 16] = [0u32; 16];
228    let mut kraft: u32 = 0;
229    let limit: u32 = 1u32 << CODEC_MAX_CODE_BITS;
230    for &len_u8 in lens.iter() {
231        let len: usize = len_u8 as usize;
232        if len > CODEC_MAX_CODE_BITS as usize {
233            return Err(DocsCodecError::InvalidCodeLengths);
234        }
235        if len > 0 {
236            bl_count[len] += 1;
237            kraft = kraft.saturating_add(1u32 << (CODEC_MAX_CODE_BITS - (len as u32)));
238        }
239    }
240    if kraft == 0 || kraft > limit {
241        return Err(DocsCodecError::InvalidCodeLengths);
242    }
243    let mut next_code: [u32; 16] = [0u32; 16];
244    let mut code: u32 = 0;
245    for bits in 1..=(CODEC_MAX_CODE_BITS as usize) {
246        code = (code + bl_count[bits - 1]) << 1;
247        next_code[bits] = code;
248    }
249    let mut codes: Vec<u32> = vec![0u32; lens.len()];
250    for (sym, &len_u8) in lens.iter().enumerate() {
251        if len_u8 > 0 {
252            let len_idx: usize = len_u8 as usize;
253            let raw: u32 = next_code[len_idx];
254            next_code[len_idx] += 1;
255            codes[sym] = reverse_bits(raw, len_u8 as u32);
256        }
257    }
258    Ok(codes)
259}
260
261/// Builds a flat `2^15`-entry O(1) lookup table for canonical Huffman decoding.
262///
263/// # Arguments
264///
265/// - `&[u8]` - Code length per symbol (`0..=CODEC_MAX_CODE_BITS`).
266///
267/// # Returns
268///
269/// - `Result<Vec<u16>, DocsCodecError>` - Packed lookup table where each entry encodes `(symbol << 4) | bit_len`.
270fn build_decode_table(lens: &[u8]) -> Result<Vec<u16>, DocsCodecError> {
271    let codes: Vec<u32> = build_canonical_codes(lens)?;
272    let mut table: Vec<u16> = vec![0u16; CODEC_TABLE_SIZE];
273    for (sym, &len_u8) in lens.iter().enumerate() {
274        if len_u8 > 0 {
275            let step: usize = 1usize << (len_u8 as u32);
276            let entry: u16 = ((sym as u16) << CODEC_TABLE_LEN_BITS) | (len_u8 as u16);
277            let mut idx: usize = codes[sym] as usize;
278            while idx < CODEC_TABLE_SIZE {
279                table[idx] = entry;
280                idx += step;
281            }
282        }
283    }
284    Ok(table)
285}
286
287/// Computes a 3-byte multiplicative hash index for the LZ77 hash chain.
288///
289/// # Arguments
290///
291/// - `&[u8]` - Input byte slice.
292/// - `usize` - Starting index (must have at least 3 bytes remaining).
293///
294/// # Returns
295///
296/// - `usize` - Hash bucket index in `0..(1 << CODEC_HASH_BITS)`.
297fn hash3(data: &[u8], pos: usize) -> usize {
298    let packed: u32 =
299        (data[pos] as u32) | ((data[pos + 1] as u32) << 8) | ((data[pos + 2] as u32) << 16);
300    ((packed.wrapping_mul(CODEC_HASH_MULTIPLIER)) >> (32 - CODEC_HASH_BITS)) as usize
301}
302
303/// Searches the hash chain at `pos` for the longest back-reference within `CODEC_WINDOW_SIZE`.
304///
305/// # Arguments
306///
307/// - `&[u8]` - Input byte slice.
308/// - `usize` - Current input position.
309/// - `u32` - Head position recorded for `hash3(data, pos)`.
310/// - `&[u32]` - Ring-buffered chain pointers indexed by `pos & (CODEC_WINDOW_SIZE - 1)`.
311///
312/// # Returns
313///
314/// - `(usize, usize)` - Best `(length, distance)` pair, or `(0, 0)` when no `>= 3`-byte match exists.
315fn find_best_match(data: &[u8], pos: usize, head_pos: u32, prev: &[u32]) -> (usize, usize) {
316    let max_len: usize = (data.len() - pos).min(CODEC_MAX_MATCH);
317    if max_len < CODEC_MIN_MATCH {
318        return (0, 0);
319    }
320    let window_mask: usize = CODEC_WINDOW_SIZE - 1;
321    let mut best_len: usize = CODEC_MIN_MATCH - 1;
322    let mut best_dist: usize = 0;
323    let mut cur: u32 = head_pos;
324    let mut steps: usize = 0;
325    while cur != CODEC_HASH_EMPTY && steps < CODEC_MAX_CHAIN {
326        let cur_idx: usize = cur as usize;
327        if cur_idx >= pos {
328            break;
329        }
330        let dist: usize = pos - cur_idx;
331        if dist > CODEC_WINDOW_SIZE {
332            break;
333        }
334        if data[cur_idx + best_len] == data[pos + best_len] && data[cur_idx] == data[pos] {
335            let mut matched: usize = 0;
336            while matched < max_len && data[cur_idx + matched] == data[pos + matched] {
337                matched += 1;
338            }
339            if matched > best_len {
340                best_len = matched;
341                best_dist = dist;
342                if best_len >= CODEC_NICE_MATCH || best_len == max_len {
343                    break;
344                }
345            }
346        }
347        let next: u32 = prev[cur_idx & window_mask];
348        if next >= cur {
349            break;
350        }
351        cur = next;
352        steps += 1;
353    }
354    if best_len >= CODEC_MIN_MATCH {
355        (best_len, best_dist)
356    } else {
357        (0, 0)
358    }
359}
360
361/// Tokenizes `data` into packed LZ77 literal and match tokens using a 1 MiB lazy-matching window.
362///
363/// # Arguments
364///
365/// - `&[u8]` - Uncompressed input byte slice.
366///
367/// # Returns
368///
369/// - `Vec<u32>` - Packed token stream (literals `< 256`; matches flagged with `CODEC_MATCH_FLAG`).
370fn lz77_tokenize(data: &[u8]) -> Vec<u32> {
371    let table_len: usize = 1usize << CODEC_HASH_BITS;
372    let mut head: Vec<u32> = vec![CODEC_HASH_EMPTY; table_len];
373    let mut prev: Vec<u32> = vec![CODEC_HASH_EMPTY; CODEC_WINDOW_SIZE];
374    let window_mask: usize = CODEC_WINDOW_SIZE - 1;
375    let mut tokens: Vec<u32> = Vec::with_capacity(data.len() / 2);
376    let mut pos: usize = 0;
377    while pos < data.len() {
378        if pos + CODEC_MIN_MATCH > data.len() {
379            tokens.push(data[pos] as u32);
380            pos += 1;
381            continue;
382        }
383        let h: usize = hash3(data, pos);
384        let prev_head: u32 = head[h];
385        prev[pos & window_mask] = prev_head;
386        head[h] = pos as u32;
387        let (mut best_len, mut best_dist): (usize, usize) =
388            find_best_match(data, pos, prev_head, &prev);
389        if (CODEC_MIN_MATCH..CODEC_LAZY_LIMIT).contains(&best_len)
390            && pos + 1 + CODEC_MIN_MATCH <= data.len()
391        {
392            let next_pos: usize = pos + 1;
393            let h2: usize = hash3(data, next_pos);
394            let prev_head2: u32 = head[h2];
395            prev[next_pos & window_mask] = prev_head2;
396            head[h2] = next_pos as u32;
397            let (next_len, next_dist): (usize, usize) =
398                find_best_match(data, next_pos, prev_head2, &prev);
399            if next_len > best_len + 1 {
400                tokens.push(data[pos] as u32);
401                pos = next_pos;
402                best_len = next_len;
403                best_dist = next_dist;
404            }
405        }
406        if best_len >= CODEC_MIN_MATCH {
407            let packed: u32 = CODEC_MATCH_FLAG
408                | (((best_len - CODEC_MIN_MATCH) as u32) << CODEC_MATCH_LEN_SHIFT)
409                | ((best_dist - 1) as u32);
410            tokens.push(packed);
411            let end: usize = pos + best_len;
412            let mut cur: usize = pos + 1;
413            while cur < end && cur + CODEC_MIN_MATCH <= data.len() {
414                let hc: usize = hash3(data, cur);
415                let prev_c: u32 = head[hc];
416                if prev_c != cur as u32 {
417                    prev[cur & window_mask] = prev_c;
418                    head[hc] = cur as u32;
419                }
420                cur += 1;
421            }
422            pos = end;
423        } else {
424            tokens.push(data[pos] as u32);
425            pos += 1;
426        }
427    }
428    tokens
429}
430
431/// Encodes one token chunk as a dynamic Canonical Huffman block into `writer`.
432///
433/// # Arguments
434///
435/// - `&mut CodecBitWriter` - Active bit writer.
436/// - `&[u32]` - Token chunk for this block.
437/// - `bool` - Whether this block is the final block in the stream.
438fn encode_huffman_block(writer: &mut CodecBitWriter, chunk: &[u32], is_final: bool) {
439    let mut lit_freqs: [u32; CODEC_LITLEN_SYMBOLS] = [0u32; CODEC_LITLEN_SYMBOLS];
440    let mut dist_freqs: [u32; CODEC_DIST_SYMBOLS] = [0u32; CODEC_DIST_SYMBOLS];
441    let mut has_matches: bool = false;
442    for &tok in chunk.iter() {
443        if (tok & CODEC_MATCH_FLAG) == 0 {
444            lit_freqs[tok as usize] += 1;
445        } else {
446            has_matches = true;
447            let length: usize = (((tok >> CODEC_MATCH_LEN_SHIFT) & CODEC_MATCH_LEN_MASK) as usize)
448                + CODEC_MIN_MATCH;
449            let distance: usize = ((tok & CODEC_MATCH_DIST_MASK) as usize) + 1;
450            let (lcode, _, _): (usize, u32, u32) = length_to_code(length);
451            let (dcode, _, _): (usize, u32, u32) = distance_to_code(distance);
452            lit_freqs[CODEC_LENGTH_SYMBOL_BASE + lcode] += 1;
453            dist_freqs[dcode] += 1;
454        }
455    }
456    lit_freqs[CODEC_END_OF_BLOCK] = 1;
457    let lit_lens: Vec<u8> = build_code_lengths(&lit_freqs, CODEC_MAX_CODE_BITS);
458    let lit_codes: Vec<u32> = build_canonical_codes(&lit_lens).unwrap_or_default();
459    let dist_lens: Vec<u8> = if has_matches {
460        build_code_lengths(&dist_freqs, CODEC_MAX_CODE_BITS)
461    } else {
462        Vec::new()
463    };
464    let dist_codes: Vec<u32> = if has_matches {
465        build_canonical_codes(&dist_lens).unwrap_or_default()
466    } else {
467        Vec::new()
468    };
469    writer.write_bits(u64::from(is_final), 1);
470    writer.write_bits(u64::from(has_matches), 1);
471    for &len_u8 in lit_lens.iter() {
472        writer.write_bits(len_u8 as u64, CODEC_CODE_LEN_FIELD_BITS);
473    }
474    if has_matches {
475        for &len_u8 in dist_lens.iter() {
476            writer.write_bits(len_u8 as u64, CODEC_CODE_LEN_FIELD_BITS);
477        }
478    }
479    for &tok in chunk.iter() {
480        if (tok & CODEC_MATCH_FLAG) == 0 {
481            let sym: usize = tok as usize;
482            writer.write_bits(lit_codes[sym] as u64, lit_lens[sym] as u32);
483        } else {
484            let length: usize = (((tok >> CODEC_MATCH_LEN_SHIFT) & CODEC_MATCH_LEN_MASK) as usize)
485                + CODEC_MIN_MATCH;
486            let distance: usize = ((tok & CODEC_MATCH_DIST_MASK) as usize) + 1;
487            let (lcode, lextra, lbits): (usize, u32, u32) = length_to_code(length);
488            let (dcode, dextra, dbits): (usize, u32, u32) = distance_to_code(distance);
489            let lsym: usize = CODEC_LENGTH_SYMBOL_BASE + lcode;
490            writer.write_bits(lit_codes[lsym] as u64, lit_lens[lsym] as u32);
491            writer.write_bits(lextra as u64, lbits);
492            writer.write_bits(dist_codes[dcode] as u64, dist_lens[dcode] as u32);
493            writer.write_bits(dextra as u64, dbits);
494        }
495    }
496    writer.write_bits(
497        lit_codes[CODEC_END_OF_BLOCK] as u64,
498        lit_lens[CODEC_END_OF_BLOCK] as u32,
499    );
500}
501
502/// Decodes a single canonical Huffman symbol from `reader` using `table`.
503///
504/// # Arguments
505///
506/// - `&mut CodecBitReader<'_>` - Active bit reader.
507/// - `&[u16]` - Flat `2^15`-entry canonical decode table.
508///
509/// # Returns
510///
511/// - `Result<usize, DocsCodecError>` - Decoded symbol id or stream/table error.
512fn decode_symbol(reader: &mut CodecBitReader<'_>, table: &[u16]) -> Result<usize, DocsCodecError> {
513    if reader.get_bit_count() < CODEC_MAX_CODE_BITS {
514        reader.refill();
515    }
516    let idx: usize = (reader.get_bit_buf() as usize) & (CODEC_TABLE_SIZE - 1);
517    let entry: u16 = table[idx];
518    let bit_len: u32 = (entry as u32) & CODEC_TABLE_LEN_MASK;
519    if bit_len == 0 {
520        return Err(DocsCodecError::InvalidSymbol);
521    }
522    if reader.get_bit_count() < bit_len {
523        return Err(DocsCodecError::Truncated);
524    }
525    reader.consume(bit_len);
526    Ok((entry >> CODEC_TABLE_LEN_BITS) as usize)
527}
528
529/// Compresses raw documentation bytes into the zero-dependency `EUVZ` LZ77 + Canonical Huffman format.
530///
531/// # Arguments
532///
533/// - `&[u8]` - Uncompressed UTF-8 or binary payload.
534///
535/// # Returns
536///
537/// - `Vec<u8>` - Compact compressed byte stream prefixed with `CODEC_MAGIC`.
538#[must_use]
539pub fn compress_docs_bytes(input: &[u8]) -> Vec<u8> {
540    let mut header: Vec<u8> = Vec::with_capacity(16);
541    header.extend_from_slice(&CODEC_MAGIC);
542    header.push(CODEC_VERSION);
543    write_varint(&mut header, input.len() as u64);
544    if input.is_empty() {
545        return header;
546    }
547    let tokens: Vec<u32> = lz77_tokenize(input);
548    let mut writer: CodecBitWriter = CodecBitWriter::with_capacity(input.len() / 3 + 32);
549    writer.get_mut_bytes().extend_from_slice(&header);
550    let total_chunks: usize = tokens.len().div_ceil(CODEC_BLOCK_TOKENS);
551    for (idx, chunk) in tokens.chunks(CODEC_BLOCK_TOKENS).enumerate() {
552        let is_final: bool = idx + 1 == total_chunks;
553        encode_huffman_block(&mut writer, chunk, is_final);
554    }
555    writer.finish()
556}
557
558/// Decompresses an `EUVZ` byte stream produced by `compress_docs_bytes` back to the exact original bytes.
559///
560/// # Arguments
561///
562/// - `&[u8]` - Compressed `EUVZ` byte stream.
563///
564/// # Returns
565///
566/// - `Result<Vec<u8>, DocsCodecError>` - Bit-exact restored byte payload or typed decode error.
567pub fn decompress_docs_bytes(compressed: &[u8]) -> Result<Vec<u8>, DocsCodecError> {
568    if compressed.len() < CODEC_MAGIC.len() + 1 {
569        return Err(DocsCodecError::Truncated);
570    }
571    if compressed[..CODEC_MAGIC.len()] != CODEC_MAGIC {
572        return Err(DocsCodecError::BadMagic);
573    }
574    let version: u8 = compressed[CODEC_MAGIC.len()];
575    if version != CODEC_VERSION {
576        return Err(DocsCodecError::UnsupportedVersion(version));
577    }
578    let mut pos: usize = CODEC_MAGIC.len() + 1;
579    let orig_len_u64: u64 = read_varint(compressed, &mut pos)?;
580    let orig_len: usize = usize::try_from(orig_len_u64).map_err(|_| DocsCodecError::Truncated)?;
581    if orig_len == 0 {
582        return Ok(Vec::new());
583    }
584    let cap_hint: usize = orig_len.min(CODEC_CAPACITY_HINT_LIMIT);
585    let mut out: Vec<u8> = Vec::with_capacity(cap_hint);
586    let mut reader: CodecBitReader<'_> = CodecBitReader::from_slice(&compressed[pos..]);
587    let mut lit_lens: [u8; CODEC_LITLEN_SYMBOLS] = [0u8; CODEC_LITLEN_SYMBOLS];
588    let mut dist_lens: [u8; CODEC_DIST_SYMBOLS] = [0u8; CODEC_DIST_SYMBOLS];
589    loop {
590        let is_final: u32 = reader.read_bits(1)?;
591        let has_matches: u32 = reader.read_bits(1)?;
592        for slot in lit_lens.iter_mut() {
593            *slot = reader.read_bits(CODEC_CODE_LEN_FIELD_BITS)? as u8;
594        }
595        let lit_table: Vec<u16> = build_decode_table(&lit_lens)?;
596        let dist_table: Vec<u16> = if has_matches != 0 {
597            for slot in dist_lens.iter_mut() {
598                *slot = reader.read_bits(CODEC_CODE_LEN_FIELD_BITS)? as u8;
599            }
600            build_decode_table(&dist_lens)?
601        } else {
602            Vec::new()
603        };
604        loop {
605            let sym: usize = decode_symbol(&mut reader, &lit_table)?;
606            if sym < CODEC_END_OF_BLOCK {
607                if out.len() >= orig_len {
608                    return Err(DocsCodecError::LengthMismatch);
609                }
610                out.push(sym as u8);
611            } else if sym == CODEC_END_OF_BLOCK {
612                break;
613            } else if sym < CODEC_LITLEN_SYMBOLS {
614                if dist_table.is_empty() {
615                    return Err(DocsCodecError::InvalidSymbol);
616                }
617                let lcode: usize = sym - CODEC_LENGTH_SYMBOL_BASE;
618                let lextra: usize = reader.read_bits(CODEC_LEN_EXTRA[lcode] as u32)? as usize;
619                let length: usize = (CODEC_LEN_BASE[lcode] as usize) + lextra;
620                let dcode: usize = decode_symbol(&mut reader, &dist_table)?;
621                if dcode >= CODEC_DIST_SYMBOLS {
622                    return Err(DocsCodecError::InvalidSymbol);
623                }
624                let dextra: usize = reader.read_bits(CODEC_DIST_EXTRA[dcode] as u32)? as usize;
625                let distance: usize = (CODEC_DIST_BASE[dcode] as usize) + dextra;
626                if distance == 0 || distance > out.len() {
627                    return Err(DocsCodecError::InvalidDistance);
628                }
629                if out.len().saturating_add(length) > orig_len {
630                    return Err(DocsCodecError::LengthMismatch);
631                }
632                let start: usize = out.len() - distance;
633                for offset in 0..length {
634                    let byte: u8 = out[start + offset];
635                    out.push(byte);
636                }
637            } else {
638                return Err(DocsCodecError::InvalidSymbol);
639            }
640        }
641        if is_final != 0 {
642            break;
643        }
644    }
645    if out.len() != orig_len {
646        return Err(DocsCodecError::LengthMismatch);
647    }
648    Ok(out)
649}
650
651/// Splits a `DocSite` into a lightweight plaintext metadata shell and an `EUVZ`-compressed page body blob.
652///
653/// # Arguments
654///
655/// - `&DocSite` - Complete parsed documentation site for one locale.
656///
657/// # Returns
658///
659/// - `Result<PackedSiteBundle, DocsCodecError>` - Split plaintext shell JSON and compressed body bytes.
660pub fn pack_site_bundle(site: &DocSite) -> Result<PackedSiteBundle, DocsCodecError> {
661    let mut shell: DocSite = site.clone();
662    let mut bodies: Vec<PackedPageBody> = Vec::with_capacity(shell.get_pages().len());
663    for page in shell.get_mut_pages().iter_mut() {
664        let md: String = take(page.get_mut_markdown_body());
665        let raw_blocks: Vec<DocBlock> = take(page.get_mut_blocks());
666        let retained_blocks: Vec<DocBlock> = if md.trim().is_empty() {
667            raw_blocks
668        } else {
669            Vec::new()
670        };
671        bodies.push(PackedPageBody::new(md, retained_blocks));
672    }
673    let shell_json: String = to_string(&shell)
674        .map_err(|err: serde_json::Error| DocsCodecError::InvalidPayload(err.to_string()))?;
675    let bodies_json: String = to_string(&bodies)
676        .map_err(|err: serde_json::Error| DocsCodecError::InvalidPayload(err.to_string()))?;
677    let compressed_bodies: Vec<u8> = compress_docs_bytes(bodies_json.as_bytes());
678    Ok(PackedSiteBundle::new(shell_json, compressed_bodies))
679}
680
681/// Reconstructs a `DocSite` from its plaintext metadata shell JSON and `EUVZ`-compressed page bodies.
682///
683/// # Arguments
684///
685/// - `&str` - Compact plaintext `DocSite` shell JSON.
686/// - `&[u8]` - `EUVZ`-compressed `Vec<PackedPageBody>` UTF-8 JSON bytes.
687///
688/// # Returns
689///
690/// - `Result<DocSite, DocsCodecError>` - Fully hydrated `DocSite` ready for native rendering and search.
691pub fn unpack_site_bundle(
692    shell_json: &str,
693    compressed_bodies: &[u8],
694) -> Result<DocSite, DocsCodecError> {
695    let mut site: DocSite = serde_json::from_str::<DocSite>(shell_json)
696        .map_err(|err: serde_json::Error| DocsCodecError::InvalidPayload(err.to_string()))?;
697    let raw_bodies: Vec<u8> = decompress_docs_bytes(compressed_bodies)?;
698    let bodies: Vec<PackedPageBody> = serde_json::from_slice::<Vec<PackedPageBody>>(&raw_bodies)
699        .map_err(|err: serde_json::Error| DocsCodecError::InvalidPayload(err.to_string()))?;
700    if bodies.len() != site.get_pages().len() {
701        return Err(DocsCodecError::PageCountMismatch);
702    }
703    for (page, mut body) in site.get_mut_pages().iter_mut().zip(bodies) {
704        page.set_markdown_body(take(body.get_mut_markdown_body()));
705        page.set_blocks(take(body.get_mut_blocks()));
706    }
707    Ok(site)
708}