| 1 |
use alloc::vec::Vec; |
| 2 |
|
| 3 |
/// Converts a series of Huffman tree bitlengths, to the bit values of the symbols. |
| 4 |
pub fn lengths_to_symbols(lengths: &[u32], max_bits: u32) -> Vec<u32> { |
| 5 |
let mut bl_count = vec![0; (max_bits + 1) as usize]; |
| 6 |
let mut next_code = vec![0; (max_bits + 1) as usize]; |
| 7 |
let n = lengths.len(); |
| 8 |
|
| 9 |
let mut symbols = vec![0; n]; |
| 10 |
|
| 11 |
// 1) Count the number of codes for each code length. Let bl_count[N] be the |
| 12 |
// number of codes of length N, N >= 1. */ |
| 13 |
for &length in lengths { |
| 14 |
assert!(length <= max_bits); |
| 15 |
bl_count[length as usize] += 1; |
| 16 |
} |
| 17 |
// 2) Find the numerical value of the smallest code for each code length. |
| 18 |
let mut code = 0; |
| 19 |
bl_count[0] = 0; |
| 20 |
for bits in 1..=max_bits { |
| 21 |
code = (code + bl_count[(bits - 1) as usize]) << 1; |
| 22 |
next_code[bits as usize] = code; |
| 23 |
} |
| 24 |
// 3) Assign numerical values to all codes, using consecutive values for all |
| 25 |
// codes of the same length with the base values determined at step 2. |
| 26 |
for i in 0..n { |
| 27 |
let len = lengths[i] as usize; |
| 28 |
if len != 0 { |
| 29 |
symbols[i] = next_code[len]; |
| 30 |
next_code[len] += 1; |
| 31 |
} |
| 32 |
} |
| 33 |
symbols |
| 34 |
} |