trie_db/
sectriedbmut.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
15use crate::{
16	triedbmut::TrieDBMutBuilder, CError, DBValue, Result, TrieDBMut, TrieHash, TrieLayout, TrieMut,
17	Value,
18};
19use hash_db::{HashDB, Hasher};
20
21/// A mutable `Trie` implementation which hashes keys and uses a generic `HashDB` backing database.
22///
23/// Use it as a `Trie` or `TrieMut` trait object. You can use `raw()` to get the backing `TrieDBMut`
24/// object.
25pub struct SecTrieDBMut<'db, L>
26where
27	L: TrieLayout,
28{
29	raw: TrieDBMut<'db, L>,
30}
31
32impl<'db, L> SecTrieDBMut<'db, L>
33where
34	L: TrieLayout,
35{
36	/// Create a new trie with the backing database `db` and empty `root`
37	/// Initialize to the state entailed by the genesis block.
38	/// This guarantees the trie is built correctly.
39	pub fn new(db: &'db mut dyn HashDB<L::Hash, DBValue>, root: &'db mut TrieHash<L>) -> Self {
40		SecTrieDBMut { raw: TrieDBMutBuilder::new(db, root).build() }
41	}
42
43	/// Create a new trie with the backing database `db` and `root`.
44	pub fn from_existing(
45		db: &'db mut dyn HashDB<L::Hash, DBValue>,
46		root: &'db mut TrieHash<L>,
47	) -> Self {
48		SecTrieDBMut { raw: TrieDBMutBuilder::from_existing(db, root).build() }
49	}
50
51	/// Get the backing database.
52	pub fn db(&self) -> &dyn HashDB<L::Hash, DBValue> {
53		self.raw.db()
54	}
55
56	/// Get the backing database.
57	pub fn db_mut(&mut self) -> &mut dyn HashDB<L::Hash, DBValue> {
58		self.raw.db_mut()
59	}
60}
61
62impl<'db, L> TrieMut<L> for SecTrieDBMut<'db, L>
63where
64	L: TrieLayout,
65{
66	fn root(&mut self) -> &TrieHash<L> {
67		self.raw.root()
68	}
69
70	fn is_empty(&self) -> bool {
71		self.raw.is_empty()
72	}
73
74	fn contains(&self, key: &[u8]) -> Result<bool, TrieHash<L>, CError<L>> {
75		self.raw.contains(&L::Hash::hash(key).as_ref())
76	}
77
78	fn get<'a, 'key>(&'a self, key: &'key [u8]) -> Result<Option<DBValue>, TrieHash<L>, CError<L>>
79	where
80		'a: 'key,
81	{
82		self.raw.get(&L::Hash::hash(key).as_ref())
83	}
84
85	fn insert(
86		&mut self,
87		key: &[u8],
88		value: &[u8],
89	) -> Result<Option<Value<L>>, TrieHash<L>, CError<L>> {
90		self.raw.insert(&L::Hash::hash(key).as_ref(), value)
91	}
92
93	fn remove(&mut self, key: &[u8]) -> Result<Option<Value<L>>, TrieHash<L>, CError<L>> {
94		self.raw.remove(&L::Hash::hash(key).as_ref())
95	}
96}