tetsy_trie_db/
recorder.rs

1// Copyright 2017, 2020 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;
18
19/// A record of a visited node.
20#[cfg_attr(feature = "std", derive(Debug))]
21#[derive(PartialEq, Eq, Clone)]
22pub struct Record<HO> {
23	/// The depth of this node.
24	pub depth: u32,
25
26	/// The raw data of the node.
27	pub data: Vec<u8>,
28
29	/// The hash of the data.
30	pub hash: HO,
31}
32
33/// Records trie nodes as they pass it.
34#[cfg_attr(feature = "std", derive(Debug))]
35pub struct Recorder<HO> {
36	nodes: Vec<Record<HO>>,
37	min_depth: u32,
38}
39
40impl<HO: Copy> Default for Recorder<HO> {
41	fn default() -> Self {
42		Recorder::new()
43	}
44}
45
46impl<HO: Copy> Recorder<HO> {
47	/// Create a new `Recorder` which records all given nodes.
48	#[inline]
49	pub fn new() -> Self {
50		Recorder::with_depth(0)
51	}
52
53	/// Create a `Recorder` which only records nodes beyond a given depth.
54	pub fn with_depth(depth: u32) -> Self {
55		Recorder {
56			nodes: Vec::new(),
57			min_depth: depth,
58		}
59	}
60
61	/// Record a visited node, given its hash, data, and depth.
62	pub fn record(&mut self, hash: &HO, data: &[u8], depth: u32) {
63		if depth >= self.min_depth {
64			self.nodes.push(Record {
65				depth,
66				data: data.into(),
67				hash: *hash,
68			})
69		}
70	}
71
72	/// Drain all visited records.
73	pub fn drain(&mut self) -> Vec<Record<HO>> {
74		crate::rstd::mem::replace(&mut self.nodes, Vec::new())
75	}
76}