1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
use crate::hasher::Hasher;
#[derive(Debug, Clone)]
pub enum NodeType {
Leaf,
Internal(Box<Node>, Box<Node>),
}
impl NodeType {
pub fn left(&self) -> Option<&Node> {
match self {
NodeType::Leaf => None,
NodeType::Internal(l, _) => Some(l),
}
}
pub fn right(&self) -> Option<&Node> {
match self {
NodeType::Leaf => None,
NodeType::Internal(_, r) => Some(r),
}
}
}
#[derive(Debug, Clone)]
pub struct Node {
hash: String,
kind: NodeType,
}
impl Node {
pub fn new_leaf<T: ToString>(hasher: &dyn Hasher, data: T) -> Self {
let hash = hasher.hash(&data.to_string());
Self {
hash,
kind: NodeType::Leaf,
}
}
pub fn new_internal(hasher: &dyn Hasher, left: Node, right: Node) -> Self {
let combined = format!("{}{}", left.hash, right.hash);
let hash = hasher.hash(&combined);
Self {
hash,
kind: NodeType::Internal(Box::new(left), Box::new(right)),
}
}
pub fn hash(&self) -> &str {
&self.hash
}
pub fn kind(&self) -> &NodeType {
&self.kind
}
}
|