referrerpolicy=no-referrer-when-downgrade

node_bench/
simple_trie.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19use std::{collections::HashMap, sync::Arc};
20
21use hash_db::{AsHashDB, HashDB, Hasher as _, Prefix};
22use kvdb::KeyValueDB;
23use node_primitives::Hash;
24use sp_trie::DBValue;
25
26pub type Hasher = sp_core::Blake2Hasher;
27
28/// Immutable generated trie database with root.
29pub struct SimpleTrie<'a> {
30	pub db: Arc<dyn KeyValueDB>,
31	pub overlay: &'a mut HashMap<Vec<u8>, Option<Vec<u8>>>,
32}
33
34impl<'a> AsHashDB<Hasher, DBValue> for SimpleTrie<'a> {
35	fn as_hash_db(&self) -> &dyn hash_db::HashDB<Hasher, DBValue> {
36		self
37	}
38
39	fn as_hash_db_mut<'b>(&'b mut self) -> &'b mut (dyn HashDB<Hasher, DBValue> + 'b) {
40		&mut *self
41	}
42}
43
44impl<'a> HashDB<Hasher, DBValue> for SimpleTrie<'a> {
45	fn get(&self, key: &Hash, prefix: Prefix) -> Option<DBValue> {
46		let key = sp_trie::prefixed_key::<Hasher>(key, prefix);
47		if let Some(value) = self.overlay.get(&key) {
48			return value.clone()
49		}
50		self.db.get(0, &key).expect("Database backend error")
51	}
52
53	fn contains(&self, hash: &Hash, prefix: Prefix) -> bool {
54		self.get(hash, prefix).is_some()
55	}
56
57	fn insert(&mut self, prefix: Prefix, value: &[u8]) -> Hash {
58		let key = Hasher::hash(value);
59		self.emplace(key, prefix, value.to_vec());
60		key
61	}
62
63	fn emplace(&mut self, key: Hash, prefix: Prefix, value: DBValue) {
64		let key = sp_trie::prefixed_key::<Hasher>(&key, prefix);
65		self.overlay.insert(key, Some(value));
66	}
67
68	fn remove(&mut self, key: &Hash, prefix: Prefix) {
69		let key = sp_trie::prefixed_key::<Hasher>(key, prefix);
70		self.overlay.insert(key, None);
71	}
72}