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