Inserts a [`TrieNode`] at the given path into the trie rooted at Self. ## Takes - `self` - The root trie node - `path` - The nibbles representation of the path to the leaf node - `node` - The node to insert at the given path - `fetcher` - The preimage fetcher for intermediate blinded nodes ## Returns - `Err(_)` - Could not insert the node at the given path in the trie. - `Ok(())` - The node was
(
&mut self,
path: &Nibbles,
value: Bytes,
fetcher: &F,
)
| 193 | /// - `Err(_)` - Could not insert the node at the given path in the trie. |
| 194 | /// - `Ok(())` - The node was successfully inserted at the given path. |
| 195 | pub fn insert<F: TrieProvider>( |
| 196 | &mut self, |
| 197 | path: &Nibbles, |
| 198 | value: Bytes, |
| 199 | fetcher: &F, |
| 200 | ) -> TrieNodeResult<()> { |
| 201 | match self { |
| 202 | Self::Empty => { |
| 203 | // If the trie node is null, insert the leaf node at the current path. |
| 204 | *self = Self::Leaf { prefix: *path, value }; |
| 205 | Ok(()) |
| 206 | } |
| 207 | Self::Leaf { prefix, value: leaf_value } => { |
| 208 | let shared_extension_nibbles = path.common_prefix_length(prefix); |
| 209 | |
| 210 | // If all nibbles are shared, update the leaf node with the new value. |
| 211 | if path == prefix { |
| 212 | *self = Self::Leaf { prefix: *prefix, value }; |
| 213 | return Ok(()); |
| 214 | } |
| 215 | |
| 216 | // Create a branch node stack containing the leaf node and the new value. |
| 217 | let mut stack = vec![Self::Empty; BRANCH_LIST_LENGTH]; |
| 218 | |
| 219 | // Insert the shortened extension into the branch stack. |
| 220 | let extension_nibble = |
| 221 | prefix.get(shared_extension_nibbles).ok_or(TrieNodeError::PathTooShort)? |
| 222 | as usize; |
| 223 | stack[extension_nibble] = Self::Leaf { |
| 224 | prefix: prefix.slice(shared_extension_nibbles + BRANCH_NODE_NIBBLES..), |
| 225 | value: leaf_value.clone(), |
| 226 | }; |
| 227 | |
| 228 | // Insert the new value into the branch stack. |
| 229 | let branch_nibble_new = |
| 230 | path.get(shared_extension_nibbles).ok_or(TrieNodeError::PathTooShort)? as usize; |
| 231 | stack[branch_nibble_new] = Self::Leaf { |
| 232 | prefix: path.slice(shared_extension_nibbles + BRANCH_NODE_NIBBLES..), |
| 233 | value, |
| 234 | }; |
| 235 | |
| 236 | // Replace the leaf node with the branch if no nibbles are shared, else create an |
| 237 | // extension. |
| 238 | if shared_extension_nibbles == 0 { |
| 239 | *self = Self::Branch { stack }; |
| 240 | } else { |
| 241 | let raw_ext_nibbles = path.slice(..shared_extension_nibbles); |
| 242 | *self = Self::Extension { |
| 243 | prefix: raw_ext_nibbles, |
| 244 | node: Box::new(Self::Branch { stack }), |
| 245 | }; |
| 246 | } |
| 247 | Ok(()) |
| 248 | } |
| 249 | Self::Extension { prefix, node } => { |
| 250 | let shared_extension_nibbles = path.common_prefix_length(prefix); |
| 251 | if shared_extension_nibbles == prefix.len() { |
| 252 | node.insert(&path.slice(shared_extension_nibbles..), value, fetcher)?; |