tetsy_hash_db/
lib.rs

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