| 1 |
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 2 |
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 3 |
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 4 |
// option. This file may not be copied, modified, or distributed |
| 5 |
// except according to those terms. |
| 6 |
|
| 7 |
use std::sync::OnceLock; |
| 8 |
|
| 9 |
use crate::huffman_table::HUFFMAN_TABLE; |
| 10 |
|
| 11 |
// Since we're encoding the table length as a u16, we need to ensure that it fits. |
| 12 |
static_assertions::const_assert!(HUFFMAN_TABLE.len() <= u16::MAX as usize); |
| 13 |
|
| 14 |
pub struct HuffmanDecoderNode { |
| 15 |
pub next: [Option<Box<HuffmanDecoderNode>>; 2], |
| 16 |
pub value: Option<u16>, |
| 17 |
} |
| 18 |
|
| 19 |
pub fn huffman_decoder_root() -> &'static HuffmanDecoderNode { |
| 20 |
static ROOT: OnceLock<HuffmanDecoderNode> = OnceLock::new(); |
| 21 |
ROOT.get_or_init(|| make_huffman_tree(0, 0)) |
| 22 |
} |
| 23 |
|
| 24 |
fn make_huffman_tree(prefix: u32, len: u8) -> HuffmanDecoderNode { |
| 25 |
let mut found = false; |
| 26 |
let mut next = [None, None]; |
| 27 |
for (i, iter) in HUFFMAN_TABLE.iter().enumerate() { |
| 28 |
if iter.len <= len { |
| 29 |
continue; |
| 30 |
} |
| 31 |
if (iter.val >> (iter.len - len)) != prefix { |
| 32 |
continue; |
| 33 |
} |
| 34 |
|
| 35 |
found = true; |
| 36 |
if iter.len == len + 1 { |
| 37 |
// This is a leaf |
| 38 |
let bit = usize::try_from(iter.val & 1).expect("u32 fits in usize"); |
| 39 |
next[bit] = Some(Box::new(HuffmanDecoderNode { |
| 40 |
next: [None, None], |
| 41 |
#[expect( |
| 42 |
clippy::cast_possible_truncation, |
| 43 |
reason = "We've checked this in a `const_assert!` above." |
| 44 |
)] |
| 45 |
value: Some(i as u16), |
| 46 |
})); |
| 47 |
if next[bit ^ 1].is_some() { |
| 48 |
return HuffmanDecoderNode { next, value: None }; |
| 49 |
} |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
if found { |
| 54 |
if next[0].is_none() { |
| 55 |
next[0] = Some(Box::new(make_huffman_tree(prefix << 1, len + 1))); |
| 56 |
} |
| 57 |
if next[1].is_none() { |
| 58 |
next[1] = Some(Box::new(make_huffman_tree((prefix << 1) + 1, len + 1))); |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
HuffmanDecoderNode { next, value: None } |
| 63 |
} |