Skip to content

Commit

Permalink
Add get function
Browse files Browse the repository at this point in the history
  • Loading branch information
morph-dev committed Oct 5, 2023
1 parent 81ec064 commit 7cfd68f
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 0 deletions.
7 changes: 7 additions & 0 deletions merkle/src/nodes/branch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@ impl BranchNode {
nodes_length + value_length
}

pub fn get(&self, path: &Nibbles, db: &dyn Db<B256, Vec<u8>>) -> Option<Vec<u8>> {
match path.first() {
None => self.value.clone(),
Some(nibble) => self.nodes[nibble].clone().get(&path.skip_head(1), db),
}
}

pub fn update(&self, path: Nibbles, value: Vec<u8>, db: &mut dyn Db<B256, Vec<u8>>) -> Node {
let mut nodes = self.nodes.clone();

Expand Down
9 changes: 9 additions & 0 deletions merkle/src/nodes/extension.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,15 @@ pub struct ExtensionNode {
}

impl ExtensionNode {
pub fn get(&self, path: &Nibbles, db: &dyn Db<B256, Vec<u8>>) -> Option<Vec<u8>> {
let common_prefix = self.path.common_prefix(path);
if self.path.len() == common_prefix {
self.node.clone().get(&path.skip_head(common_prefix), db)
} else {
None
}
}

pub fn update(&self, path: Nibbles, value: Vec<u8>, db: &mut dyn Db<B256, Vec<u8>>) -> Node {
let common_prefix = self.path.common_prefix(&path);

Expand Down
8 changes: 8 additions & 0 deletions merkle/src/nodes/leaf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ pub struct LeafNode {
}

impl LeafNode {
pub fn get(&self, path: &Nibbles, _db: &dyn Db<B256, Vec<u8>>) -> Option<Vec<u8>> {
if self.path[..] == path[..] {
Some(self.value.clone())
} else {
None
}
}

pub fn update(&self, path: Nibbles, value: Vec<u8>, db: &mut dyn Db<B256, Vec<u8>>) -> Node {
let common_prefix = self.path.common_prefix(&path);
// Path is the same
Expand Down
14 changes: 14 additions & 0 deletions merkle/src/nodes/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,20 @@ impl From<Node> for NodeRef {
}

impl NodeRef {
pub fn get(&mut self, path: &Nibbles, db: &dyn Db<B256, Vec<u8>>) -> Option<Vec<u8>> {
self.load(db);

match &self.node {
None => panic!("Node should be present"),
Some(node) => match node.as_ref() {
Node::Nil => None,
Node::Branch(branch) => branch.get(path, db),
Node::Extension(extension) => extension.get(path, db),
Node::Leaf(leaf) => leaf.get(path, db),
},
}
}

pub fn update(
&mut self,
path: Nibbles,
Expand Down

0 comments on commit 7cfd68f

Please sign in to comment.