Skip to main content

bpack/unpack/
node.rs

1use crate::set_bit_16;
2use crate::unpack::Table;
3
4#[derive(Clone, Debug)]
5pub struct Node {
6    pub value: Option<u8>,
7    left_child: Option<Box<Node>>,
8    right_child: Option<Box<Node>>,
9}
10
11impl Node {
12    pub fn new_leaf(v: u8) -> Self {
13        Node {
14            value: Some(v),
15            left_child: None,
16            right_child: None,
17        }
18    }
19
20    pub fn new_non_leaf(l: Node, r: Node) -> Self {
21        Node {
22            value: None,
23            left_child: Some(Box::new(l)),
24            right_child: Some(Box::new(r)),
25        }
26    }
27
28    pub fn dfs(&self, counter: &mut i8, bits: u16, table: &mut Table) {
29        if let Some(node) = &self.left_child {
30            *counter += 1;
31
32            let idx = (!(*counter - 16) + 1) as u16;
33            let code = set_bit_16(bits, idx, 0);
34
35            node.dfs(counter, code, table);
36        }
37
38        // go right
39        if let Some(node) = &self.right_child {
40            *counter += 1;
41
42            let idx = (!(*counter - 16) + 1) as u16;
43            let code = set_bit_16(bits, idx, 1);
44
45            node.dfs(counter, code, table);
46        }
47
48        // do the logic
49        if let Some(val) = self.value {
50            table.set(val, bits, *counter);
51        }
52        *counter -= 1;
53        // println!("my value -> {:?}", self.value);
54    }
55
56
57}