alloy_trie/proof/
proof_nodes.rs

1use crate::{HashMap, Nibbles};
2use alloy_primitives::Bytes;
3use core::ops::Deref;
4
5use alloc::vec::Vec;
6
7/// A wrapper struct for trie node key to RLP encoded trie node.
8#[derive(PartialEq, Eq, Clone, Default, Debug)]
9#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
10pub struct ProofNodes(HashMap<Nibbles, Bytes>);
11
12impl Deref for ProofNodes {
13    type Target = HashMap<Nibbles, Bytes>;
14
15    fn deref(&self) -> &Self::Target {
16        &self.0
17    }
18}
19
20impl FromIterator<(Nibbles, Bytes)> for ProofNodes {
21    fn from_iter<T: IntoIterator<Item = (Nibbles, Bytes)>>(iter: T) -> Self {
22        Self(HashMap::from_iter(iter))
23    }
24}
25
26impl Extend<(Nibbles, Bytes)> for ProofNodes {
27    fn extend<T: IntoIterator<Item = (Nibbles, Bytes)>>(&mut self, iter: T) {
28        self.0.extend(iter);
29    }
30}
31
32impl ProofNodes {
33    /// Return iterator over proof nodes that match the target.
34    pub fn matching_nodes_iter<'a>(
35        &'a self,
36        target: &'a Nibbles,
37    ) -> impl Iterator<Item = (&'a Nibbles, &'a Bytes)> {
38        self.0.iter().filter(|(key, _)| target.starts_with(key))
39    }
40
41    /// Return the vec of proof nodes that match the target.
42    pub fn matching_nodes(&self, target: &Nibbles) -> Vec<(Nibbles, Bytes)> {
43        self.matching_nodes_iter(target).map(|(key, node)| (key.clone(), node.clone())).collect()
44    }
45
46    /// Return the sorted vec of proof nodes that match the target.
47    pub fn matching_nodes_sorted(&self, target: &Nibbles) -> Vec<(Nibbles, Bytes)> {
48        let mut nodes = self.matching_nodes(target);
49        nodes.sort_unstable_by(|a, b| a.0.cmp(&b.0));
50        nodes
51    }
52
53    /// Insert the RLP encoded trie node at key.
54    pub fn insert(&mut self, key: Nibbles, node: Bytes) -> Option<Bytes> {
55        self.0.insert(key, node)
56    }
57
58    /// Return the sorted vec of all proof nodes.
59    pub fn nodes_sorted(&self) -> Vec<(Nibbles, Bytes)> {
60        let mut nodes = Vec::from_iter(self.0.iter().map(|(k, v)| (k.clone(), v.clone())));
61        nodes.sort_unstable_by(|a, b| a.0.cmp(&b.0));
62        nodes
63    }
64
65    /// Convert into sorted vec of all proof nodes.
66    pub fn into_nodes_sorted(self) -> Vec<(Nibbles, Bytes)> {
67        let mut nodes = Vec::from_iter(self.0);
68        nodes.sort_unstable_by(|a, b| a.0.cmp(&b.0));
69        nodes
70    }
71
72    /// Convert wrapper struct into inner map.
73    pub fn into_inner(self) -> HashMap<Nibbles, Bytes> {
74        self.0
75    }
76
77    /// Extends with the elements of another `ProofNodes`.
78    pub fn extend_from(&mut self, other: Self) {
79        self.extend(other.0);
80    }
81}