MCPcopy Create free account
hub / github.com/TechHara/gunzip / new

Method new

src/codebook.rs:12–58  ·  view source on GitHub ↗
(lengths: impl IntoIterator<Item = u32>, len: usize)

Source from the content-addressed store, hash-verified

10
11impl CodeBook {
12 pub fn new(lengths: impl IntoIterator<Item = u32>, len: usize) -> Result<Self> {
13 let err = Err(Error::InvalidCodeLengths);
14
15 // follow RFC1951 https://www.rfc-editor.org/rfc/rfc1951#ref-1
16 if len == 0 || len > MAX_LL_SYMBOL as usize + 1 {
17 return err;
18 }
19
20 let mut tree = Vec::with_capacity(len);
21 let mut max_len = 0; // max(lengths)
22
23 // step 1
24 // # of codes having bitcode length count
25 let mut bl_count = [0; MAX_CODELENGTH as usize + 1];
26 for l in lengths {
27 bl_count[l as usize] += 1;
28 tree.push((0, l));
29 max_len = max_len.max(l);
30 }
31
32 if max_len > MAX_CODELENGTH {
33 return err;
34 }
35
36 // step 2
37 let mut next_code = [0; MAX_CODELENGTH as usize + 1];
38 let mut code = 0;
39 bl_count[0] = 0; // this is a must!!
40 for bits in 1..=max_len as usize {
41 code = (code + bl_count[bits - 1]) << 1;
42 next_code[bits] = code;
43 }
44
45 // step 3
46 for pair in &mut tree {
47 let len = pair.1 as usize;
48 if len != 0 {
49 pair.0 = next_code[len];
50 next_code[len] += 1;
51 }
52 }
53
54 Ok(Self {
55 tree,
56 max_length: max_len,
57 })
58 }
59
60 /// maximum number of bits within the codebook
61 pub fn max_length(&self) -> u32 {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected