lib_jsl_information/source_coders/
huffman.rs1use std::cmp::Ordering;
28use std::collections::BinaryHeap;
29
30use lib_jsl_core::ErrorsJSL;
31
32const MAGIC: &[u8; 4] = b"HUF0";
33
34#[derive(Clone, Debug)]
35enum HuffmanNode {
36 Leaf { symbol: u8 },
37 Internal { left: Box<HuffmanNode>, right: Box<HuffmanNode> },
38}
39
40#[derive(Clone, Debug)]
41struct HeapEntry {
42 frequency: u32,
43 min_symbol: u8,
44 node: HuffmanNode,
45}
46
47impl PartialEq for HeapEntry {
48 fn eq(&self, other: &Self) -> bool {
49 self.frequency == other.frequency && self.min_symbol == other.min_symbol
50 }
51}
52
53impl Eq for HeapEntry {}
54
55impl PartialOrd for HeapEntry {
56 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
57 Some(self.cmp(other))
58 }
59}
60
61impl Ord for HeapEntry {
62 fn cmp(&self, other: &Self) -> Ordering {
63 other
67 .frequency
68 .cmp(&self.frequency)
69 .then_with(|| other.min_symbol.cmp(&self.min_symbol))
70 }
71}
72
73pub fn huffman_compress(input: &[u8]) -> Vec<u8> {
75 try_huffman_compress(input).unwrap_or_default()
76}
77
78pub fn try_huffman_compress(input: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
80 if input.len() > u64::MAX as usize {
81 return Err(ErrorsJSL::InvalidInputRange("Huffman input is too large to encode its original length."));
82 }
83
84 let frequencies = build_frequency_table(input);
85 let symbol_count = frequencies.iter().filter(|&&count| count > 0).count();
86
87 if symbol_count > u16::MAX as usize {
88 return Err(ErrorsJSL::InvalidInputRange("Huffman frequency table has too many distinct symbols."));
89 }
90
91 let mut output = Vec::new();
92 output.extend_from_slice(MAGIC);
93 output.extend_from_slice(&(input.len() as u64).to_le_bytes());
94 output.extend_from_slice(&(symbol_count as u16).to_le_bytes());
95
96 for (symbol, &frequency) in frequencies.iter().enumerate() {
98 if frequency > 0 {
99 output.push(symbol as u8);
100 output.extend_from_slice(&frequency.to_le_bytes());
101 }
102 }
103
104 if input.is_empty() {
105 return Ok(output);
106 }
107
108 let root = build_tree_from_frequencies(&frequencies)?;
109 if symbol_count == 1 {
110 return Ok(output);
113 }
114 let mut codes = vec![Vec::new(); 256];
115 let mut current_path = Vec::new();
116 build_code_table(&root, &mut current_path, &mut codes);
117
118 let mut current_byte = 0u8;
121 let mut bit_count = 0u8;
122
123 for &byte in input {
124 for &bit in &codes[byte as usize] {
125 current_byte <<= 1;
126 if bit {
127 current_byte |= 1;
128 }
129 bit_count += 1;
130
131 if bit_count == 8 {
132 output.push(current_byte);
133 current_byte = 0;
134 bit_count = 0;
135 }
136 }
137 }
138
139 if bit_count > 0 {
142 current_byte <<= 8 - bit_count;
143 output.push(current_byte);
144 }
145
146 Ok(output)
147}
148
149pub fn huffman_decompress(input: &[u8]) -> Vec<u8> {
151 try_huffman_decompress(input).unwrap_or_default()
152}
153
154pub fn try_huffman_decompress(input: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
156 if input.len() < MAGIC.len() || &input[..MAGIC.len()] != MAGIC {
157 return Err(ErrorsJSL::InvalidInputRange("Compressed payload is missing the Huffman header."));
158 }
159
160 let mut cursor = MAGIC.len();
161
162 if cursor + 8 + 2 > input.len() {
163 return Err(ErrorsJSL::InvalidInputRange("Huffman header is truncated before length or symbol count."));
164 }
165
166 let original_len = u64::from_le_bytes(
167 input[cursor..cursor + 8]
168 .try_into()
169 .map_err(|_| ErrorsJSL::RuntimeError("Failed to parse Huffman original length field."))?,
170 ) as usize;
171 cursor += 8;
172
173 let symbol_count = u16::from_le_bytes(
174 input[cursor..cursor + 2]
175 .try_into()
176 .map_err(|_| ErrorsJSL::RuntimeError("Failed to parse Huffman symbol count field."))?,
177 ) as usize;
178 cursor += 2;
179
180 let table_bytes = symbol_count
181 .checked_mul(5)
182 .ok_or(ErrorsJSL::InvalidInputRange("Huffman frequency table size overflowed."))?;
183 if cursor + table_bytes > input.len() {
184 return Err(ErrorsJSL::InvalidInputRange("Huffman frequency table extends beyond the compressed payload."));
185 }
186
187 let mut frequencies = [0u32; 256];
188 for _ in 0..symbol_count {
189 let symbol = input[cursor];
190 let frequency = u32::from_le_bytes(
191 input[cursor + 1..cursor + 5]
192 .try_into()
193 .map_err(|_| ErrorsJSL::RuntimeError("Failed to parse Huffman symbol frequency field."))?,
194 );
195 cursor += 5;
196
197 if frequency == 0 {
198 return Err(ErrorsJSL::InvalidInputRange("Huffman frequency table cannot contain zero-frequency entries."));
199 }
200 if frequencies[symbol as usize] != 0 {
201 return Err(ErrorsJSL::InvalidInputRange("Huffman frequency table contains duplicate symbol entries."));
202 }
203
204 frequencies[symbol as usize] = frequency;
205 }
206
207 if original_len == 0 {
208 return Ok(Vec::new());
209 }
210
211 let total_frequency: usize = frequencies.iter().map(|&count| count as usize).sum();
212 if total_frequency != original_len {
213 return Err(ErrorsJSL::InvalidInputRange("Huffman frequency table does not match the stored original length."));
214 }
215
216 let root = build_tree_from_frequencies(&frequencies)?;
217
218 if let HuffmanNode::Leaf { symbol } = root {
222 return Ok(vec![symbol; original_len]);
223 }
224
225 let bitstream = &input[cursor..];
226 let mut output = Vec::with_capacity(original_len);
227 let mut current = &root;
228
229 for &packed_byte in bitstream {
230 for shift in (0..8).rev() {
231 let bit_is_set = ((packed_byte >> shift) & 1) == 1;
234
235 current = match current {
236 HuffmanNode::Leaf { symbol } => {
237 output.push(*symbol);
241 if output.len() == original_len {
242 return Ok(output);
243 }
244
245 descend_from_root(&root, bit_is_set)?
246 }
247 HuffmanNode::Internal { left, right } => {
248 if bit_is_set { right.as_ref() } else { left.as_ref() }
249 }
250 };
251
252 if let HuffmanNode::Leaf { symbol } = current {
253 output.push(*symbol);
256 if output.len() == original_len {
257 return Ok(output);
258 }
259 current = &root;
260 }
261 }
262 }
263
264 Err(ErrorsJSL::InvalidInputRange("Huffman bitstream ended before the declared number of output bytes was reconstructed."))
265}
266
267fn descend_from_root(root: &HuffmanNode, bit_is_set: bool) -> Result<&HuffmanNode, ErrorsJSL> {
268 match root {
269 HuffmanNode::Internal { left, right } => {
270 if bit_is_set { Ok(right.as_ref()) } else { Ok(left.as_ref()) }
271 }
272 HuffmanNode::Leaf { .. } => Err(ErrorsJSL::RuntimeError("Tried to descend from a leaf-only Huffman tree.")),
273 }
274}
275
276fn build_frequency_table(input: &[u8]) -> [u32; 256] {
277 let mut frequencies = [0u32; 256];
278 for &byte in input {
279 frequencies[byte as usize] = frequencies[byte as usize].saturating_add(1);
280 }
281 frequencies
282}
283
284fn build_tree_from_frequencies(frequencies: &[u32; 256]) -> Result<HuffmanNode, ErrorsJSL> {
285 let mut heap = BinaryHeap::new();
286
287 for (symbol, &frequency) in frequencies.iter().enumerate() {
288 if frequency > 0 {
289 heap.push(HeapEntry {
291 frequency,
292 min_symbol: symbol as u8,
293 node: HuffmanNode::Leaf { symbol: symbol as u8 },
294 });
295 }
296 }
297
298 if heap.is_empty() {
299 return Err(ErrorsJSL::InvalidInputRange("Cannot build a Huffman tree from an empty frequency table."));
300 }
301
302 while heap.len() > 1 {
304 let left = heap.pop().ok_or(ErrorsJSL::RuntimeError("Huffman heap unexpectedly emptied while building the tree."))?;
307 let right = heap.pop().ok_or(ErrorsJSL::RuntimeError("Huffman heap unexpectedly emptied while building the tree."))?;
308
309 heap.push(HeapEntry {
310 frequency: left.frequency.saturating_add(right.frequency),
311 min_symbol: left.min_symbol.min(right.min_symbol),
312 node: HuffmanNode::Internal {
313 left: Box::new(left.node),
314 right: Box::new(right.node),
315 },
316 });
317 }
318 heap.pop()
321 .map(|entry| entry.node)
322 .ok_or(ErrorsJSL::RuntimeError("Failed to extract the final Huffman tree from the heap."))
323}
324
325fn build_code_table(node: &HuffmanNode, current_path: &mut Vec<bool>, codes: &mut [Vec<bool>]) {
326 match node {
327 HuffmanNode::Leaf { symbol } => {
328 if current_path.is_empty() {
332 current_path.push(false);
333 codes[*symbol as usize] = current_path.clone();
334 current_path.pop();
335 } else {
336 codes[*symbol as usize] = current_path.clone();
337 }
338 }
339 HuffmanNode::Internal { left, right } => {
340 current_path.push(false);
342 build_code_table(left, current_path, codes);
343 current_path.pop();
344
345 current_path.push(true);
347 build_code_table(right, current_path, codes);
348 current_path.pop();
349 }
350 }
351}
352
353#[cfg(test)]
354mod tests {
355 use super::*;
356
357 #[test]
358 fn round_trip_empty_input() {
359 let payload = b"";
360 let compressed = try_huffman_compress(payload).unwrap();
361 let decompressed = try_huffman_decompress(&compressed).unwrap();
362
363 assert_eq!(decompressed, payload);
364 assert_eq!(&compressed[..MAGIC.len()], MAGIC);
365 }
366
367 #[test]
368 fn round_trip_repeated_text() {
369 let payload = b"this is an example of a huffman tree";
370 let compressed = try_huffman_compress(payload).unwrap();
371 let decompressed = try_huffman_decompress(&compressed).unwrap();
372
373 assert_eq!(decompressed, payload);
374 }
375
376 #[test]
377 fn round_trip_binary_data() {
378 let payload = [0u8, 0, 0, 1, 1, 2, 3, 5, 8, 13, 21, 21, 21, 34];
379 let compressed = try_huffman_compress(&payload).unwrap();
380 let decompressed = try_huffman_decompress(&compressed).unwrap();
381
382 assert_eq!(decompressed, payload);
383 }
384
385 #[test]
386 fn round_trip_single_symbol_input() {
387 let payload = [42u8; 1024];
388 let compressed = try_huffman_compress(&payload).unwrap();
389 let decompressed = try_huffman_decompress(&compressed).unwrap();
390
391 assert_eq!(decompressed, payload);
392 assert_eq!(compressed.len(), 4 + 8 + 2 + 5);
394 }
395
396 #[test]
397 fn round_trip_kjv_text_asset() {
398 let payload = include_bytes!("../../test_assets/kjv.txt");
399 let compressed = try_huffman_compress(payload).unwrap();
400 let decompressed = try_huffman_decompress(&compressed).unwrap();
401
402 assert_eq!(decompressed, payload);
403 }
404
405 #[test]
406 fn malformed_stream_returns_error() {
407 let malformed = vec![b'H', b'U', b'F', b'0', 0x01];
408 let result = try_huffman_decompress(&malformed);
409
410 assert!(result.is_err());
411 }
412
413 #[test]
414 fn wrapper_returns_empty_on_malformed_stream() {
415 let malformed = vec![0x01, 0x02, 0x03];
416 let decompressed = huffman_decompress(&malformed);
417
418 assert!(decompressed.is_empty());
419 }
420}