hash_db/
lib.rs

1// Copyright 2017, 2021 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//! Database of byte-slices keyed to their hash.
16
17#![cfg_attr(not(feature = "std"), no_std)]
18
19#[cfg(not(feature = "std"))]
20use core::hash;
21#[cfg(feature = "std")]
22use std::fmt::Debug;
23#[cfg(feature = "std")]
24use std::hash;
25
26#[cfg(feature = "std")]
27pub trait MaybeDebug: Debug {}
28#[cfg(feature = "std")]
29impl<T: Debug> MaybeDebug for T {}
30#[cfg(not(feature = "std"))]
31pub trait MaybeDebug {}
32#[cfg(not(feature = "std"))]
33impl<T> MaybeDebug for T {}
34
35/// A trie node prefix, it is the nibble path from the trie root
36/// to the trie node.
37/// For a node containing no partial key value it is the full key.
38/// For a value node or node containing a partial key, it is the full key minus its node partial
39/// nibbles (the node key can be split into prefix and node partial).
40/// Therefore it is always the leftmost portion of the node key, so its internal representation
41/// is a non expanded byte slice followed by a last padded byte representation.
42/// The padded byte is an optional padded value.
43pub type Prefix<'a> = (&'a [u8], Option<u8>);
44
45/// An empty prefix constant.
46/// Can be use when the prefix is not use internally
47/// or for root nodes.
48pub static EMPTY_PREFIX: Prefix<'static> = (&[], None);
49
50/// Trait describing an object that can hash a slice of bytes. Used to abstract
51/// other types over the hashing algorithm. Defines a single `hash` method and an
52/// `Out` associated type with the necessary bounds.
53pub trait Hasher: Sync + Send {
54	/// The output type of the `Hasher`
55	type Out: AsRef<[u8]>
56		+ AsMut<[u8]>
57		+ Default
58		+ MaybeDebug
59		+ core::cmp::Ord
60		+ PartialEq
61		+ Eq
62		+ hash::Hash
63		+ Send
64		+ Sync
65		+ Clone
66		+ Copy;
67	/// What to use to build `HashMap`s with this `Hasher`.
68	type StdHasher: Sync + Send + Default + hash::Hasher;
69	/// The length in bytes of the `Hasher` output.
70	const LENGTH: usize;
71
72	/// Compute the hash of the provided slice of bytes returning the `Out` type of the `Hasher`.
73	fn hash(x: &[u8]) -> Self::Out;
74}
75
76/// Trait modelling a plain datastore whose key is a fixed type.
77/// The caller should ensure that a key only corresponds to
78/// one value.
79pub trait PlainDB<K, V>: Send + Sync + AsPlainDB<K, V> {
80	/// Look up a given hash into the bytes that hash to it, returning None if the
81	/// hash is not known.
82	fn get(&self, key: &K) -> Option<V>;
83
84	/// Check for the existence of a hash-key.
85	fn contains(&self, key: &K) -> bool;
86
87	/// Insert a datum item into the DB. Insertions are counted and the equivalent
88	/// number of `remove()`s must be performed before the data is considered dead.
89	/// The caller should ensure that a key only corresponds to one value.
90	fn emplace(&mut self, key: K, value: V);
91
92	/// Remove a datum previously inserted. Insertions can be "owed" such that the
93	/// same number of `insert()`s may happen without the data being eventually
94	/// being inserted into the DB. It can be "owed" more than once.
95	/// The caller should ensure that a key only corresponds to one value.
96	fn remove(&mut self, key: &K);
97}
98
99/// Trait for immutable reference of PlainDB.
100pub trait PlainDBRef<K, V> {
101	/// Look up a given hash into the bytes that hash to it, returning None if the
102	/// hash is not known.
103	fn get(&self, key: &K) -> Option<V>;
104
105	/// Check for the existance of a hash-key.
106	fn contains(&self, key: &K) -> bool;
107}
108
109impl<'a, K, V> PlainDBRef<K, V> for &'a dyn PlainDB<K, V> {
110	fn get(&self, key: &K) -> Option<V> {
111		PlainDB::get(*self, key)
112	}
113	fn contains(&self, key: &K) -> bool {
114		PlainDB::contains(*self, key)
115	}
116}
117
118impl<'a, K, V> PlainDBRef<K, V> for &'a mut dyn PlainDB<K, V> {
119	fn get(&self, key: &K) -> Option<V> {
120		PlainDB::get(*self, key)
121	}
122	fn contains(&self, key: &K) -> bool {
123		PlainDB::contains(*self, key)
124	}
125}
126
127/// Trait modelling datastore keyed by a hash defined by the `Hasher`.
128pub trait HashDB<H: Hasher, T>: Send + Sync + AsHashDB<H, T> {
129	/// Look up a given hash into the bytes that hash to it, returning None if the
130	/// hash is not known.
131	fn get(&self, key: &H::Out, prefix: Prefix) -> Option<T>;
132
133	/// Check for the existence of a hash-key.
134	fn contains(&self, key: &H::Out, prefix: Prefix) -> bool;
135
136	/// Insert a datum item into the DB and return the datum's hash for a later lookup. Insertions
137	/// are counted and the equivalent number of `remove()`s must be performed before the data
138	/// is considered dead.
139	fn insert(&mut self, prefix: Prefix, value: &[u8]) -> H::Out;
140
141	/// Like `insert()`, except you provide the key and the data is all moved.
142	fn emplace(&mut self, key: H::Out, prefix: Prefix, value: T);
143
144	/// Remove a datum previously inserted. Insertions can be "owed" such that the same number of
145	/// `insert()`s may happen without the data being eventually being inserted into the DB.
146	/// It can be "owed" more than once.
147	fn remove(&mut self, key: &H::Out, prefix: Prefix);
148}
149
150/// Trait for immutable reference of HashDB.
151pub trait HashDBRef<H: Hasher, T> {
152	/// Look up a given hash into the bytes that hash to it, returning None if the
153	/// hash is not known.
154	fn get(&self, key: &H::Out, prefix: Prefix) -> Option<T>;
155
156	/// Check for the existance of a hash-key.
157	fn contains(&self, key: &H::Out, prefix: Prefix) -> bool;
158}
159
160impl<'a, H: Hasher, T> HashDBRef<H, T> for &'a dyn HashDB<H, T> {
161	fn get(&self, key: &H::Out, prefix: Prefix) -> Option<T> {
162		HashDB::get(*self, key, prefix)
163	}
164	fn contains(&self, key: &H::Out, prefix: Prefix) -> bool {
165		HashDB::contains(*self, key, prefix)
166	}
167}
168
169impl<'a, H: Hasher, T> HashDBRef<H, T> for &'a mut dyn HashDB<H, T> {
170	fn get(&self, key: &H::Out, prefix: Prefix) -> Option<T> {
171		HashDB::get(*self, key, prefix)
172	}
173	fn contains(&self, key: &H::Out, prefix: Prefix) -> bool {
174		HashDB::contains(*self, key, prefix)
175	}
176}
177
178/// Upcast trait for HashDB.
179pub trait AsHashDB<H: Hasher, T> {
180	/// Perform upcast to HashDB for anything that derives from HashDB.
181	fn as_hash_db(&self) -> &dyn HashDB<H, T>;
182	/// Perform mutable upcast to HashDB for anything that derives from HashDB.
183	fn as_hash_db_mut<'a>(&'a mut self) -> &'a mut (dyn HashDB<H, T> + 'a);
184}
185
186/// Upcast trait for PlainDB.
187pub trait AsPlainDB<K, V> {
188	/// Perform upcast to PlainDB for anything that derives from PlainDB.
189	fn as_plain_db(&self) -> &dyn PlainDB<K, V>;
190	/// Perform mutable upcast to PlainDB for anything that derives from PlainDB.
191	fn as_plain_db_mut<'a>(&'a mut self) -> &'a mut (dyn PlainDB<K, V> + 'a);
192}
193
194// NOTE: There used to be a `impl<T> AsHashDB for T` but that does not work with generics.
195// See https://stackoverflow.com/questions/48432842/
196// implementing-a-trait-for-reference-and-non-reference-types-causes-conflicting-im
197// This means we need concrete impls of AsHashDB in several places, which somewhat defeats
198// the point of the trait.
199impl<'a, H: Hasher, T> AsHashDB<H, T> for &'a mut dyn HashDB<H, T> {
200	fn as_hash_db(&self) -> &dyn HashDB<H, T> {
201		&**self
202	}
203	fn as_hash_db_mut<'b>(&'b mut self) -> &'b mut (dyn HashDB<H, T> + 'b) {
204		&mut **self
205	}
206}
207
208#[cfg(feature = "std")]
209impl<'a, K, V> AsPlainDB<K, V> for &'a mut dyn PlainDB<K, V> {
210	fn as_plain_db(&self) -> &dyn PlainDB<K, V> {
211		&**self
212	}
213	fn as_plain_db_mut<'b>(&'b mut self) -> &'b mut (dyn PlainDB<K, V> + 'b) {
214		&mut **self
215	}
216}