trie_db_fun/
triedbmut.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//! In-memory trie representation.
16
17use crate::{
18	lookup::Lookup,
19	nibble::{nibble_ops, BackingByteVec, NibbleSlice, NibbleVec},
20	node::{
21		decode_hash, Node as EncodedNode, NodeHandle as EncodedNodeHandle, NodeHandleOwned,
22		NodeKey, NodeOwned, Value as EncodedValue, ValueOwned,
23	},
24	node_codec::NodeCodec,
25	rstd::{boxed::Box, convert::TryFrom, mem, ops::Index, result, vec::Vec, VecDeque},
26	Bytes, CError, CachedValue, DBValue, Result, TrieAccess, TrieCache, TrieError, TrieHash,
27	TrieLayout, TrieMut, TrieRecorder,
28};
29
30use hash_db::{HashDB, Hasher, Prefix, EMPTY_PREFIX};
31
32#[cfg(feature = "std")]
33use std::collections::HashSet as Set;
34
35#[cfg(not(feature = "std"))]
36use alloc::collections::btree_set::BTreeSet as Set;
37
38#[cfg(feature = "std")]
39use log::trace;
40
41#[cfg(feature = "std")]
42use crate::rstd::fmt::{self, Debug};
43
44// For lookups into the Node storage buffer.
45// This is deliberately non-copyable.
46#[cfg_attr(feature = "std", derive(Debug))]
47struct StorageHandle(usize);
48
49// Handles to nodes in the trie.
50#[cfg_attr(feature = "std", derive(Debug))]
51enum NodeHandle<H> {
52	/// Loaded into memory.
53	InMemory(StorageHandle),
54	/// Either a hash or an inline node
55	Hash(H),
56}
57
58impl<H> From<StorageHandle> for NodeHandle<H> {
59	fn from(handle: StorageHandle) -> Self {
60		NodeHandle::InMemory(handle)
61	}
62}
63
64fn empty_children<H>() -> Box<[Option<NodeHandle<H>>; nibble_ops::NIBBLE_LENGTH]> {
65	Box::new([
66		None, None, None, None, None, None, None, None, None, None, None, None, None, None, None,
67		None,
68	])
69}
70
71/// Type alias to indicate the nible covers a full key,
72/// therefore its left side is a full prefix.
73type NibbleFullKey<'key> = NibbleSlice<'key>;
74
75/// Value representation for Node.
76#[derive(Clone, Eq)]
77pub enum Value<L: TrieLayout> {
78	/// Value bytes inlined in a trie node.
79	Inline(Bytes),
80	/// Hash of the value.
81	Node(TrieHash<L>),
82	/// Hash of value bytes if calculated and value bytes.
83	/// The hash may be undefined until it node is added
84	/// to the db.
85	NewNode(Option<TrieHash<L>>, Bytes),
86}
87
88impl<L: TrieLayout> PartialEq<Self> for Value<L> {
89	fn eq(&self, other: &Self) -> bool {
90		match (self, other) {
91			(Value::Inline(v), Value::Inline(ov)) => v == ov,
92			(Value::Node(h), Value::Node(oh)) => h == oh,
93			(Value::NewNode(Some(h), _), Value::NewNode(Some(oh), _)) => h == oh,
94			(Value::NewNode(_, v), Value::NewNode(_, ov)) => v == ov,
95			// Note that for uncalculated hash we do not calculate it and default to true.
96			// This is rather similar to default Eq implementation.
97			_ => false,
98		}
99	}
100}
101
102impl<'a, L: TrieLayout> From<EncodedValue<'a>> for Value<L> {
103	fn from(v: EncodedValue<'a>) -> Self {
104		match v {
105			EncodedValue::Inline(value) => Value::Inline(value.into()),
106			EncodedValue::Node(hash) => {
107				let mut h = TrieHash::<L>::default();
108				h.as_mut().copy_from_slice(hash);
109				Value::Node(h)
110			},
111		}
112	}
113}
114
115impl<L: TrieLayout> From<&ValueOwned<TrieHash<L>>> for Value<L> {
116	fn from(val: &ValueOwned<TrieHash<L>>) -> Self {
117		match val {
118			ValueOwned::Inline(data, _) => Self::Inline(data.clone()),
119			ValueOwned::Node(hash) => Self::Node(*hash),
120		}
121	}
122}
123
124impl<L: TrieLayout> From<(Bytes, Option<u32>)> for Value<L> {
125	fn from((v, threshold): (Bytes, Option<u32>)) -> Self {
126		match v {
127			value =>
128				if threshold.map_or(false, |threshold| value.len() >= threshold as usize) {
129					Value::NewNode(None, value)
130				} else {
131					Value::Inline(value)
132				},
133		}
134	}
135}
136
137enum NodeToEncode<'a, H> {
138	Node(&'a [u8]),
139	TrieNode(NodeHandle<H>),
140}
141
142impl<L: TrieLayout> Value<L> {
143	fn new(value: Bytes, new_threshold: Option<u32>) -> Self {
144		(value, new_threshold).into()
145	}
146
147	fn into_encoded<'a, F>(
148		&'a mut self,
149		partial: Option<&NibbleSlice>,
150		f: &mut F,
151	) -> EncodedValue<'a>
152	where
153		F: FnMut(
154			NodeToEncode<TrieHash<L>>,
155			Option<&NibbleSlice>,
156			Option<u8>,
157		) -> ChildReference<TrieHash<L>>,
158	{
159		if let Value::NewNode(hash, value) = self {
160			let new_hash =
161				if let ChildReference::Hash(hash) = f(NodeToEncode::Node(&value), partial, None) {
162					hash
163				} else {
164					unreachable!("Value node can never be inlined; qed")
165				};
166			if let Some(h) = hash.as_ref() {
167				debug_assert!(h == &new_hash);
168			} else {
169				*hash = Some(new_hash);
170			}
171		}
172		let value = match &*self {
173			Value::Inline(value) => EncodedValue::Inline(&value),
174			Value::Node(hash) => EncodedValue::Node(hash.as_ref()),
175			Value::NewNode(Some(hash), _value) => EncodedValue::Node(hash.as_ref()),
176			Value::NewNode(None, _value) =>
177				unreachable!("New external value are always added before encoding anode"),
178		};
179		value
180	}
181
182	fn in_memory_fetched_value(
183		&self,
184		prefix: Prefix,
185		db: &dyn HashDB<L::Hash, DBValue>,
186		recorder: &Option<core::cell::RefCell<&mut dyn TrieRecorder<TrieHash<L>>>>,
187		full_key: &[u8],
188	) -> Result<Option<DBValue>, TrieHash<L>, CError<L>> {
189		Ok(Some(match self {
190			Value::Inline(value) => value.to_vec(),
191			Value::NewNode(_, value) => value.to_vec(),
192			Value::Node(hash) =>
193				if let Some(value) = db.get(hash, prefix) {
194					recorder.as_ref().map(|r| {
195						r.borrow_mut().record(TrieAccess::Value {
196							hash: *hash,
197							value: value.as_slice().into(),
198							full_key,
199						})
200					});
201
202					value
203				} else {
204					return Err(Box::new(TrieError::IncompleteDatabase(hash.clone())))
205				},
206		}))
207	}
208}
209
210/// Node types in the Trie.
211enum Node<L: TrieLayout> {
212	/// Empty node.
213	Empty,
214	/// A leaf node contains the end of a key and a value.
215	/// This key is encoded from a `NibbleSlice`, meaning it contains
216	/// a flag indicating it is a leaf.
217	Leaf(NodeKey, Value<L>),
218	/// An extension contains a shared portion of a key and a child node.
219	/// The shared portion is encoded from a `NibbleSlice` meaning it contains
220	/// a flag indicating it is an extension.
221	/// The child node is always a branch.
222	Extension(NodeKey, NodeHandle<TrieHash<L>>),
223	/// A branch has up to 16 children and an optional value.
224	Branch(Box<[Option<NodeHandle<TrieHash<L>>>; nibble_ops::NIBBLE_LENGTH]>, Option<Value<L>>),
225	/// Branch node with support for a nibble (to avoid extension node).
226	NibbledBranch(
227		NodeKey,
228		Box<[Option<NodeHandle<TrieHash<L>>>; nibble_ops::NIBBLE_LENGTH]>,
229		Option<Value<L>>,
230	),
231}
232
233#[cfg(feature = "std")]
234struct ToHex<'a>(&'a [u8]);
235#[cfg(feature = "std")]
236impl<'a> Debug for ToHex<'a> {
237	fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
238		let hex = rustc_hex::ToHexIter::new(self.0.iter());
239		for b in hex {
240			write!(fmt, "{}", b)?;
241		}
242		Ok(())
243	}
244}
245
246#[cfg(feature = "std")]
247impl<L: TrieLayout> Debug for Value<L> {
248	fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
249		match self {
250			Self::Inline(value) => write!(fmt, "Some({:?})", ToHex(value)),
251			Self::Node(hash) => write!(fmt, "Hash({:?})", ToHex(hash.as_ref())),
252			Self::NewNode(Some(hash), _) => write!(fmt, "Hash({:?})", ToHex(hash.as_ref())),
253			Self::NewNode(_hash, value) => write!(fmt, "Some({:?})", ToHex(value)),
254		}
255	}
256}
257
258#[cfg(feature = "std")]
259impl<L: TrieLayout> Debug for Node<L>
260where
261	L::Hash: Debug,
262{
263	fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
264		match *self {
265			Self::Empty => write!(fmt, "Empty"),
266			Self::Leaf((ref a, ref b), ref c) =>
267				write!(fmt, "Leaf({:?}, {:?})", (a, ToHex(&*b)), c),
268			Self::Extension((ref a, ref b), ref c) =>
269				write!(fmt, "Extension({:?}, {:?})", (a, ToHex(&*b)), c),
270			Self::Branch(ref a, ref b) => write!(fmt, "Branch({:?}, {:?}", a, b),
271			Self::NibbledBranch((ref a, ref b), ref c, ref d) =>
272				write!(fmt, "NibbledBranch({:?}, {:?}, {:?})", (a, ToHex(&*b)), c, d),
273		}
274	}
275}
276
277impl<L: TrieLayout> Node<L> {
278	// load an inline node into memory or get the hash to do the lookup later.
279	fn inline_or_hash(
280		parent_hash: TrieHash<L>,
281		child: EncodedNodeHandle,
282		storage: &mut NodeStorage<L>,
283	) -> Result<NodeHandle<TrieHash<L>>, TrieHash<L>, CError<L>> {
284		let handle = match child {
285			EncodedNodeHandle::Hash(data) => {
286				let hash = decode_hash::<L::Hash>(data)
287					.ok_or_else(|| Box::new(TrieError::InvalidHash(parent_hash, data.to_vec())))?;
288				NodeHandle::Hash(hash)
289			},
290			EncodedNodeHandle::Inline(data) => {
291				let child = Node::from_encoded(parent_hash, data, storage)?;
292				NodeHandle::InMemory(storage.alloc(Stored::New(child)))
293			},
294		};
295		Ok(handle)
296	}
297
298	// load an inline node into memory or get the hash to do the lookup later.
299	fn inline_or_hash_owned(
300		child: &NodeHandleOwned<TrieHash<L>>,
301		storage: &mut NodeStorage<L>,
302	) -> NodeHandle<TrieHash<L>> {
303		match child {
304			NodeHandleOwned::Hash(hash) => NodeHandle::Hash(*hash),
305			NodeHandleOwned::Inline(node) => {
306				let child = Node::from_node_owned(&**node, storage);
307				NodeHandle::InMemory(storage.alloc(Stored::New(child)))
308			},
309		}
310	}
311
312	// Decode a node from encoded bytes.
313	fn from_encoded<'a, 'b>(
314		node_hash: TrieHash<L>,
315		data: &'a [u8],
316		storage: &'b mut NodeStorage<L>,
317	) -> Result<Self, TrieHash<L>, CError<L>> {
318		let encoded_node =
319			L::Codec::decode(data).map_err(|e| Box::new(TrieError::DecoderError(node_hash, e)))?;
320		let node = match encoded_node {
321			EncodedNode::Empty => Node::Empty,
322			EncodedNode::Leaf(k, v) => Node::Leaf(k.into(), v.into()),
323			EncodedNode::Extension(key, cb) =>
324				Node::Extension(key.into(), Self::inline_or_hash(node_hash, cb, storage)?),
325			EncodedNode::Branch(encoded_children, val) => {
326				let mut child = |i: usize| match encoded_children[i] {
327					Some(child) => Self::inline_or_hash(node_hash, child, storage).map(Some),
328					None => Ok(None),
329				};
330
331				let children = Box::new([
332					child(0)?,
333					child(1)?,
334					child(2)?,
335					child(3)?,
336					child(4)?,
337					child(5)?,
338					child(6)?,
339					child(7)?,
340					child(8)?,
341					child(9)?,
342					child(10)?,
343					child(11)?,
344					child(12)?,
345					child(13)?,
346					child(14)?,
347					child(15)?,
348				]);
349
350				Node::Branch(children, val.map(Into::into))
351			},
352			EncodedNode::NibbledBranch(k, encoded_children, val) => {
353				let mut child = |i: usize| match encoded_children[i] {
354					Some(child) => Self::inline_or_hash(node_hash, child, storage).map(Some),
355					None => Ok(None),
356				};
357
358				let children = Box::new([
359					child(0)?,
360					child(1)?,
361					child(2)?,
362					child(3)?,
363					child(4)?,
364					child(5)?,
365					child(6)?,
366					child(7)?,
367					child(8)?,
368					child(9)?,
369					child(10)?,
370					child(11)?,
371					child(12)?,
372					child(13)?,
373					child(14)?,
374					child(15)?,
375				]);
376
377				Node::NibbledBranch(k.into(), children, val.map(Into::into))
378			},
379		};
380		Ok(node)
381	}
382
383	/// Decode a node from a [`NodeOwned`].
384	fn from_node_owned(node_owned: &NodeOwned<TrieHash<L>>, storage: &mut NodeStorage<L>) -> Self {
385		match node_owned {
386			NodeOwned::Empty => Node::Empty,
387			NodeOwned::Leaf(k, v) => Node::Leaf(k.into(), v.into()),
388			NodeOwned::Extension(key, cb) =>
389				Node::Extension(key.into(), Self::inline_or_hash_owned(cb, storage)),
390			NodeOwned::Branch(encoded_children, val) => {
391				let mut child = |i: usize| {
392					encoded_children[i]
393						.as_ref()
394						.map(|child| Self::inline_or_hash_owned(child, storage))
395				};
396
397				let children = Box::new([
398					child(0),
399					child(1),
400					child(2),
401					child(3),
402					child(4),
403					child(5),
404					child(6),
405					child(7),
406					child(8),
407					child(9),
408					child(10),
409					child(11),
410					child(12),
411					child(13),
412					child(14),
413					child(15),
414				]);
415
416				Node::Branch(children, val.as_ref().map(Into::into))
417			},
418			NodeOwned::NibbledBranch(k, encoded_children, val) => {
419				let mut child = |i: usize| {
420					encoded_children[i]
421						.as_ref()
422						.map(|child| Self::inline_or_hash_owned(child, storage))
423				};
424
425				let children = Box::new([
426					child(0),
427					child(1),
428					child(2),
429					child(3),
430					child(4),
431					child(5),
432					child(6),
433					child(7),
434					child(8),
435					child(9),
436					child(10),
437					child(11),
438					child(12),
439					child(13),
440					child(14),
441					child(15),
442				]);
443
444				Node::NibbledBranch(k.into(), children, val.as_ref().map(Into::into))
445			},
446			NodeOwned::Value(_, _) =>
447				unreachable!("`NodeOwned::Value` can only be returned for the hash of a value."),
448		}
449	}
450
451	// TODO: parallelize
452	/// Here `child_cb` should process the first parameter to either insert an external
453	/// node value or to encode and add a new branch child node.
454	fn into_encoded<F>(self, mut child_cb: F) -> Vec<u8>
455	where
456		F: FnMut(
457			NodeToEncode<TrieHash<L>>,
458			Option<&NibbleSlice>,
459			Option<u8>,
460		) -> ChildReference<TrieHash<L>>,
461	{
462		match self {
463			Node::Empty => L::Codec::empty_node().to_vec(),
464			Node::Leaf(partial, mut value) => {
465				let pr = NibbleSlice::new_offset(&partial.1[..], partial.0);
466				let value = value.into_encoded::<F>(Some(&pr), &mut child_cb);
467				L::Codec::leaf_node(pr.right_iter(), pr.len(), value)
468			},
469			Node::Extension(partial, child) => {
470				let pr = NibbleSlice::new_offset(&partial.1[..], partial.0);
471				let it = pr.right_iter();
472				let c = child_cb(NodeToEncode::TrieNode(child), Some(&pr), None);
473				L::Codec::extension_node(it, pr.len(), c)
474			},
475			Node::Branch(mut children, mut value) => {
476				let value = value.as_mut().map(|v| v.into_encoded::<F>(None, &mut child_cb));
477				L::Codec::branch_node(
478					// map the `NodeHandle`s from the Branch to `ChildReferences`
479					children.iter_mut().map(Option::take).enumerate().map(|(i, maybe_child)| {
480						maybe_child.map(|child| {
481							child_cb(NodeToEncode::TrieNode(child), None, Some(i as u8))
482						})
483					}),
484					value,
485				)
486			},
487			Node::NibbledBranch(partial, mut children, mut value) => {
488				let pr = NibbleSlice::new_offset(&partial.1[..], partial.0);
489				let value = value.as_mut().map(|v| v.into_encoded::<F>(Some(&pr), &mut child_cb));
490				let it = pr.right_iter();
491				L::Codec::branch_node_nibbled(
492					it,
493					pr.len(),
494					// map the `NodeHandle`s from the Branch to `ChildReferences`
495					children.iter_mut().map(Option::take).enumerate().map(|(i, maybe_child)| {
496						//let branch_index = [i as u8];
497						maybe_child.map(|child| {
498							let pr = NibbleSlice::new_offset(&partial.1[..], partial.0);
499							child_cb(NodeToEncode::TrieNode(child), Some(&pr), Some(i as u8))
500						})
501					}),
502					value,
503				)
504			},
505		}
506	}
507
508	/// Returns the key partial key of this node.
509	fn partial_key(&self) -> Option<&NodeKey> {
510		match &self {
511			Self::Empty => None,
512			Self::Leaf(key, _) => Some(key),
513			Self::Branch(_, _) => None,
514			Self::NibbledBranch(key, _, _) => Some(key),
515			Self::Extension(key, _) => Some(key),
516		}
517	}
518}
519
520// post-inspect action.
521enum Action<L: TrieLayout> {
522	// Replace a node with a new one.
523	Replace(Node<L>),
524	// Restore the original node. This trusts that the node is actually the original.
525	Restore(Node<L>),
526	// if it is a new node, just clears the storage.
527	Delete,
528}
529
530// post-insert action. Same as action without delete
531enum InsertAction<L: TrieLayout> {
532	// Replace a node with a new one.
533	Replace(Node<L>),
534	// Restore the original node.
535	Restore(Node<L>),
536}
537
538impl<L: TrieLayout> InsertAction<L> {
539	fn into_action(self) -> Action<L> {
540		match self {
541			InsertAction::Replace(n) => Action::Replace(n),
542			InsertAction::Restore(n) => Action::Restore(n),
543		}
544	}
545
546	// unwrap the node, disregarding replace or restore state.
547	fn unwrap_node(self) -> Node<L> {
548		match self {
549			InsertAction::Replace(n) | InsertAction::Restore(n) => n,
550		}
551	}
552}
553
554// What kind of node is stored here.
555enum Stored<L: TrieLayout> {
556	// A new node.
557	New(Node<L>),
558	// A cached node, loaded from the DB.
559	Cached(Node<L>, TrieHash<L>),
560}
561
562/// Used to build a collection of child nodes from a collection of `NodeHandle`s
563#[derive(Clone, Copy)]
564#[cfg_attr(feature = "std", derive(Debug))]
565pub enum ChildReference<HO> {
566	// `HO` is e.g. `H256`, i.e. the output of a `Hasher`
567	Hash(HO),
568	Inline(HO, usize), // usize is the length of the node data we store in the `H::Out`
569}
570
571impl<'a, HO> TryFrom<EncodedNodeHandle<'a>> for ChildReference<HO>
572where
573	HO: AsRef<[u8]> + AsMut<[u8]> + Default + Clone + Copy,
574{
575	type Error = Vec<u8>;
576
577	fn try_from(handle: EncodedNodeHandle<'a>) -> result::Result<Self, Vec<u8>> {
578		match handle {
579			EncodedNodeHandle::Hash(data) => {
580				let mut hash = HO::default();
581				if data.len() != hash.as_ref().len() {
582					return Err(data.to_vec())
583				}
584				hash.as_mut().copy_from_slice(data);
585				Ok(ChildReference::Hash(hash))
586			},
587			EncodedNodeHandle::Inline(data) => {
588				let mut hash = HO::default();
589				if data.len() > hash.as_ref().len() {
590					return Err(data.to_vec())
591				}
592				hash.as_mut()[..data.len()].copy_from_slice(data);
593				Ok(ChildReference::Inline(hash, data.len()))
594			},
595		}
596	}
597}
598
599/// Compact and cache-friendly storage for Trie nodes.
600struct NodeStorage<L: TrieLayout> {
601	nodes: Vec<Stored<L>>,
602	free_indices: VecDeque<usize>,
603}
604
605impl<L: TrieLayout> NodeStorage<L> {
606	/// Create a new storage.
607	fn empty() -> Self {
608		NodeStorage { nodes: Vec::new(), free_indices: VecDeque::new() }
609	}
610
611	/// Allocate a new node in the storage.
612	fn alloc(&mut self, stored: Stored<L>) -> StorageHandle {
613		if let Some(idx) = self.free_indices.pop_front() {
614			self.nodes[idx] = stored;
615			StorageHandle(idx)
616		} else {
617			self.nodes.push(stored);
618			StorageHandle(self.nodes.len() - 1)
619		}
620	}
621
622	/// Remove a node from the storage, consuming the handle and returning the node.
623	fn destroy(&mut self, handle: StorageHandle) -> Stored<L> {
624		let idx = handle.0;
625
626		self.free_indices.push_back(idx);
627		mem::replace(&mut self.nodes[idx], Stored::New(Node::Empty))
628	}
629}
630
631impl<'a, L: TrieLayout> Index<&'a StorageHandle> for NodeStorage<L> {
632	type Output = Node<L>;
633
634	fn index(&self, handle: &'a StorageHandle) -> &Node<L> {
635		match self.nodes[handle.0] {
636			Stored::New(ref node) => node,
637			Stored::Cached(ref node, _) => node,
638		}
639	}
640}
641
642/// A builder for creating a [`TrieDBMut`].
643pub struct TrieDBMutBuilder<'db, L: TrieLayout> {
644	db: &'db mut dyn HashDB<L::Hash, DBValue>,
645	root: &'db mut TrieHash<L>,
646	cache: Option<&'db mut dyn TrieCache<L::Codec>>,
647	recorder: Option<&'db mut dyn TrieRecorder<TrieHash<L>>>,
648}
649
650impl<'db, L: TrieLayout> TrieDBMutBuilder<'db, L> {
651	/// Create a builder for constructing a new trie with the backing database `db` and empty
652	/// `root`.
653	pub fn new(db: &'db mut dyn HashDB<L::Hash, DBValue>, root: &'db mut TrieHash<L>) -> Self {
654		*root = L::Codec::hashed_null_node();
655
656		Self { root, db, cache: None, recorder: None }
657	}
658
659	/// Create a builder for constructing a new trie with the backing database `db` and `root`.
660	///
661	/// This doesn't check if `root` exists in the given `db`. If `root` doesn't exist it will fail
662	/// when trying to lookup any key.
663	pub fn from_existing(
664		db: &'db mut dyn HashDB<L::Hash, DBValue>,
665		root: &'db mut TrieHash<L>,
666	) -> Self {
667		Self { db, root, cache: None, recorder: None }
668	}
669
670	/// Use the given `cache` for the db.
671	pub fn with_cache(mut self, cache: &'db mut dyn TrieCache<L::Codec>) -> Self {
672		self.cache = Some(cache);
673		self
674	}
675
676	/// Use the given optional `cache` for the db.
677	pub fn with_optional_cache<'cache: 'db>(
678		mut self,
679		cache: Option<&'cache mut dyn TrieCache<L::Codec>>,
680	) -> Self {
681		// Make the compiler happy by "converting" the lifetime
682		self.cache = cache.map(|c| c as _);
683		self
684	}
685
686	/// Use the given `recorder` to record trie accesses.
687	pub fn with_recorder(mut self, recorder: &'db mut dyn TrieRecorder<TrieHash<L>>) -> Self {
688		self.recorder = Some(recorder);
689		self
690	}
691
692	/// Use the given optional `recorder` to record trie accesses.
693	pub fn with_optional_recorder<'recorder: 'db>(
694		mut self,
695		recorder: Option<&'recorder mut dyn TrieRecorder<TrieHash<L>>>,
696	) -> Self {
697		// Make the compiler happy by "converting" the lifetime
698		self.recorder = recorder.map(|r| r as _);
699		self
700	}
701
702	/// Build the [`TrieDBMut`].
703	pub fn build(self) -> TrieDBMut<'db, L> {
704		let root_handle = NodeHandle::Hash(*self.root);
705
706		TrieDBMut {
707			db: self.db,
708			root: self.root,
709			cache: self.cache,
710			recorder: self.recorder.map(core::cell::RefCell::new),
711			storage: NodeStorage::empty(),
712			death_row: Default::default(),
713			root_handle,
714		}
715	}
716}
717
718/// A `Trie` implementation using a generic `HashDB` backing database.
719///
720/// Use it as a `TrieMut` trait object. You can use `db()` to get the backing database object.
721/// Note that changes are not committed to the database until `commit` is called.
722///
723/// Querying the root or dropping the trie will commit automatically.
724///
725///
726/// # Example
727/// ```ignore
728/// use hash_db::Hasher;
729/// use reference_trie_fun::{RefTrieDBMut, TrieMut};
730/// use trie_db_fun::DBValue;
731/// use keccak_hasher::KeccakHasher;
732/// use memory_db::*;
733///
734/// let mut memdb = MemoryDB::<KeccakHasher, HashKey<_>, DBValue>::default();
735/// let mut root = Default::default();
736/// let mut t = RefTrieDBMut::new(&mut memdb, &mut root);
737/// assert!(t.is_empty());
738/// assert_eq!(*t.root(), KeccakHasher::hash(&[0u8][..]));
739/// t.insert(b"foo", b"bar").unwrap();
740/// assert!(t.contains(b"foo").unwrap());
741/// assert_eq!(t.get(b"foo").unwrap().unwrap(), b"bar".to_vec());
742/// t.remove(b"foo").unwrap();
743/// assert!(!t.contains(b"foo").unwrap());
744/// ```
745pub struct TrieDBMut<'a, L>
746where
747	L: TrieLayout,
748{
749	storage: NodeStorage<L>,
750	db: &'a mut dyn HashDB<L::Hash, DBValue>,
751	root: &'a mut TrieHash<L>,
752	root_handle: NodeHandle<TrieHash<L>>,
753	death_row: Set<(TrieHash<L>, (BackingByteVec, Option<u8>))>,
754	/// Optional cache for speeding up the lookup of nodes.
755	cache: Option<&'a mut dyn TrieCache<L::Codec>>,
756	/// Optional trie recorder for recording trie accesses.
757	recorder: Option<core::cell::RefCell<&'a mut dyn TrieRecorder<TrieHash<L>>>>,
758}
759
760impl<'a, L> TrieDBMut<'a, L>
761where
762	L: TrieLayout,
763{
764	/// Get the backing database.
765	pub fn db(&self) -> &dyn HashDB<L::Hash, DBValue> {
766		self.db
767	}
768
769	/// Get the backing database mutably.
770	pub fn db_mut(&mut self) -> &mut dyn HashDB<L::Hash, DBValue> {
771		self.db
772	}
773
774	// Cache a node by hash.
775	fn cache(
776		&mut self,
777		hash: TrieHash<L>,
778		key: Prefix,
779	) -> Result<StorageHandle, TrieHash<L>, CError<L>> {
780		// We only check the `cache` for a node with `get_node` and don't insert
781		// the node if it wasn't there, because in substrate we only access the node while computing
782		// a new trie (aka some branch). We assume that this node isn't that important
783		// to have it being cached.
784		let node = match self.cache.as_mut().and_then(|c| c.get_node(&hash)) {
785			Some(node) => {
786				if let Some(recorder) = self.recorder.as_mut() {
787					recorder.borrow_mut().record(TrieAccess::NodeOwned { hash, node_owned: &node });
788				}
789
790				Node::from_node_owned(&node, &mut self.storage)
791			},
792			None => {
793				let node_encoded = self
794					.db
795					.get(&hash, key)
796					.ok_or_else(|| Box::new(TrieError::IncompleteDatabase(hash)))?;
797
798				if let Some(recorder) = self.recorder.as_mut() {
799					recorder.borrow_mut().record(TrieAccess::EncodedNode {
800						hash,
801						encoded_node: node_encoded.as_slice().into(),
802					});
803				}
804
805				Node::from_encoded(hash, &node_encoded, &mut self.storage)?
806			},
807		};
808
809		Ok(self.storage.alloc(Stored::Cached(node, hash)))
810	}
811
812	// Inspect a node, choosing either to replace, restore, or delete it.
813	// If restored or replaced, returns the new node along with a flag of whether it was changed.
814	fn inspect<F>(
815		&mut self,
816		stored: Stored<L>,
817		key: &mut NibbleFullKey,
818		inspector: F,
819	) -> Result<Option<(Stored<L>, bool)>, TrieHash<L>, CError<L>>
820	where
821		F: FnOnce(
822			&mut Self,
823			Node<L>,
824			&mut NibbleFullKey,
825		) -> Result<Action<L>, TrieHash<L>, CError<L>>,
826	{
827		let current_key = *key;
828		Ok(match stored {
829			Stored::New(node) => match inspector(self, node, key)? {
830				Action::Restore(node) => Some((Stored::New(node), false)),
831				Action::Replace(node) => Some((Stored::New(node), true)),
832				Action::Delete => None,
833			},
834			Stored::Cached(node, hash) => match inspector(self, node, key)? {
835				Action::Restore(node) => Some((Stored::Cached(node, hash), false)),
836				Action::Replace(node) => {
837					self.death_row.insert((hash, current_key.left_owned()));
838					Some((Stored::New(node), true))
839				},
840				Action::Delete => {
841					self.death_row.insert((hash, current_key.left_owned()));
842					None
843				},
844			},
845		})
846	}
847
848	// Walk the trie, attempting to find the key's node.
849	fn lookup(
850		&self,
851		full_key: &[u8],
852		mut partial: NibbleSlice,
853		handle: &NodeHandle<TrieHash<L>>,
854	) -> Result<Option<DBValue>, TrieHash<L>, CError<L>> {
855		let mut handle = handle;
856		// prefix only use for value node access, so this is always correct.
857		let prefix = (full_key, None);
858		loop {
859			let (mid, child) = match handle {
860				NodeHandle::Hash(hash) => {
861					let mut recorder = self.recorder.as_ref().map(|r| r.borrow_mut());
862
863					return Lookup::<L, _> {
864						db: &self.db,
865						query: |v: &[u8]| v.to_vec(),
866						hash: *hash,
867						cache: None,
868						recorder: recorder
869							.as_mut()
870							.map(|r| &mut ***r as &mut dyn TrieRecorder<TrieHash<L>>),
871					}
872					.look_up(full_key, partial)
873				},
874				NodeHandle::InMemory(handle) => match &self.storage[handle] {
875					Node::Empty => return Ok(None),
876					Node::Leaf(slice, value) =>
877						if NibbleSlice::from_stored(slice) == partial {
878							return Ok(value.in_memory_fetched_value(
879								prefix,
880								self.db,
881								&self.recorder,
882								full_key,
883							)?)
884						} else {
885							return Ok(None)
886						},
887					Node::Extension(slice, child) => {
888						let slice = NibbleSlice::from_stored(slice);
889						if partial.starts_with(&slice) {
890							(slice.len(), child)
891						} else {
892							return Ok(None)
893						}
894					},
895					Node::Branch(children, value) =>
896						if partial.is_empty() {
897							return Ok(if let Some(v) = value.as_ref() {
898								v.in_memory_fetched_value(
899									prefix,
900									self.db,
901									&self.recorder,
902									full_key,
903								)?
904							} else {
905								None
906							})
907						} else {
908							let idx = partial.at(0);
909							match children[idx as usize].as_ref() {
910								Some(child) => (1, child),
911								None => return Ok(None),
912							}
913						},
914					Node::NibbledBranch(slice, children, value) => {
915						let slice = NibbleSlice::from_stored(slice);
916						if slice == partial {
917							return Ok(if let Some(v) = value.as_ref() {
918								v.in_memory_fetched_value(
919									prefix,
920									self.db,
921									&self.recorder,
922									full_key,
923								)?
924							} else {
925								None
926							})
927						} else if partial.starts_with(&slice) {
928							let idx = partial.at(slice.len());
929							match children[idx as usize].as_ref() {
930								Some(child) => (1 + slice.len(), child),
931								None => return Ok(None),
932							}
933						} else {
934							return Ok(None)
935						}
936					},
937				},
938			};
939
940			partial = partial.mid(mid);
941			handle = child;
942		}
943	}
944
945	/// Insert a key-value pair into the trie, creating new nodes if necessary.
946	fn insert_at(
947		&mut self,
948		handle: NodeHandle<TrieHash<L>>,
949		key: &mut NibbleFullKey,
950		value: Bytes,
951		old_val: &mut Option<Value<L>>,
952	) -> Result<(StorageHandle, bool), TrieHash<L>, CError<L>> {
953		let h = match handle {
954			NodeHandle::InMemory(h) => h,
955			NodeHandle::Hash(h) => self.cache(h, key.left())?,
956		};
957		// cache then destroy for hash handle (handle being root in most case)
958		let stored = self.storage.destroy(h);
959		let (new_stored, changed) = self
960			.inspect(stored, key, move |trie, stored, key| {
961				trie.insert_inspector(stored, key, value, old_val).map(|a| a.into_action())
962			})?
963			.expect("Insertion never deletes.");
964
965		Ok((self.storage.alloc(new_stored), changed))
966	}
967
968	fn replace_old_value(
969		&mut self,
970		old_value: &mut Option<Value<L>>,
971		stored_value: Option<Value<L>>,
972		prefix: Prefix,
973	) {
974		match &stored_value {
975			Some(Value::NewNode(Some(hash), _)) // also removing new node in case commit is called multiple times
976			| Some(Value::Node(hash)) => {
977				self.death_row.insert((
978					hash.clone(),
979					(prefix.0.into(), prefix.1),
980				));
981			},
982			_ => (),
983		}
984		*old_value = stored_value;
985	}
986
987	/// The insertion inspector.
988	fn insert_inspector(
989		&mut self,
990		node: Node<L>,
991		key: &mut NibbleFullKey,
992		value: Bytes,
993		old_val: &mut Option<Value<L>>,
994	) -> Result<InsertAction<L>, TrieHash<L>, CError<L>> {
995		let partial = *key;
996
997		#[cfg(feature = "std")]
998		trace!(target: "trie", "augmented (partial: {:?}, value: {:?})", partial, ToHex(&value));
999
1000		Ok(match node {
1001			Node::Empty => {
1002				#[cfg(feature = "std")]
1003				trace!(target: "trie", "empty: COMPOSE");
1004				let value = Value::new(value, L::MAX_INLINE_VALUE);
1005				InsertAction::Replace(Node::Leaf(partial.to_stored(), value))
1006			},
1007			Node::Branch(mut children, stored_value) => {
1008				debug_assert!(L::USE_EXTENSION);
1009				#[cfg(feature = "std")]
1010				trace!(target: "trie", "branch: ROUTE,AUGMENT");
1011
1012				if partial.is_empty() {
1013					let value = Some(Value::new(value, L::MAX_INLINE_VALUE));
1014					let unchanged = stored_value == value;
1015					let branch = Node::Branch(children, value);
1016
1017					self.replace_old_value(old_val, stored_value, key.left());
1018
1019					if unchanged {
1020						InsertAction::Restore(branch)
1021					} else {
1022						InsertAction::Replace(branch)
1023					}
1024				} else {
1025					let idx = partial.at(0) as usize;
1026					key.advance(1);
1027					if let Some(child) = children[idx].take() {
1028						// Original had something there. recurse down into it.
1029						let (new_child, changed) = self.insert_at(child, key, value, old_val)?;
1030						children[idx] = Some(new_child.into());
1031						if !changed {
1032							// The new node we composed didn't change.
1033							// It means our branch is untouched too.
1034							return Ok(InsertAction::Restore(Node::Branch(children, stored_value)))
1035						}
1036					} else {
1037						// Original had nothing there. compose a leaf.
1038						let value = Value::new(value, L::MAX_INLINE_VALUE);
1039						let leaf =
1040							self.storage.alloc(Stored::New(Node::Leaf(key.to_stored(), value)));
1041						children[idx] = Some(leaf.into());
1042					}
1043
1044					InsertAction::Replace(Node::Branch(children, stored_value))
1045				}
1046			},
1047			Node::NibbledBranch(encoded, mut children, stored_value) => {
1048				debug_assert!(!L::USE_EXTENSION);
1049				#[cfg(feature = "std")]
1050				trace!(target: "trie", "branch: ROUTE,AUGMENT");
1051				let existing_key = NibbleSlice::from_stored(&encoded);
1052
1053				let common = partial.common_prefix(&existing_key);
1054				if common == existing_key.len() && common == partial.len() {
1055					let value = Some(Value::new(value, L::MAX_INLINE_VALUE));
1056					let unchanged = stored_value == value;
1057					let branch = Node::NibbledBranch(existing_key.to_stored(), children, value);
1058
1059					let mut key_val = key.clone();
1060					key_val.advance(existing_key.len());
1061					self.replace_old_value(old_val, stored_value, key_val.left());
1062
1063					if unchanged {
1064						InsertAction::Restore(branch)
1065					} else {
1066						InsertAction::Replace(branch)
1067					}
1068				} else if common < existing_key.len() {
1069					// insert a branch value in between
1070					#[cfg(feature = "std")]
1071					trace!(
1072						target: "trie",
1073						"partially-shared-prefix (exist={:?}; new={:?}; common={:?}):\
1074							 AUGMENT-AT-END",
1075						existing_key.len(),
1076						partial.len(),
1077						common,
1078					);
1079					let nbranch_partial = existing_key.mid(common + 1).to_stored();
1080					let low = Node::NibbledBranch(nbranch_partial, children, stored_value);
1081					let ix = existing_key.at(common);
1082					let mut children = empty_children();
1083					let alloc_storage = self.storage.alloc(Stored::New(low));
1084
1085					children[ix as usize] = Some(alloc_storage.into());
1086
1087					let value = Value::new(value, L::MAX_INLINE_VALUE);
1088					if partial.len() - common == 0 {
1089						InsertAction::Replace(Node::NibbledBranch(
1090							existing_key.to_stored_range(common),
1091							children,
1092							Some(value),
1093						))
1094					} else {
1095						let ix = partial.at(common);
1096						let stored_leaf = Node::Leaf(partial.mid(common + 1).to_stored(), value);
1097
1098						let leaf = self.storage.alloc(Stored::New(stored_leaf));
1099
1100						children[ix as usize] = Some(leaf.into());
1101						InsertAction::Replace(Node::NibbledBranch(
1102							existing_key.to_stored_range(common),
1103							children,
1104							None,
1105						))
1106					}
1107				} else {
1108					// Append after common == existing_key and partial > common
1109					#[cfg(feature = "std")]
1110					trace!(target: "trie", "branch: ROUTE,AUGMENT");
1111					let idx = partial.at(common) as usize;
1112					key.advance(common + 1);
1113					if let Some(child) = children[idx].take() {
1114						// Original had something there. recurse down into it.
1115						let (new_child, changed) = self.insert_at(child, key, value, old_val)?;
1116						children[idx] = Some(new_child.into());
1117						if !changed {
1118							// The new node we composed didn't change.
1119							// It means our branch is untouched too.
1120							let n_branch = Node::NibbledBranch(
1121								existing_key.to_stored(),
1122								children,
1123								stored_value,
1124							);
1125							return Ok(InsertAction::Restore(n_branch))
1126						}
1127					} else {
1128						// Original had nothing there. compose a leaf.
1129						let value = Value::new(value, L::MAX_INLINE_VALUE);
1130						let leaf =
1131							self.storage.alloc(Stored::New(Node::Leaf(key.to_stored(), value)));
1132
1133						children[idx] = Some(leaf.into());
1134					}
1135					InsertAction::Replace(Node::NibbledBranch(
1136						existing_key.to_stored(),
1137						children,
1138						stored_value,
1139					))
1140				}
1141			},
1142			Node::Leaf(encoded, stored_value) => {
1143				let existing_key = NibbleSlice::from_stored(&encoded);
1144				let common = partial.common_prefix(&existing_key);
1145				if common == existing_key.len() && common == partial.len() {
1146					#[cfg(feature = "std")]
1147					trace!(target: "trie", "equivalent-leaf: REPLACE");
1148					// equivalent leaf.
1149					let value = Value::new(value, L::MAX_INLINE_VALUE);
1150					let unchanged = stored_value == value;
1151					let mut key_val = key.clone();
1152					key_val.advance(existing_key.len());
1153					self.replace_old_value(old_val, Some(stored_value), key_val.left());
1154					if unchanged {
1155						// unchanged. restore
1156						InsertAction::Restore(Node::Leaf(encoded.clone(), value))
1157					} else {
1158						InsertAction::Replace(Node::Leaf(encoded.clone(), value))
1159					}
1160				} else if (L::USE_EXTENSION && common == 0) ||
1161					(!L::USE_EXTENSION && common < existing_key.len())
1162				{
1163					#[cfg(feature = "std")]
1164					trace!(
1165						target: "trie",
1166						"lesser-common-prefix, not-both-empty (exist={:?}; new={:?}):\
1167							TRANSMUTE,AUGMENT",
1168						existing_key.len(),
1169						partial.len(),
1170					);
1171
1172					// one of us isn't empty: transmute to branch here
1173					let mut children = empty_children();
1174					let branch = if L::USE_EXTENSION && existing_key.is_empty() {
1175						// always replace since branch isn't leaf.
1176						Node::Branch(children, Some(stored_value))
1177					} else {
1178						let idx = existing_key.at(common) as usize;
1179						let new_leaf =
1180							Node::Leaf(existing_key.mid(common + 1).to_stored(), stored_value);
1181						children[idx] = Some(self.storage.alloc(Stored::New(new_leaf)).into());
1182
1183						if L::USE_EXTENSION {
1184							Node::Branch(children, None)
1185						} else {
1186							Node::NibbledBranch(partial.to_stored_range(common), children, None)
1187						}
1188					};
1189
1190					// always replace because whatever we get out here
1191					// is not the branch we started with.
1192					let branch_action =
1193						self.insert_inspector(branch, key, value, old_val)?.unwrap_node();
1194					InsertAction::Replace(branch_action)
1195				} else if !L::USE_EXTENSION {
1196					#[cfg(feature = "std")]
1197					trace!(target: "trie", "complete-prefix (common={:?}): AUGMENT-AT-END", common);
1198
1199					// fully-shared prefix for an extension.
1200					// make a stub branch
1201					let branch = Node::NibbledBranch(
1202						existing_key.to_stored(),
1203						empty_children(),
1204						Some(stored_value),
1205					);
1206					// augment the new branch.
1207					let branch = self.insert_inspector(branch, key, value, old_val)?.unwrap_node();
1208
1209					InsertAction::Replace(branch)
1210				} else if common == existing_key.len() {
1211					debug_assert!(L::USE_EXTENSION);
1212					#[cfg(feature = "std")]
1213					trace!(target: "trie", "complete-prefix (common={:?}): AUGMENT-AT-END", common);
1214
1215					// fully-shared prefix for an extension.
1216					// make a stub branch and an extension.
1217					let branch = Node::Branch(empty_children(), Some(stored_value));
1218					// augment the new branch.
1219					key.advance(common);
1220					let branch = self.insert_inspector(branch, key, value, old_val)?.unwrap_node();
1221
1222					// always replace since we took a leaf and made an extension.
1223					let leaf = self.storage.alloc(Stored::New(branch));
1224					InsertAction::Replace(Node::Extension(existing_key.to_stored(), leaf.into()))
1225				} else {
1226					debug_assert!(L::USE_EXTENSION);
1227					#[cfg(feature = "std")]
1228					trace!(
1229						target: "trie",
1230						"partially-shared-prefix (exist={:?}; new={:?}; common={:?}):\
1231							 AUGMENT-AT-END",
1232						existing_key.len(),
1233						partial.len(),
1234						common,
1235					);
1236
1237					// partially-shared prefix for an extension.
1238					// start by making a leaf.
1239					let low = Node::Leaf(existing_key.mid(common).to_stored(), stored_value);
1240
1241					// augment it. this will result in the Leaf -> common == 0 routine,
1242					// which creates a branch.
1243					key.advance(common);
1244					let augmented_low =
1245						self.insert_inspector(low, key, value, old_val)?.unwrap_node();
1246					// make an extension using it. this is a replacement.
1247					InsertAction::Replace(Node::Extension(
1248						existing_key.to_stored_range(common),
1249						self.storage.alloc(Stored::New(augmented_low)).into(),
1250					))
1251				}
1252			},
1253			Node::Extension(encoded, child_branch) => {
1254				debug_assert!(L::USE_EXTENSION);
1255				let existing_key = NibbleSlice::from_stored(&encoded);
1256				let common = partial.common_prefix(&existing_key);
1257				if common == 0 {
1258					#[cfg(feature = "std")]
1259					trace!(
1260						target: "trie",
1261						"no-common-prefix, not-both-empty (exist={:?}; new={:?}):\
1262							 TRANSMUTE,AUGMENT",
1263						existing_key.len(),
1264						partial.len(),
1265					);
1266
1267					// partial isn't empty: make a branch here
1268					// extensions may not have empty partial keys.
1269					assert!(!existing_key.is_empty());
1270					let idx = existing_key.at(0) as usize;
1271
1272					let mut children = empty_children();
1273					children[idx] = if existing_key.len() == 1 {
1274						// direct extension, just replace.
1275						Some(child_branch)
1276					} else {
1277						// No need to register set branch (was here before).
1278						// Note putting a branch in extension requires fix.
1279						let ext = Node::Extension(existing_key.mid(1).to_stored(), child_branch);
1280						Some(self.storage.alloc(Stored::New(ext)).into())
1281					};
1282
1283					// continue inserting.
1284					let branch_action = self
1285						.insert_inspector(Node::Branch(children, None), key, value, old_val)?
1286						.unwrap_node();
1287					InsertAction::Replace(branch_action)
1288				} else if common == existing_key.len() {
1289					#[cfg(feature = "std")]
1290					trace!(target: "trie", "complete-prefix (common={:?}): AUGMENT-AT-END", common);
1291
1292					// fully-shared prefix.
1293
1294					// insert into the child node.
1295					key.advance(common);
1296					let (new_child, changed) = self.insert_at(child_branch, key, value, old_val)?;
1297
1298					let new_ext = Node::Extension(existing_key.to_stored(), new_child.into());
1299
1300					// if the child branch wasn't changed, meaning this extension remains the same.
1301					if changed {
1302						InsertAction::Replace(new_ext)
1303					} else {
1304						InsertAction::Restore(new_ext)
1305					}
1306				} else {
1307					#[cfg(feature = "std")]
1308					trace!(
1309						target: "trie",
1310						"partially-shared-prefix (exist={:?}; new={:?}; common={:?}):\
1311							 AUGMENT-AT-END",
1312						existing_key.len(),
1313						partial.len(),
1314						common,
1315					);
1316
1317					// partially-shared.
1318					let low = Node::Extension(existing_key.mid(common).to_stored(), child_branch);
1319					// augment the extension. this will take the common == 0 path,
1320					// creating a branch.
1321					key.advance(common);
1322					let augmented_low =
1323						self.insert_inspector(low, key, value, old_val)?.unwrap_node();
1324
1325					// always replace, since this extension is not the one we started with.
1326					// this is known because the partial key is only the common prefix.
1327					InsertAction::Replace(Node::Extension(
1328						existing_key.to_stored_range(common),
1329						self.storage.alloc(Stored::New(augmented_low)).into(),
1330					))
1331				}
1332			},
1333		})
1334	}
1335
1336	/// Removes a node from the trie based on key.
1337	fn remove_at(
1338		&mut self,
1339		handle: NodeHandle<TrieHash<L>>,
1340		key: &mut NibbleFullKey,
1341		old_val: &mut Option<Value<L>>,
1342	) -> Result<Option<(StorageHandle, bool)>, TrieHash<L>, CError<L>> {
1343		let stored = match handle {
1344			NodeHandle::InMemory(h) => self.storage.destroy(h),
1345			NodeHandle::Hash(h) => {
1346				let handle = self.cache(h, key.left())?;
1347				self.storage.destroy(handle)
1348			},
1349		};
1350
1351		let opt = self.inspect(stored, key, move |trie, node, key| {
1352			trie.remove_inspector(node, key, old_val)
1353		})?;
1354
1355		Ok(opt.map(|(new, changed)| (self.storage.alloc(new), changed)))
1356	}
1357
1358	/// The removal inspector.
1359	fn remove_inspector(
1360		&mut self,
1361		node: Node<L>,
1362		key: &mut NibbleFullKey,
1363		old_val: &mut Option<Value<L>>,
1364	) -> Result<Action<L>, TrieHash<L>, CError<L>> {
1365		let partial = *key;
1366		Ok(match (node, partial.is_empty()) {
1367			(Node::Empty, _) => Action::Delete,
1368			(Node::Branch(c, None), true) => Action::Restore(Node::Branch(c, None)),
1369			(Node::NibbledBranch(n, c, None), true) =>
1370				Action::Restore(Node::NibbledBranch(n, c, None)),
1371			(Node::Branch(children, val), true) => {
1372				self.replace_old_value(old_val, val, key.left());
1373				// always replace since we took the value out.
1374				Action::Replace(self.fix(Node::Branch(children, None), *key)?)
1375			},
1376			(Node::NibbledBranch(n, children, val), true) => {
1377				self.replace_old_value(old_val, val, key.left());
1378				// always replace since we took the value out.
1379				Action::Replace(self.fix(Node::NibbledBranch(n, children, None), *key)?)
1380			},
1381			(Node::Branch(mut children, value), false) => {
1382				let idx = partial.at(0) as usize;
1383				if let Some(child) = children[idx].take() {
1384					#[cfg(feature = "std")]
1385					trace!(
1386						target: "trie",
1387						"removing value out of branch child, partial={:?}",
1388						partial,
1389					);
1390					let prefix = *key;
1391					key.advance(1);
1392					match self.remove_at(child, key, old_val)? {
1393						Some((new, changed)) => {
1394							children[idx] = Some(new.into());
1395							let branch = Node::Branch(children, value);
1396							match changed {
1397								// child was changed, so we were too.
1398								true => Action::Replace(branch),
1399								// unchanged, so we are too.
1400								false => Action::Restore(branch),
1401							}
1402						},
1403						None => {
1404							// the child we took was deleted.
1405							// the node may need fixing.
1406							#[cfg(feature = "std")]
1407							trace!(target: "trie", "branch child deleted, partial={:?}", partial);
1408							Action::Replace(self.fix(Node::Branch(children, value), prefix)?)
1409						},
1410					}
1411				} else {
1412					// no change needed.
1413					Action::Restore(Node::Branch(children, value))
1414				}
1415			},
1416			(Node::NibbledBranch(encoded, mut children, value), false) => {
1417				let (common, existing_length) = {
1418					let existing_key = NibbleSlice::from_stored(&encoded);
1419					(existing_key.common_prefix(&partial), existing_key.len())
1420				};
1421				if common == existing_length && common == partial.len() {
1422					// replace val
1423					if let Some(value) = value {
1424						let mut key_val = key.clone();
1425						key_val.advance(existing_length);
1426						self.replace_old_value(old_val, Some(value), key_val.left());
1427						let f = self.fix(Node::NibbledBranch(encoded, children, None), *key);
1428						Action::Replace(f?)
1429					} else {
1430						Action::Restore(Node::NibbledBranch(encoded, children, None))
1431					}
1432				} else if common < existing_length {
1433					// partway through an extension -- nothing to do here.
1434					Action::Restore(Node::NibbledBranch(encoded, children, value))
1435				} else {
1436					// common == existing_length && common < partial.len() : check children
1437					let idx = partial.at(common) as usize;
1438
1439					if let Some(child) = children[idx].take() {
1440						#[cfg(feature = "std")]
1441						trace!(
1442							target: "trie",
1443							"removing value out of branch child, partial={:?}",
1444							partial,
1445						);
1446						let prefix = *key;
1447						key.advance(common + 1);
1448						match self.remove_at(child, key, old_val)? {
1449							Some((new, changed)) => {
1450								children[idx] = Some(new.into());
1451								let branch = Node::NibbledBranch(encoded, children, value);
1452								match changed {
1453									// child was changed, so we were too.
1454									true => Action::Replace(branch),
1455									// unchanged, so we are too.
1456									false => Action::Restore(branch),
1457								}
1458							},
1459							None => {
1460								// the child we took was deleted.
1461								// the node may need fixing.
1462								#[cfg(feature = "std")]
1463								trace!(
1464									target: "trie",
1465									"branch child deleted, partial={:?}",
1466									partial,
1467								);
1468								Action::Replace(
1469									self.fix(
1470										Node::NibbledBranch(encoded, children, value),
1471										prefix,
1472									)?,
1473								)
1474							},
1475						}
1476					} else {
1477						// no change needed.
1478						Action::Restore(Node::NibbledBranch(encoded, children, value))
1479					}
1480				}
1481			},
1482			(Node::Leaf(encoded, value), _) => {
1483				let existing_key = NibbleSlice::from_stored(&encoded);
1484				if existing_key == partial {
1485					// this is the node we were looking for. Let's delete it.
1486					let mut key_val = key.clone();
1487					key_val.advance(existing_key.len());
1488					self.replace_old_value(old_val, Some(value), key_val.left());
1489					Action::Delete
1490				} else {
1491					// leaf the node alone.
1492					#[cfg(feature = "std")]
1493					trace!(
1494						target: "trie",
1495						"restoring leaf wrong partial, partial={:?}, existing={:?}",
1496						partial,
1497						NibbleSlice::from_stored(&encoded),
1498					);
1499					Action::Restore(Node::Leaf(encoded, value))
1500				}
1501			},
1502			(Node::Extension(encoded, child_branch), _) => {
1503				let (common, existing_length) = {
1504					let existing_key = NibbleSlice::from_stored(&encoded);
1505					(existing_key.common_prefix(&partial), existing_key.len())
1506				};
1507				if common == existing_length {
1508					// try to remove from the child branch.
1509					#[cfg(feature = "std")]
1510					trace!(target: "trie", "removing from extension child, partial={:?}", partial);
1511					let prefix = *key;
1512					key.advance(common);
1513					match self.remove_at(child_branch, key, old_val)? {
1514						Some((new_child, changed)) => {
1515							// if the child branch was unchanged, then the extension is too.
1516							// otherwise, this extension may need fixing.
1517							match changed {
1518								true => Action::Replace(
1519									self.fix(Node::Extension(encoded, new_child.into()), prefix)?,
1520								),
1521								false =>
1522									Action::Restore(Node::Extension(encoded, new_child.into())),
1523							}
1524						},
1525						None => {
1526							// the whole branch got deleted.
1527							// that means that this extension is useless.
1528							Action::Delete
1529						},
1530					}
1531				} else {
1532					// partway through an extension -- nothing to do here.
1533					Action::Restore(Node::Extension(encoded, child_branch))
1534				}
1535			},
1536		})
1537	}
1538
1539	/// Given a node which may be in an _invalid state_, fix it such that it is then in a valid
1540	/// state.
1541	///
1542	/// _invalid state_ means:
1543	/// - Branch node where there is only a single entry;
1544	/// - Extension node followed by anything other than a Branch node.
1545	fn fix(&mut self, node: Node<L>, key: NibbleSlice) -> Result<Node<L>, TrieHash<L>, CError<L>> {
1546		self.fix_inner(node, key, false)
1547	}
1548	fn fix_inner(
1549		&mut self,
1550		node: Node<L>,
1551		key: NibbleSlice,
1552		recurse_extension: bool,
1553	) -> Result<Node<L>, TrieHash<L>, CError<L>> {
1554		match node {
1555			Node::Branch(mut children, value) => {
1556				// if only a single value, transmute to leaf/extension and feed through fixed.
1557				#[cfg_attr(feature = "std", derive(Debug))]
1558				enum UsedIndex {
1559					None,
1560					One(u8),
1561					Many,
1562				}
1563				let mut used_index = UsedIndex::None;
1564				for i in 0..16 {
1565					match (children[i].is_none(), &used_index) {
1566						(false, &UsedIndex::None) => used_index = UsedIndex::One(i as u8),
1567						(false, &UsedIndex::One(_)) => {
1568							used_index = UsedIndex::Many;
1569							break
1570						},
1571						_ => continue,
1572					}
1573				}
1574
1575				match (used_index, value) {
1576					(UsedIndex::None, None) => {
1577						panic!("Branch with no subvalues. Something went wrong.")
1578					},
1579					(UsedIndex::One(a), None) => {
1580						// only one onward node. make an extension.
1581
1582						let new_partial = NibbleSlice::new_offset(&[a], 1).to_stored();
1583						let child = children[a as usize]
1584							.take()
1585							.expect("used_index only set if occupied; qed");
1586						let new_node = Node::Extension(new_partial, child);
1587						self.fix(new_node, key)
1588					},
1589					(UsedIndex::None, Some(value)) => {
1590						// make a leaf.
1591						#[cfg(feature = "std")]
1592						trace!(target: "trie", "fixing: branch -> leaf");
1593						Ok(Node::Leaf(NibbleSlice::new(&[]).to_stored(), value))
1594					},
1595					(_, value) => {
1596						// all is well.
1597						#[cfg(feature = "std")]
1598						trace!(target: "trie", "fixing: restoring branch");
1599						Ok(Node::Branch(children, value))
1600					},
1601				}
1602			},
1603			Node::NibbledBranch(enc_nibble, mut children, value) => {
1604				// if only a single value, transmute to leaf/extension and feed through fixed.
1605				#[cfg_attr(feature = "std", derive(Debug))]
1606				enum UsedIndex {
1607					None,
1608					One(u8),
1609					Many,
1610				}
1611				let mut used_index = UsedIndex::None;
1612				for i in 0..16 {
1613					match (children[i].is_none(), &used_index) {
1614						(false, &UsedIndex::None) => used_index = UsedIndex::One(i as u8),
1615						(false, &UsedIndex::One(_)) => {
1616							used_index = UsedIndex::Many;
1617							break
1618						},
1619						_ => continue,
1620					}
1621				}
1622
1623				match (used_index, value) {
1624					(UsedIndex::None, None) => {
1625						panic!("Branch with no subvalues. Something went wrong.")
1626					},
1627					(UsedIndex::One(a), None) => {
1628						// only one onward node. use child instead
1629						let child = children[a as usize]
1630							.take()
1631							.expect("used_index only set if occupied; qed");
1632						let mut key2 = key.clone();
1633						key2.advance(
1634							(enc_nibble.1.len() * nibble_ops::NIBBLE_PER_BYTE) - enc_nibble.0,
1635						);
1636						let (start, alloc_start, prefix_end) = match key2.left() {
1637							(start, None) => (start, None, Some(nibble_ops::push_at_left(0, a, 0))),
1638							(start, Some(v)) => {
1639								let mut so: BackingByteVec = start.into();
1640								so.push(nibble_ops::pad_left(v) | a);
1641								(start, Some(so), None)
1642							},
1643						};
1644						let child_prefix = (
1645							alloc_start.as_ref().map(|start| &start[..]).unwrap_or(start),
1646							prefix_end,
1647						);
1648						let stored = match child {
1649							NodeHandle::InMemory(h) => self.storage.destroy(h),
1650							NodeHandle::Hash(h) => {
1651								let handle = self.cache(h, child_prefix)?;
1652								self.storage.destroy(handle)
1653							},
1654						};
1655						let child_node = match stored {
1656							Stored::New(node) => node,
1657							Stored::Cached(node, hash) => {
1658								self.death_row
1659									.insert((hash, (child_prefix.0[..].into(), child_prefix.1)));
1660								node
1661							},
1662						};
1663						match child_node {
1664							Node::Leaf(sub_partial, value) => {
1665								let mut enc_nibble = enc_nibble;
1666								combine_key(
1667									&mut enc_nibble,
1668									(nibble_ops::NIBBLE_PER_BYTE - 1, &[a][..]),
1669								);
1670								combine_key(&mut enc_nibble, (sub_partial.0, &sub_partial.1[..]));
1671								Ok(Node::Leaf(enc_nibble, value))
1672							},
1673							Node::NibbledBranch(sub_partial, ch_children, ch_value) => {
1674								let mut enc_nibble = enc_nibble;
1675								combine_key(
1676									&mut enc_nibble,
1677									(nibble_ops::NIBBLE_PER_BYTE - 1, &[a][..]),
1678								);
1679								combine_key(&mut enc_nibble, (sub_partial.0, &sub_partial.1[..]));
1680								Ok(Node::NibbledBranch(enc_nibble, ch_children, ch_value))
1681							},
1682							_ => unreachable!(),
1683						}
1684					},
1685					(UsedIndex::None, Some(value)) => {
1686						// make a leaf.
1687						#[cfg(feature = "std")]
1688						trace!(target: "trie", "fixing: branch -> leaf");
1689						Ok(Node::Leaf(enc_nibble, value))
1690					},
1691					(_, value) => {
1692						// all is well.
1693						#[cfg(feature = "std")]
1694						trace!(target: "trie", "fixing: restoring branch");
1695						Ok(Node::NibbledBranch(enc_nibble, children, value))
1696					},
1697				}
1698			},
1699			Node::Extension(partial, child) => {
1700				let mut key2 = key.clone();
1701				let (start, alloc_start, prefix_end) = if !recurse_extension {
1702					// We could advance key, but this code can also be called
1703					// recursively, so there might be some prefix from branch.
1704					let last = partial.1[partial.1.len() - 1] & (255 >> 4);
1705					key2.advance((partial.1.len() * nibble_ops::NIBBLE_PER_BYTE) - partial.0 - 1);
1706					match key2.left() {
1707						(start, None) => (start, None, Some(nibble_ops::push_at_left(0, last, 0))),
1708						(start, Some(v)) => {
1709							let mut so: BackingByteVec = start.into();
1710							// Complete last byte with `last`.
1711							so.push(nibble_ops::pad_left(v) | last);
1712							(start, Some(so), None)
1713						},
1714					}
1715				} else {
1716					let k2 = key2.left();
1717
1718					let mut so: NibbleVec = Default::default();
1719					so.append_optional_slice_and_nibble(Some(&NibbleSlice::new(k2.0)), None);
1720					if let Some(n) = k2.1 {
1721						so.push(n >> nibble_ops::BIT_PER_NIBBLE);
1722					}
1723					so.append_optional_slice_and_nibble(
1724						Some(&NibbleSlice::from_stored(&partial)),
1725						None,
1726					);
1727					let so = so.as_prefix();
1728					(k2.0, Some(so.0.into()), so.1)
1729				};
1730				let child_prefix =
1731					(alloc_start.as_ref().map(|start| &start[..]).unwrap_or(start), prefix_end);
1732
1733				let stored = match child {
1734					NodeHandle::InMemory(h) => self.storage.destroy(h),
1735					NodeHandle::Hash(h) => {
1736						let handle = self.cache(h, child_prefix)?;
1737						self.storage.destroy(handle)
1738					},
1739				};
1740
1741				let (child_node, maybe_hash) = match stored {
1742					Stored::New(node) => (node, None),
1743					Stored::Cached(node, hash) => (node, Some(hash)),
1744				};
1745
1746				match child_node {
1747					Node::Extension(sub_partial, sub_child) => {
1748						// combine with node below.
1749						if let Some(hash) = maybe_hash {
1750							// delete the cached child since we are going to replace it.
1751							self.death_row
1752								.insert((hash, (child_prefix.0[..].into(), child_prefix.1)));
1753						}
1754						// subpartial
1755						let mut partial = partial;
1756						combine_key(&mut partial, (sub_partial.0, &sub_partial.1[..]));
1757						#[cfg(feature = "std")]
1758						trace!(
1759							target: "trie",
1760							"fixing: extension combination. new_partial={:?}",
1761							partial,
1762						);
1763
1764						self.fix_inner(Node::Extension(partial, sub_child), key.into(), true)
1765					},
1766					Node::Leaf(sub_partial, value) => {
1767						// combine with node below.
1768						if let Some(hash) = maybe_hash {
1769							// delete the cached child since we are going to replace it.
1770							self.death_row
1771								.insert((hash, (child_prefix.0[..].into(), child_prefix.1)));
1772						}
1773						// subpartial oly
1774						let mut partial = partial;
1775						combine_key(&mut partial, (sub_partial.0, &sub_partial.1[..]));
1776						#[cfg(feature = "std")]
1777						trace!(
1778							target: "trie",
1779							"fixing: extension -> leaf. new_partial={:?}",
1780							partial,
1781						);
1782						Ok(Node::Leaf(partial, value))
1783					},
1784					child_node => {
1785						#[cfg(feature = "std")]
1786						trace!(target: "trie", "fixing: restoring extension");
1787
1788						// reallocate the child node.
1789						let stored = if let Some(hash) = maybe_hash {
1790							Stored::Cached(child_node, hash)
1791						} else {
1792							Stored::New(child_node)
1793						};
1794
1795						Ok(Node::Extension(partial, self.storage.alloc(stored).into()))
1796					},
1797				}
1798			},
1799			other => Ok(other), // only ext and branch need fixing.
1800		}
1801	}
1802
1803	/// Commit the in-memory changes to disk, freeing their storage and
1804	/// updating the state root.
1805	pub fn commit(&mut self) {
1806		#[cfg(feature = "std")]
1807		trace!(target: "trie", "Committing trie changes to db.");
1808
1809		//   // always kill all the nodes on death row.
1810		//   #[cfg(feature = "std")]
1811		//   trace!(target: "trie", "{:?} nodes to remove from db", self.death_row.len());
1812
1813		//   #[cfg(feature = "std")]
1814		//   for (hash, prefix) in self.death_row.drain() {
1815		//   	self.db.remove(&hash, (&prefix.0[..], prefix.1));
1816		//   }
1817
1818		//   #[cfg(not(feature = "std"))]
1819		//   for (hash, prefix) in core::mem::take(&mut self.death_row).into_iter() {
1820		//   	self.db.remove(&hash, (&prefix.0[..], prefix.1));
1821		//   }
1822
1823		self.death_row.clear();
1824
1825		let handle = match self.root_handle() {
1826			NodeHandle::Hash(_) => return, // no changes necessary.
1827			NodeHandle::InMemory(h) => h,
1828		};
1829
1830		match self.storage.destroy(handle) {
1831			Stored::New(node) => {
1832				// Reconstructs the full key for root node.
1833				let full_key = self.cache.as_ref().and_then(|_| {
1834					node.partial_key().and_then(|k| Some(NibbleSlice::from_stored(k).into()))
1835				});
1836
1837				let mut k = NibbleVec::new();
1838
1839				let encoded_root = node.into_encoded(|node, o_slice, o_index| {
1840					let mov = k.append_optional_slice_and_nibble(o_slice, o_index);
1841					match node {
1842						NodeToEncode::Node(value) => {
1843							let value_hash = self.db.insert(k.as_prefix(), value);
1844							self.cache_value(k.inner(), value, value_hash);
1845							k.drop_lasts(mov);
1846							ChildReference::Hash(value_hash)
1847						},
1848						NodeToEncode::TrieNode(child) => {
1849							let result = self.commit_child(child, &mut k);
1850							k.drop_lasts(mov);
1851							result
1852						},
1853					}
1854				});
1855				#[cfg(feature = "std")]
1856				trace!(target: "trie", "encoded root node: {:?}", ToHex(&encoded_root[..]));
1857
1858				*self.root = self.db.insert(EMPTY_PREFIX, &encoded_root);
1859
1860				self.cache_node(*self.root, &encoded_root, full_key);
1861
1862				self.root_handle = NodeHandle::Hash(*self.root);
1863			},
1864			Stored::Cached(node, hash) => {
1865				// probably won't happen, but update the root and move on.
1866				*self.root = hash;
1867				self.root_handle =
1868					NodeHandle::InMemory(self.storage.alloc(Stored::Cached(node, hash)));
1869			},
1870		}
1871	}
1872
1873	/// Cache the given `encoded` node.
1874	fn cache_node(&mut self, hash: TrieHash<L>, encoded: &[u8], full_key: Option<NibbleVec>) {
1875		// If we have a cache, cache our node directly.
1876		if let Some(cache) = self.cache.as_mut() {
1877			let node = cache.get_or_insert_node(hash, &mut || {
1878				Ok(L::Codec::decode(&encoded)
1879					.ok()
1880					.and_then(|n| n.to_owned_node::<L>().ok())
1881					.expect("Just encoded the node, so it should decode without any errors; qed"))
1882			});
1883
1884			// `node` should always be `OK`, but let's play it safe.
1885			let node = if let Ok(node) = node { node } else { return };
1886
1887			let mut values_to_cache = Vec::new();
1888
1889			// If the given node has data attached, the `full_key` is the full key to this node.
1890			if let Some(full_key) = full_key {
1891				node.data().and_then(|v| node.data_hash().map(|h| (&full_key, v, h))).map(
1892					|(k, v, h)| {
1893						values_to_cache.push((k.inner().to_vec(), (v.clone(), h).into()));
1894					},
1895				);
1896
1897				fn cache_child_values<L: TrieLayout>(
1898					node: &NodeOwned<TrieHash<L>>,
1899					values_to_cache: &mut Vec<(Vec<u8>, CachedValue<TrieHash<L>>)>,
1900					full_key: NibbleVec,
1901				) {
1902					node.child_iter().flat_map(|(n, c)| c.as_inline().map(|c| (n, c))).for_each(
1903						|(n, c)| {
1904							let mut key = full_key.clone();
1905							n.map(|n| key.push(n));
1906							c.partial_key().map(|p| key.append(p));
1907
1908							if let Some((hash, data)) =
1909								c.data().and_then(|d| c.data_hash().map(|h| (h, d)))
1910							{
1911								values_to_cache
1912									.push((key.inner().to_vec(), (data.clone(), hash).into()));
1913							}
1914
1915							cache_child_values::<L>(c, values_to_cache, key);
1916						},
1917					);
1918				}
1919
1920				// Also cache values of inline nodes.
1921				cache_child_values::<L>(&node, &mut values_to_cache, full_key.clone());
1922			}
1923
1924			values_to_cache.into_iter().for_each(|(k, v)| cache.cache_value_for_key(&k, v));
1925		}
1926	}
1927
1928	/// Cache the given `value`.
1929	///
1930	/// `hash` is the hash of `value`.
1931	fn cache_value(&mut self, full_key: &[u8], value: impl Into<Bytes>, hash: TrieHash<L>) {
1932		if let Some(cache) = self.cache.as_mut() {
1933			let value = value.into();
1934
1935			// `get_or_insert` should always return `Ok`, but be safe.
1936			let value = if let Ok(value) = cache
1937				.get_or_insert_node(hash, &mut || Ok(NodeOwned::Value(value.clone(), hash)))
1938				.map(|n| n.data().cloned())
1939			{
1940				value
1941			} else {
1942				None
1943			};
1944
1945			if let Some(value) = value {
1946				cache.cache_value_for_key(full_key, (value, hash).into())
1947			}
1948		}
1949	}
1950
1951	/// Commit a node by hashing it and writing it to the db. Returns a
1952	/// `ChildReference` which in most cases carries a normal hash but for the
1953	/// case where we can fit the actual data in the `Hasher`s output type, we
1954	/// store the data inline. This function is used as the callback to the
1955	/// `into_encoded` method of `Node`.
1956	fn commit_child(
1957		&mut self,
1958		handle: NodeHandle<TrieHash<L>>,
1959		prefix: &mut NibbleVec,
1960	) -> ChildReference<TrieHash<L>> {
1961		match handle {
1962			NodeHandle::Hash(hash) => ChildReference::Hash(hash),
1963			NodeHandle::InMemory(storage_handle) => {
1964				match self.storage.destroy(storage_handle) {
1965					Stored::Cached(_, hash) => ChildReference::Hash(hash),
1966					Stored::New(node) => {
1967						// Reconstructs the full key
1968						let full_key = self.cache.as_ref().and_then(|_| {
1969							let mut prefix = prefix.clone();
1970							if let Some(partial) = node.partial_key() {
1971								prefix.append_partial(NibbleSlice::from_stored(partial).right());
1972							}
1973							Some(prefix)
1974						});
1975
1976						let encoded = {
1977							let commit_child = |node: NodeToEncode<TrieHash<L>>,
1978							                    o_slice: Option<&NibbleSlice>,
1979							                    o_index: Option<u8>| {
1980								let mov = prefix.append_optional_slice_and_nibble(o_slice, o_index);
1981								match node {
1982									NodeToEncode::Node(value) => {
1983										let value_hash = self.db.insert(prefix.as_prefix(), value);
1984
1985										self.cache_value(prefix.inner(), value, value_hash);
1986
1987										prefix.drop_lasts(mov);
1988										ChildReference::Hash(value_hash)
1989									},
1990									NodeToEncode::TrieNode(node_handle) => {
1991										let result = self.commit_child(node_handle, prefix);
1992										prefix.drop_lasts(mov);
1993										result
1994									},
1995								}
1996							};
1997							node.into_encoded(commit_child)
1998						};
1999						if encoded.len() >= L::Hash::LENGTH {
2000							let hash = self.db.insert(prefix.as_prefix(), &encoded);
2001
2002							self.cache_node(hash, &encoded, full_key);
2003
2004							ChildReference::Hash(hash)
2005						} else {
2006							// it's a small value, so we cram it into a `TrieHash<L>`
2007							// and tag with length
2008							let mut h = <TrieHash<L>>::default();
2009							let len = encoded.len();
2010							h.as_mut()[..len].copy_from_slice(&encoded[..len]);
2011
2012							ChildReference::Inline(h, len)
2013						}
2014					},
2015				}
2016			},
2017		}
2018	}
2019
2020	// a hack to get the root node's handle
2021	fn root_handle(&self) -> NodeHandle<TrieHash<L>> {
2022		match self.root_handle {
2023			NodeHandle::Hash(h) => NodeHandle::Hash(h),
2024			NodeHandle::InMemory(StorageHandle(x)) => NodeHandle::InMemory(StorageHandle(x)),
2025		}
2026	}
2027}
2028
2029impl<'a, L> TrieMut<L> for TrieDBMut<'a, L>
2030where
2031	L: TrieLayout,
2032{
2033	fn root(&mut self) -> &TrieHash<L> {
2034		self.commit();
2035		self.root
2036	}
2037
2038	fn is_empty(&self) -> bool {
2039		match self.root_handle {
2040			NodeHandle::Hash(h) => h == L::Codec::hashed_null_node(),
2041			NodeHandle::InMemory(ref h) => match self.storage[h] {
2042				Node::Empty => true,
2043				_ => false,
2044			},
2045		}
2046	}
2047
2048	fn get<'x, 'key>(&'x self, key: &'key [u8]) -> Result<Option<DBValue>, TrieHash<L>, CError<L>>
2049	where
2050		'x: 'key,
2051	{
2052		self.lookup(key, NibbleSlice::new(key), &self.root_handle)
2053	}
2054
2055	fn insert(
2056		&mut self,
2057		key: &[u8],
2058		value: &[u8],
2059	) -> Result<Option<Value<L>>, TrieHash<L>, CError<L>> {
2060		if !L::ALLOW_EMPTY && value.is_empty() {
2061			return self.remove(key)
2062		}
2063
2064		let mut old_val = None;
2065
2066		#[cfg(feature = "std")]
2067		trace!(target: "trie", "insert: key={:?}, value={:?}", ToHex(key), ToHex(&value));
2068
2069		let value = Bytes::from(value);
2070		let root_handle = self.root_handle();
2071		let (new_handle, _changed) =
2072			self.insert_at(root_handle, &mut NibbleSlice::new(key), value, &mut old_val)?;
2073
2074		#[cfg(feature = "std")]
2075		trace!(target: "trie", "insert: altered trie={}", _changed);
2076		self.root_handle = NodeHandle::InMemory(new_handle);
2077
2078		Ok(old_val)
2079	}
2080
2081	fn remove(&mut self, key: &[u8]) -> Result<Option<Value<L>>, TrieHash<L>, CError<L>> {
2082		#[cfg(feature = "std")]
2083		trace!(target: "trie", "remove: key={:?}", ToHex(key));
2084
2085		let root_handle = self.root_handle();
2086		let mut key_slice = NibbleSlice::new(key);
2087		let mut old_val = None;
2088
2089		match self.remove_at(root_handle, &mut key_slice, &mut old_val)? {
2090			Some((handle, _changed)) => {
2091				#[cfg(feature = "std")]
2092				trace!(target: "trie", "remove: altered trie={}", _changed);
2093				self.root_handle = NodeHandle::InMemory(handle);
2094			},
2095			None => {
2096				#[cfg(feature = "std")]
2097				trace!(target: "trie", "remove: obliterated trie");
2098				self.root_handle = NodeHandle::Hash(L::Codec::hashed_null_node());
2099				*self.root = L::Codec::hashed_null_node();
2100			},
2101		}
2102
2103		Ok(old_val)
2104	}
2105}
2106
2107impl<'a, L> Drop for TrieDBMut<'a, L>
2108where
2109	L: TrieLayout,
2110{
2111	fn drop(&mut self) {
2112		self.commit();
2113	}
2114}
2115
2116/// combine two NodeKeys
2117fn combine_key(start: &mut NodeKey, end: (usize, &[u8])) {
2118	debug_assert!(start.0 < nibble_ops::NIBBLE_PER_BYTE);
2119	debug_assert!(end.0 < nibble_ops::NIBBLE_PER_BYTE);
2120	let final_offset = (start.0 + end.0) % nibble_ops::NIBBLE_PER_BYTE;
2121	let _shifted = nibble_ops::shift_key(start, final_offset);
2122	let st = if end.0 > 0 {
2123		let sl = start.1.len();
2124		start.1[sl - 1] |= nibble_ops::pad_right(end.1[0]);
2125		1
2126	} else {
2127		0
2128	};
2129	(st..end.1.len()).for_each(|i| start.1.push(end.1[i]));
2130}
2131
2132#[cfg(test)]
2133mod tests {
2134	use crate::nibble::BackingByteVec;
2135
2136	#[test]
2137	fn combine_test() {
2138		let a: BackingByteVec = [0x12, 0x34][..].into();
2139		let b: &[u8] = [0x56, 0x78][..].into();
2140		let test_comb = |a: (_, &BackingByteVec), b, c| {
2141			let mut a = (a.0, a.1.clone());
2142			super::combine_key(&mut a, b);
2143			assert_eq!((a.0, &a.1[..]), c);
2144		};
2145		test_comb((0, &a), (0, &b), (0, &[0x12, 0x34, 0x56, 0x78][..]));
2146		test_comb((1, &a), (0, &b), (1, &[0x12, 0x34, 0x56, 0x78][..]));
2147		test_comb((0, &a), (1, &b), (1, &[0x01, 0x23, 0x46, 0x78][..]));
2148		test_comb((1, &a), (1, &b), (0, &[0x23, 0x46, 0x78][..]));
2149	}
2150}