forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

huffman.rs160 lines, 5.6 KiBHistoryRawDownload
1//! Canonical Huffman decoding through a two-level lookup table.
2//!
3//! A code is at most fifteen bits, so one flat 32768-entry table would decode
4//! in a single load — and cost more to build than most Matroska blocks cost to
5//! inflate. Instead the first `root_bits` bits index a small root table; the
6//! few codes longer than that point at a sub-table indexed by their remaining
7//! bits. Both levels are one indexed load, so no code is ever walked bit by bit.
8//!
9//! Codes are stored bit-reversed, because DEFLATE packs a code high bit first
10//! into a stream that is read low bit first: reversing at build time turns
11//! decoding into "peek `root_bits`, index".
12
13use crate::Error;
14use crate::bits::Bits;
15
16/// Longest code RFC 1951 permits.
17pub(crate) const MAX_BITS: u32 = 15;
18
19/// Entry layout: `0` is "no code here"; otherwise bit 31 marks a sub-table
20/// link (`sub_bits` in 24..28, offset in 0..24) and a leaf holds the symbol in
21/// 4..20 with its code length in 0..4.
22const SUB_FLAG: u32 = 1 << 31;
23
24pub(crate) struct Table {
25 root_bits: u32,
26 root: Vec<u32>,
27 subs: Vec<u32>,
28}
29
30impl Table {
31 /// Build from one code length per symbol (`0` = symbol absent).
32 ///
33 /// `root_bits` is the first-level width; codes longer than it get a
34 /// sub-table. An over-subscribed set is always corrupt. An incomplete one
35 /// is corrupt too, except for the single-code case RFC 1951 allows for a
36 /// distance tree that a stream never actually uses.
37 pub(crate) fn new(lengths: &[u16], root_bits: u32) -> Result<Table, Error> {
38 let mut count = [0u32; MAX_BITS as usize + 1];
39 let mut max_len = 0;
40 for &l in lengths {
41 if l as u32 > MAX_BITS {
42 return Err(Error::corrupt("Huffman code length above 15"));
43 }
44 if l > 0 {
45 count[l as usize] += 1;
46 max_len = max_len.max(l as u32);
47 }
48 }
49 if max_len == 0 {
50 // No symbols at all: legal to declare, corrupt to use.
51 return Ok(Table {
52 root_bits: 1,
53 root: vec![0; 2],
54 subs: Vec::new(),
55 });
56 }
57
58 let mut left = 1i64;
59 let mut total = 0u32;
60 for &at_length in count.iter().skip(1) {
61 left = (left << 1) - at_length as i64;
62 if left < 0 {
63 return Err(Error::corrupt("over-subscribed Huffman code"));
64 }
65 total += at_length;
66 }
67 if left > 0 && total > 1 {
68 return Err(Error::corrupt("incomplete Huffman code"));
69 }
70
71 let mut next = [0u32; MAX_BITS as usize + 2];
72 let mut code = 0u32;
73 for l in 1..=MAX_BITS as usize {
74 code = (code + count[l - 1]) << 1;
75 next[l] = code;
76 }
77 let mut codes = vec![0u32; lengths.len()];
78 for (sym, &l) in lengths.iter().enumerate() {
79 if l > 0 {
80 codes[sym] = next[l as usize];
81 next[l as usize] += 1;
82 }
83 }
84
85 let root_bits = root_bits.min(max_len).max(1);
86 let root_mask = (1u32 << root_bits) - 1;
87 let mut root = vec![0u32; 1 << root_bits];
88 let mut subs = Vec::new();
89
90 // How wide each sub-table has to be, before anything is written into it.
91 let mut sub_len = vec![0u32; 1 << root_bits];
92 for (sym, &l) in lengths.iter().enumerate() {
93 let l = l as u32;
94 if l > root_bits {
95 let prefix = (reverse(codes[sym], l) & root_mask) as usize;
96 sub_len[prefix] = sub_len[prefix].max(l - root_bits);
97 }
98 }
99 for (prefix, &bits) in sub_len.iter().enumerate() {
100 if bits > 0 {
101 let offset = subs.len() as u32;
102 subs.resize(subs.len() + (1 << bits), 0);
103 root[prefix] = SUB_FLAG | (bits << 24) | offset;
104 }
105 }
106
107 for (sym, &l) in lengths.iter().enumerate() {
108 let l = l as u32;
109 if l == 0 {
110 continue;
111 }
112 let rev = reverse(codes[sym], l);
113 let leaf = ((sym as u32) << 4) | l;
114 if l <= root_bits {
115 let mut i = rev;
116 while i < 1 << root_bits {
117 root[i as usize] = leaf;
118 i += 1 << l;
119 }
120 } else {
121 let link = root[(rev & root_mask) as usize];
122 let bits = (link >> 24) & 0xf;
123 let offset = (link & 0x00ff_ffff) as usize;
124 let mut i = rev >> root_bits;
125 while i < 1 << bits {
126 subs[offset + i as usize] = leaf;
127 i += 1 << (l - root_bits);
128 }
129 }
130 }
131
132 Ok(Table {
133 root_bits,
134 root,
135 subs,
136 })
137 }
138
139 /// Decode one symbol, consuming exactly its code.
140 #[inline]
141 pub(crate) fn decode(&self, bits: &mut Bits) -> Result<u16, Error> {
142 bits.refill();
143 let mut entry = self.root[bits.peek(self.root_bits) as usize];
144 if entry & SUB_FLAG != 0 {
145 let width = (entry >> 24) & 0xf;
146 let offset = (entry & 0x00ff_ffff) as usize;
147 entry = self.subs[offset + bits.peek_at(self.root_bits, width) as usize];
148 }
149 if entry == 0 {
150 return Err(Error::corrupt("Huffman code not in the tree"));
151 }
152 bits.consume(entry & 0xf)?;
153 Ok((entry >> 4) as u16)
154 }
155}
156
157/// The low `n` bits of `code`, reversed.
158fn reverse(code: u32, n: u32) -> u32 {
159 code.reverse_bits() >> (32 - n)
160}