Skip to main content

trie_db/
recorder.rs

1// Copyright 2017, 2021 Parity Technologies
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Trie query recorder.
16
17use crate::{rstd::vec::Vec, RecordedForKey, TrieAccess, TrieHash, TrieLayout, TrieRecorder};
18use hashbrown::HashMap;
19
20/// The record of a visited node.
21#[cfg_attr(feature = "std", derive(Debug))]
22#[derive(PartialEq, Eq, Clone)]
23pub struct Record<HO> {
24	/// The hash of the node.
25	pub hash: HO,
26	/// The data representing the node.
27	pub data: Vec<u8>,
28}
29
30/// Records trie nodes as they pass it.
31#[cfg_attr(feature = "std", derive(Debug))]
32pub struct Recorder<L: TrieLayout> {
33	nodes: Vec<Record<TrieHash<L>>>,
34	recorded_keys: HashMap<Vec<u8>, RecordedForKey>,
35}
36
37impl<L: TrieLayout> Default for Recorder<L> {
38	fn default() -> Self {
39		Recorder::new()
40	}
41}
42
43impl<L: TrieLayout> Recorder<L> {
44	/// Create a new `Recorder` which records all given nodes.
45	pub fn new() -> Self {
46		Self { nodes: Default::default(), recorded_keys: Default::default() }
47	}
48
49	/// Drain all visited records.
50	pub fn drain(&mut self) -> Vec<Record<TrieHash<L>>> {
51		self.recorded_keys.clear();
52		crate::rstd::mem::take(&mut self.nodes)
53	}
54}
55
56impl<L: TrieLayout> TrieRecorder<TrieHash<L>> for Recorder<L> {
57	fn record<'a>(&mut self, access: TrieAccess<'a, TrieHash<L>>) {
58		match access {
59			TrieAccess::EncodedNode { hash, encoded_node, .. } => {
60				self.nodes.push(Record { hash, data: encoded_node.to_vec() });
61			},
62			TrieAccess::NodeOwned { hash, node_owned, .. } => {
63				self.nodes.push(Record { hash, data: node_owned.to_encoded::<L::Codec>() });
64			},
65			TrieAccess::Value { hash, value, full_key } => {
66				self.nodes.push(Record { hash, data: value.to_vec() });
67				self.recorded_keys.entry(full_key.to_vec()).insert(RecordedForKey::Value);
68			},
69			TrieAccess::Hash { full_key } => {
70				self.recorded_keys.entry(full_key.to_vec()).or_insert(RecordedForKey::Hash);
71			},
72			TrieAccess::NonExisting { full_key } => {
73				// We handle the non existing value/hash like having recorded the value.
74				self.recorded_keys.entry(full_key.to_vec()).insert(RecordedForKey::Value);
75			},
76		}
77	}
78
79	fn trie_nodes_recorded_for_key(&self, key: &[u8]) -> RecordedForKey {
80		self.recorded_keys.get(key).copied().unwrap_or(RecordedForKey::None)
81	}
82}