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