bitstring_trees/tree/
mod.rs

1//! generic map of bit strings prefixes to values
2//!
3//! This is a very generic abstraction and therefore not easy to use.
4//!
5//! Look for other containers in this crate that offer specific use cases.
6
7use alloc::boxed::Box;
8use bitstring::BitString;
9use core::{
10	fmt,
11	mem::{
12		replace,
13		swap,
14		take,
15	},
16	ptr::NonNull,
17};
18use goto::LookupStepWith;
19
20use crate::walk_mut::NodeOrTree;
21
22use self::goto::NodeRef as _;
23
24pub use self::{
25	goto::{
26		InsertPosition,
27		InsertPositionWith,
28	},
29	iter::{
30		IterInOrder,
31		IterLeaf,
32		IterLeafFull,
33		IterPostOrder,
34		IterPreOrder,
35	},
36	mut_borrowed::{
37		IterMutBorrowedInOrder,
38		IterMutBorrowedLeaf,
39		IterMutBorrowedLeafFull,
40		IterMutBorrowedPostOrder,
41		IterMutBorrowedPreOrder,
42		IterWalkMutBorrowedPath,
43		WalkMutBorrowed,
44		WalkMutBorrowedPath,
45	},
46	mut_gen::IterMutPath,
47	mut_owned::{
48		IterMutOwnedInOrder,
49		IterMutOwnedLeaf,
50		IterMutOwnedLeafFull,
51		IterMutOwnedPostOrder,
52		IterMutOwnedPreOrder,
53		IterWalkMutOwnedPath,
54		WalkMutOwned,
55		WalkMutOwnedPath,
56	},
57	path::{
58		IterPath,
59		MutPath,
60	},
61	walk::Walk,
62	walk_dir::WalkedDirection,
63};
64
65mod goto;
66mod iter;
67mod mut_borrowed;
68mod mut_gen;
69mod mut_owned;
70mod path;
71mod walk;
72mod walk_dir;
73
74/// Define Tree behavior
75pub trait TreeProperties {
76	/// Bitstring key
77	type Key: BitString + Clone;
78	/// Value attached to all inner and leaf nodes
79	type Value: Default;
80	/// Value attached to leaf nodes only
81	type LeafValue: Clone + Default;
82
83	/// Used to compare leaf values to allow combining of leafs.
84	/// (Only used when LEAF_EMPTY=false);
85	type LeafValueComparer: LeafValueComparer<Self::LeafValue>;
86
87	/// Whether value is insignificant (inner nodes can be removed)
88	///
89	/// When true `Value` should be `()`.
90	const EMPTY: bool;
91
92	/// Whether leaf value is insignificant (leafs won't
93	/// cloned down a path to insert a new leaf - new leaf
94	/// gets ignored if a parent leaf is present).
95	///
96	/// Most operations won't touch the set of covered bitstrings
97	/// by leaf nodes unless that is their explicit goal.
98	///
99	/// When true `LeafValue` should be `()`.
100	const LEAF_EMPTY: bool;
101
102	/// Whether to completely ignore leafs and the bitstrings they cover.
103	///
104	/// Use this if you only care about the inner `Value`s.
105	///
106	/// If set `LEAF_EMPTY` must be set too.
107	const IGNORE_LEAFS: bool;
108}
109
110const fn tp_valid<TP: TreeProperties>() -> bool {
111	if TP::IGNORE_LEAFS && !TP::LEAF_EMPTY {
112		return false;
113	}
114
115	if TP::EMPTY && TP::IGNORE_LEAFS {
116		return false;
117	} // useless tree
118
119	// if TP::EMPTY && !is_empty_tuple::<TP::Value>() { return false; }
120	// if TP::LEAF_EMPTY && !is_empty_tuple::<TP::LeafValue>() { return false; }
121
122	true
123}
124
125/// Define how to compare leaf values in tree
126pub trait LeafValueComparer<V> {
127	/// Whether two leaf values are equal and can be merged if they are neighbors keys
128	fn eq(a: &V, b: &V) -> bool;
129}
130
131/// Use [`Eq`] for [`LeafValueComparer`]
132pub struct DefaultCompare;
133
134impl<V: Eq> LeafValueComparer<V> for DefaultCompare {
135	#[inline]
136	fn eq(a: &V, b: &V) -> bool {
137		a == b
138	}
139}
140
141/// Define no leaf values to be equal for [`LeafValueComparer`]
142pub struct NoEqual;
143
144impl<V> LeafValueComparer<V> for NoEqual {
145	#[inline]
146	fn eq(_a: &V, _b: &V) -> bool {
147		false
148	}
149}
150
151/// Node in tree
152pub struct Node<TP: TreeProperties> {
153	key: TP::Key,
154	value: TP::Value,
155	state: NodeState<TP>,
156}
157
158impl<TP> Clone for Node<TP>
159where
160	TP: TreeProperties,
161	TP::Value: Clone,
162{
163	fn clone(&self) -> Self {
164		Self {
165			key: self.key.clone(),
166			value: self.value.clone(),
167			state: self.state.clone(),
168		}
169	}
170}
171
172impl<TP> fmt::Debug for Node<TP>
173where
174	TP: TreeProperties,
175	TP::Key: fmt::Debug,
176	TP::Value: fmt::Debug,
177	TP::LeafValue: fmt::Debug,
178{
179	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
180		match self.state {
181			NodeState::Leaf { ref value } => write!(
182				f,
183				"Leaf {{ key: {:?}, inner: {:?}, value: {:?} }}",
184				self.key, self.value, value,
185			),
186			NodeState::InnerNode { ref children } => write!(
187				f,
188				"InnerNode {{ key: {:?}, inner: {:?}, left: {:?}, right: {:?} }}",
189				self.key, self.value, children.left, children.right,
190			),
191		}
192	}
193}
194
195impl<TP: TreeProperties> Node<TP> {
196	#[inline]
197	fn _is_prefix_of(&self, key: &TP::Key, key_len: usize) -> bool {
198		goto::is_prefix(&self.key, self.key.len(), key, key_len)
199	}
200
201	/// Get key of node
202	#[inline]
203	pub fn get_key(&self) -> &TP::Key {
204		&self.key
205	}
206
207	/// Get value of node
208	#[inline]
209	pub fn get_value(&self) -> &TP::Value {
210		&self.value
211	}
212
213	/// Get mutable value of node
214	#[inline]
215	pub fn get_value_mut(&mut self) -> &mut TP::Value {
216		&mut self.value
217	}
218
219	/// Whether node is a leaf
220	#[inline]
221	pub fn is_leaf(&self) -> bool {
222		matches!(self.state, NodeState::Leaf { .. })
223	}
224
225	/// Return reference to leaf value if node is a leaf
226	#[inline]
227	pub fn get_leaf_value(&self) -> Option<&TP::LeafValue> {
228		match self.state {
229			NodeState::Leaf { ref value } => Some(value),
230			_ => None,
231		}
232	}
233
234	/// Return mutable reference to leaf value if node is a leaf
235	#[inline]
236	pub fn get_leaf_value_mut(&mut self) -> Option<&mut TP::LeafValue> {
237		match self.state {
238			NodeState::Leaf { ref mut value } => Some(value),
239			_ => None,
240		}
241	}
242
243	/// Make node a leaf node (i.e. drop potential child nodes) and set leaf value
244	#[inline]
245	pub fn set_leaf_value(&mut self, value: TP::LeafValue) -> &mut TP::LeafValue {
246		self.state = NodeState::Leaf { value };
247		match self.state {
248			NodeState::Leaf { ref mut value } => value,
249			_ => unreachable!(),
250		}
251	}
252
253	/// Return mutable reference to leaf value
254	///
255	/// If node isn't a leaf, make it one and initialize it with given constructor
256	pub fn get_or_make_leaf_value_with<F>(&mut self, f: F) -> &mut TP::LeafValue
257	where
258		F: FnOnce() -> TP::LeafValue,
259	{
260		match self.state {
261			NodeState::Leaf { .. } => (),
262			NodeState::InnerNode { .. } => {
263				self.state = NodeState::Leaf { value: f() };
264			},
265		}
266		match self.state {
267			NodeState::Leaf { ref mut value } => value,
268			_ => unreachable!(),
269		}
270	}
271
272	/// Return reference to (left, right) child nodes unless node is a leaf
273	#[inline]
274	pub fn get_children(&self) -> Option<(&Self, &Self)> {
275		match self.state {
276			NodeState::InnerNode { ref children } => Some((&children.left, &children.right)),
277			_ => None,
278		}
279	}
280
281	/// Return mutable reference to (left, right) child nodes unless node is a leaf
282	#[inline]
283	pub fn get_children_mut(&mut self) -> Option<(&mut Self, &mut Self)> {
284		match self.state {
285			NodeState::InnerNode { ref mut children } => {
286				Some((&mut children.left, &mut children.right))
287			},
288			_ => None,
289		}
290	}
291
292	/// Return reference to left child node unless node is a leaf
293	#[inline]
294	pub fn get_left(&self) -> Option<&Self> {
295		match self.state {
296			NodeState::InnerNode { ref children } => Some(&children.left),
297			_ => None,
298		}
299	}
300
301	/// Return mutable reference to left child node unless node is a leaf
302	#[inline]
303	pub fn get_left_mut(&mut self) -> Option<&mut Self> {
304		match self.state {
305			NodeState::InnerNode { ref mut children } => Some(&mut children.left),
306			_ => None,
307		}
308	}
309
310	/// Return reference to right child node unless node is a leaf
311	#[inline]
312	pub fn get_right(&self) -> Option<&Self> {
313		match self.state {
314			NodeState::InnerNode { ref children } => Some(&children.right),
315			_ => None,
316		}
317	}
318
319	/// Return mutable reference to right child node unless node is a leaf
320	#[inline]
321	pub fn get_right_mut(&mut self) -> Option<&mut Self> {
322		match self.state {
323			NodeState::InnerNode { ref mut children } => Some(&mut children.right),
324			_ => None,
325		}
326	}
327
328	/// Return reference to requested child node unless node is a leaf
329	///
330	/// `false` returns left and `true` returns right node.
331	#[inline]
332	pub fn get_child(&self, side_bit: bool) -> Option<&Node<TP>> {
333		match self.state {
334			NodeState::InnerNode { ref children } => Some({
335				if side_bit {
336					&children.right
337				} else {
338					&children.left
339				}
340			}),
341			_ => None,
342		}
343	}
344
345	/// Return mutable reference to requested child node unless node is a leaf
346	///
347	/// `false` returns left and `true` returns right node.
348	#[inline]
349	pub fn get_child_mut(&mut self, side_bit: bool) -> Option<&mut Node<TP>> {
350		match self.state {
351			NodeState::InnerNode { ref mut children } => Some({
352				if side_bit {
353					&mut children.right
354				} else {
355					&mut children.left
356				}
357			}),
358			_ => None,
359		}
360	}
361
362	fn new_leaf(key: TP::Key, inner: TP::Value, value: TP::LeafValue) -> Self {
363		Self {
364			key,
365			value: inner,
366			state: NodeState::Leaf { value },
367		}
368	}
369
370	// test whether two nodes can be combined because their leaf values are equal
371	//
372	// with real values (TP::EMPTY = false) we should never combines leaf nodes.
373	// if leaf values are empty too we don't need to actually compare data.
374	fn leaf_value_eq(a: &TP::LeafValue, b: &TP::LeafValue) -> bool {
375		TP::EMPTY && (TP::LEAF_EMPTY || TP::LeafValueComparer::eq(a, b))
376	}
377
378	// panic-safe modification
379	// always insert leaf! (no compression check)
380	fn insert_leaf_sibling(
381		&mut self,
382		shared_prefix_len: usize,
383		key: TP::Key,
384		value: TP::LeafValue,
385	) {
386		debug_assert!(shared_prefix_len < self.key.len());
387		debug_assert!(shared_prefix_len < key.len());
388		debug_assert!(key.get(shared_prefix_len) != self.key.get(shared_prefix_len));
389
390		// need to split path to this node; requires new parent
391		let old_key: <TP as TreeProperties>::Key = self.key.clone();
392		let new_leaf = Self::new_leaf(key.clone(), Default::default(), value);
393		let tmp_node = NodeState::Leaf {
394			value: Default::default(),
395		};
396		// need to move inner value down
397		let new_inner: TP::Value = Default::default();
398
399		// start modification; make it panic safe
400		// * if this panics assume the key is left at its previous value:
401		self.key.clip(shared_prefix_len);
402		// * everything else shouldn't panic
403		let old_inner = replace(&mut self.value, new_inner);
404		let old_node = replace(&mut self.state, tmp_node);
405		// TODO: new_inner_unknown_order calls BitString::get which might panic (but shouldn't)
406		let old_state = replace(
407			&mut self.state,
408			NodeState::new_inner_unknown_order(
409				shared_prefix_len,
410				Self {
411					key: old_key,
412					value: old_inner,
413					state: old_node,
414				},
415				new_leaf,
416			),
417		);
418		// modification done, allow panics again
419		drop(old_state);
420	}
421
422	// create chain of nodes to final leaf {key, value}; every shorter path from parent_key_len
423	// to it gets an inner node with a side leaf {side_value}
424	fn linear_split(
425		parent_key_len: usize,
426		side_value: TP::LeafValue,
427		mut key: TP::Key,
428		value: TP::LeafValue,
429	) -> NodeState<TP> {
430		let mut new_node = NodeState::Leaf { value };
431		for l_minus1 in (parent_key_len..key.len()).rev() {
432			key.clip(l_minus1 + 1);
433			let mut other_key = key.clone();
434			other_key.flip(l_minus1);
435			new_node = NodeState::new_inner_unknown_order(
436				l_minus1,
437				Node {
438					key: key.clone(),
439					value: Default::default(),
440					state: new_node,
441				},
442				Node::new_leaf(other_key, Default::default(), side_value.clone()),
443			);
444		}
445		new_node
446	}
447
448	// panic-safe modification
449	// always insert leaf! (no compression check)
450	// must be currently a leaf node, and `self.key` must be a prefix of `key`
451	// will split current leaf value into chain if needed
452	fn insert_sub_leaf(&mut self, key: TP::Key, value: TP::LeafValue) {
453		let self_key_len = self.key.len(); // self.key is (shared) prefix of key!
454									 // new value below in tree
455		let old_value = self.get_leaf_value().expect("must be at leaf node").clone();
456
457		let new_state = if TP::IGNORE_LEAFS {
458			// leaf nodes not important; just create direct sibling
459			let mut other_key = key.clone();
460			other_key.clip(self_key_len + 1);
461			other_key.flip(self_key_len);
462			NodeState::new_inner_unknown_order(
463				self_key_len,
464				Node {
465					key,
466					value: Default::default(),
467					state: NodeState::Leaf { value },
468				},
469				Node::new_leaf(other_key, Default::default(), old_value),
470			)
471		} else {
472			// full chain of old leaf values
473			Self::linear_split(self_key_len, old_value, key, value)
474		};
475
476		// now start modification; make it panic safe
477		// * replacing state shouldn't panic
478		let old_state = replace(&mut self.state, new_state);
479		// panics allowed again
480		drop(old_state);
481	}
482
483	// panic-safe modification
484	fn clip_to_value(&mut self, key_len: usize, value: TP::LeafValue) {
485		let mut old_inner = None;
486		if key_len != self.key.len() {
487			let new_inner = Default::default();
488
489			// start modification; make it panic safe
490			// * if this panics assume the key is left at its previous value:
491			self.key.clip(key_len);
492			// * everything else shouldn't panic
493			old_inner = Some(replace(&mut self.value, new_inner));
494		}
495		let old_state = replace(&mut self.state, NodeState::Leaf { value });
496		// modification done, allow panics again
497		drop(old_state);
498		drop(old_inner);
499	}
500
501	/// pre condition: self is the node to insert `key` at
502	fn insert_leaf_value(&mut self, key: TP::Key, value: TP::LeafValue) {
503		let key_len = key.len();
504		let self_key_len = self.key.len();
505		let shared_prefix_len = self.key.shared_prefix_len(&key);
506
507		if shared_prefix_len == key_len {
508			// either key == self.key, or key is a prefix of self.key
509			// => replace subtree
510			// panic-safe modification:
511			self.clip_to_value(shared_prefix_len, value);
512			return;
513		}
514
515		if shared_prefix_len < self_key_len {
516			// need to insert new inner node at `self`, i.e. split path to this node
517			debug_assert!(shared_prefix_len < key_len);
518
519			// but first check a shortcut: if we could compress afterward, don't create
520			// new nodes in the first place
521			if TP::EMPTY {
522				// we can merge inner nodes
523				if self_key_len == key_len && self_key_len == shared_prefix_len + 1 {
524					// we'd create direct neighbor nodes below
525					if let Some(old_value) = self.get_leaf_value() {
526						if Self::leaf_value_eq(&value, old_value) {
527							// both nodes would be leaf nodes, and their values match
528							// panic-safe modification:
529							self.clip_to_value(shared_prefix_len, value.clone());
530							return;
531						}
532					}
533				}
534			}
535
536			self.insert_leaf_sibling(shared_prefix_len, key, value);
537			return;
538		}
539
540		// otherwise: self.key is a (real) prefix of key
541		// if self isn't a leaf we're not at the insert position (violiating precondition)
542		debug_assert!(shared_prefix_len == self_key_len);
543		debug_assert!(shared_prefix_len < key_len);
544
545		// new value below in tree
546		let old_value = self.get_leaf_value().expect("should be at leaf node");
547
548		// borrow check is unhappy with putting this into the match below.
549		if TP::LEAF_EMPTY {
550			// we don't care about leaf values, and the key is already covered by a leaf.
551			return;
552		}
553		if TP::LeafValueComparer::eq(old_value, &value) {
554			// leaf values match, no need to create lots of nodes
555			return;
556		}
557		self.insert_sub_leaf(key, value);
558	}
559
560	// return true when self is a leaf afterwards
561	fn compress(&mut self) -> bool {
562		let self_key_len = self.key.len();
563
564		// compress: if node has two children, and both sub keys are
565		// exactly one bit longer than the key of the parent node, and
566		// both child nodes are leafs and share the same value, make the
567		// current node a leaf
568		let value = match self.state {
569			NodeState::InnerNode { ref mut children } => {
570				if children.left.key.len() != self_key_len + 1 {
571					return false;
572				}
573				if children.right.key.len() != self_key_len + 1 {
574					return false;
575				}
576				let left_value = match children.left.get_leaf_value() {
577					Some(value) => value,
578					None => return false, // not a leaf
579				};
580				let right_value = match children.right.get_leaf_value() {
581					Some(value) => value,
582					None => return false, // not a leaf
583				};
584				if !Self::leaf_value_eq(left_value, right_value) {
585					return false; // values not equal
586				}
587				// clone value from left side
588				left_value.clone()
589			},
590			NodeState::Leaf { .. } => return true, // already compressed
591		};
592		// now start modification; make it panic safe
593		// (single assignment should be safe anyway, but make it explicit)
594		let old_state = replace(&mut self.state, NodeState::Leaf { value });
595		// drop afterwards
596		drop(old_state);
597		true
598	}
599
600	// delete either left or right side
601	fn delete_side(&mut self, delete_right: bool) {
602		// start modification; make it panic safe
603		// * take might panic when creation of default state fails - nothing else was modified
604		let mut old_state = take(&mut self.state);
605		// * swaps shouldn't panic
606		match old_state {
607			NodeState::Leaf { .. } => {
608				// no children, not deleting anything. probably shouldn't end up here, but easy to handle.
609				swap(&mut self.state, &mut old_state);
610			},
611			NodeState::InnerNode { ref mut children } => {
612				if delete_right {
613					// drop right, replace self with left
614					swap(self, &mut children.left);
615				} else {
616					// drop left, replace self with right
617					swap(self, &mut children.right);
618				}
619			},
620		}
621		// * modification done, panics allowed again
622		drop(old_state);
623	}
624}
625
626/// Nodes of a [`Tree`] can be either an InnerNode (with two children)
627/// or a leaf node.
628enum NodeState<TP: TreeProperties> {
629	/// Inner node
630	InnerNode { children: Box<Children<TP>> },
631	/// Leaf node
632	Leaf { value: TP::LeafValue },
633}
634
635impl<TP: TreeProperties> Default for NodeState<TP> {
636	fn default() -> Self {
637		Self::Leaf {
638			value: Default::default(),
639		}
640	}
641}
642
643impl<TP> Clone for NodeState<TP>
644where
645	TP: TreeProperties,
646	TP::Value: Clone,
647{
648	fn clone(&self) -> Self {
649		match self {
650			Self::InnerNode { children } => Self::InnerNode {
651				children: children.clone(),
652			},
653			Self::Leaf { value } => Self::Leaf {
654				value: value.clone(),
655			},
656		}
657	}
658}
659
660impl<TP: TreeProperties> NodeState<TP> {
661	fn new_inner_unknown_order(shared_prefix_len: usize, a: Node<TP>, b: Node<TP>) -> Self {
662		let a_right = a.key.get(shared_prefix_len);
663		assert_eq!(!a_right, b.key.get(shared_prefix_len));
664		if a_right {
665			Self::InnerNode {
666				children: Box::new(Children { left: b, right: a }),
667			}
668		} else {
669			Self::InnerNode {
670				children: Box::new(Children { left: a, right: b }),
671			}
672		}
673	}
674}
675
676struct Children<TP: TreeProperties> {
677	left: Node<TP>,
678	right: Node<TP>,
679}
680
681impl<TP> Clone for Children<TP>
682where
683	TP: TreeProperties,
684	TP::Value: Clone,
685{
686	fn clone(&self) -> Self {
687		Self {
688			left: self.left.clone(),
689			right: self.right.clone(),
690		}
691	}
692}
693
694/// [`Tree`] is a binary tree with path-shortening.
695///
696/// Nodes are either inner nodes with two child nodes, or leaf nodes.
697/// Both node types carry keys and values, leaf nodes an additional leaf value (of different type).
698pub struct Tree<TP: TreeProperties> {
699	node: Option<Node<TP>>,
700}
701
702impl<TP: TreeProperties> Default for Tree<TP> {
703	fn default() -> Self {
704		Self::new()
705	}
706}
707
708impl<TP> Clone for Tree<TP>
709where
710	TP: TreeProperties,
711	TP::Value: Clone,
712{
713	fn clone(&self) -> Self {
714		Self {
715			node: self.node.clone(),
716		}
717	}
718}
719
720impl<TP> fmt::Debug for Tree<TP>
721where
722	TP: TreeProperties,
723	TP::Key: fmt::Debug,
724	TP::Value: fmt::Debug,
725	TP::LeafValue: fmt::Debug,
726{
727	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
728		match self.node {
729			None => {
730				write!(f, "Tree {{ }}")
731			},
732			Some(ref node) => {
733				write!(f, "Tree {{ {:?} }}", node)
734			},
735		}
736	}
737}
738
739impl<TP: TreeProperties> Tree<TP> {
740	/// New (empty) tree.
741	pub const fn new() -> Self {
742		assert!(tp_valid::<TP>()); // TODO: make it a static assert somehow?
743		Self { node: None }
744	}
745
746	/// Set a new prefix => value mapping.
747	///
748	/// Leaf values are designed to split all values into prefixes
749	/// that either have a leaf value or no leaf value set.
750	///
751	/// Sibling prefixes that share the same leaf value are merged.
752	pub fn set_leaf_value(&mut self, key: TP::Key, value: TP::LeafValue) {
753		let mut walk = self.walk_mut::<(), ()>();
754		walk.goto_insert(&key);
755
756		match walk.inner.walk.current_mut() {
757			NodeOrTree::Tree(root) => {
758				assert!(root.is_none());
759				*root = Some(Node::new_leaf(key, Default::default(), value));
760			},
761			NodeOrTree::Node(node) => {
762				node.insert_leaf_value(key, value);
763			},
764		}
765
766		// compress while walking up the tree until compress fails
767		if TP::EMPTY {
768			while walk.up().is_some() {
769				match walk.current_mut() {
770					NodeOrTree::Tree(_) => break,
771					NodeOrTree::Node(node) => {
772						if !node.compress() {
773							break;
774						}
775					},
776				}
777			}
778		}
779	}
780
781	/// Get reference to root node
782	pub fn root(&self) -> Option<&Node<TP>> {
783		self.node.as_ref()
784	}
785
786	/// Get mutable reference to root node
787	pub fn root_mut(&mut self) -> Option<&mut Node<TP>> {
788		self.node.as_mut()
789	}
790
791	/// Get reference to node with exact key
792	pub fn get<'r>(&'r self, key: &TP::Key) -> Option<&'r Node<TP>> {
793		match self.goto_insert(key)? {
794			InsertPositionWith::AlreadyExists(n) => Some(n),
795			_ => None,
796		}
797	}
798
799	/// Get mutable reference to node with exact key
800	pub fn get_mut<'r>(&'r mut self, key: &TP::Key) -> Option<&'r mut Node<TP>> {
801		match self.goto_mut_insert(key)? {
802			InsertPositionWith::AlreadyExists(n) => Some(n),
803			_ => None,
804		}
805	}
806
807	/// Goto insert position for given key
808	pub fn goto_insert<'r>(&'r self, key: &TP::Key) -> Option<InsertPositionWith<&'r Node<TP>>> {
809		Some(self.node.as_ref()?.goto_insert(key))
810	}
811
812	/// Goto mutable insert position for given key
813	pub fn goto_mut_insert<'r>(
814		&'r mut self,
815		key: &TP::Key,
816	) -> Option<InsertPositionWith<&'r mut Node<TP>>> {
817		Some(self.node.as_mut()?.goto_insert(key))
818	}
819
820	/// Get a reference to the node with the longest prefix satisfying callback of the target key
821	pub fn get_longest_prefix_with<'r, F>(
822		&'r self,
823		key: &TP::Key,
824		mut callback: F,
825	) -> Option<&'r Node<TP>>
826	where
827		F: FnMut(&Node<TP>) -> bool,
828	{
829		let key_len = key.len();
830		let mut step = self.node.as_ref()?.lookup_initial_step(key, key_len);
831		let mut result = None;
832		loop {
833			step = match step {
834				LookupStepWith::Path(node, _) => {
835					if callback(node) {
836						result = Some(node);
837					}
838					node.lookup_step(key, key_len)
839				},
840				LookupStepWith::Found(node, _) => {
841					if callback(node) {
842						return Some(node);
843					}
844					return result;
845				},
846				LookupStepWith::Miss => {
847					return result;
848				},
849			};
850		}
851	}
852
853	/// Get a reference to the node with the longest prefix satisfying callback of the target key
854	pub fn get_longest_prefix_mut_with<'r, F>(
855		&'r mut self,
856		key: &TP::Key,
857		mut callback: F,
858	) -> Option<&'r mut Node<TP>>
859	where
860		F: FnMut(&mut Node<TP>) -> bool,
861	{
862		let key_len = key.len();
863		let mut step = self.node.as_mut()?.lookup_initial_step(key, key_len);
864		let mut result = None;
865		loop {
866			step = match step {
867				LookupStepWith::Path(node, _) => {
868					if callback(node) {
869						result = Some(NonNull::from(&mut *node));
870					}
871					node.lookup_step(key, key_len)
872				},
873				LookupStepWith::Found(node, _) => {
874					if callback(node) {
875						return Some(node);
876					}
877					break;
878				},
879				LookupStepWith::Miss => {
880					break;
881				},
882			};
883		}
884		// safety: steps derived from result are not borrowed anymore
885		return Some(unsafe { result?.as_mut() });
886	}
887
888	/// Get a reference to the node with the longest prefix of the target key
889	pub fn get_most_specific<'r>(&'r self, key: &TP::Key) -> Option<&'r Node<TP>> {
890		let key_len = key.len();
891		let mut current = match self.node.as_ref()?.lookup_initial_step(key, key_len) {
892			LookupStepWith::Path(node, _) => node,
893			LookupStepWith::Found(node, _) => return Some(node),
894			LookupStepWith::Miss => return None,
895		};
896		loop {
897			current = match current.lookup_step(key, key_len) {
898				LookupStepWith::Path(node, _) => node,
899				LookupStepWith::Found(node, _) => return Some(node),
900				LookupStepWith::Miss => return Some(current),
901			};
902		}
903	}
904
905	/// Get a mutable reference to the node with the longest prefix of the target key
906	pub fn get_most_specific_mut<'r>(&'r mut self, key: &TP::Key) -> Option<&'r mut Node<TP>> {
907		let key_len = key.len();
908		let mut current = match self.node.as_mut()?.lookup_initial_step(key, key_len) {
909			LookupStepWith::Path(node, _) => node,
910			LookupStepWith::Found(node, _) => return Some(node),
911			LookupStepWith::Miss => return None,
912		};
913		loop {
914			let previous = current as *mut _;
915			current = match current.lookup_step(key, key_len) {
916				LookupStepWith::Path(node, _) => node,
917				LookupStepWith::Found(node, _) => return Some(node),
918				// safety: current isn't actually still be borrowed, but borrow checker fails (polonius should fix this).
919				// LookupStep::Miss => return Some(current),
920				LookupStepWith::Miss => return Some(unsafe { &mut *previous }),
921			};
922		}
923	}
924
925	/// Walk tree
926	pub fn walk<D, A>(&self) -> Walk<'_, TP, D, A> {
927		Walk::new(self)
928	}
929
930	/// Iterate over nodes of tree that are a prefix of target key
931	pub fn iter_path(&self, key: TP::Key) -> IterPath<'_, TP> {
932		IterPath::new(self.node.as_ref(), key)
933	}
934
935	/// Iterate over nodes of tree depth-first pre-order
936	pub fn iter_pre_order(&self) -> IterPreOrder<'_, TP> {
937		IterPreOrder::new(self)
938	}
939
940	/// Iterate over nodes of tree depth-first in-order
941	pub fn iter_in_order(&self) -> IterInOrder<'_, TP> {
942		IterInOrder::new(self)
943	}
944
945	/// Iterate over nodes of tree depth-first post-order
946	pub fn iter_post_order(&self) -> IterPostOrder<'_, TP> {
947		IterPostOrder::new(self)
948	}
949
950	/// Iterate over nodes and leaf values of tree in-order
951	pub fn iter_leaf(&self) -> IterLeaf<'_, TP> {
952		IterLeaf::new(self)
953	}
954
955	/// Iterate over nodes and leaf values and uncovered keys of tree in-order
956	pub fn iter_leaf_full(&self) -> IterLeafFull<'_, TP> {
957		IterLeafFull::new(self)
958	}
959
960	/// Walk mutable tree
961	pub fn walk_mut<D, A>(&mut self) -> WalkMutOwned<'_, TP, D, A> {
962		WalkMutOwned {
963			inner: mut_gen::WalkMut::new(self),
964		}
965	}
966
967	/// Iterate over keys and mutable values of tree that are a prefix of target key
968	pub fn iter_mut_path(&mut self, key: TP::Key) -> MutPath<'_, TP> {
969		MutPath::new(self.node.as_mut(), key)
970	}
971
972	/// Iterate over keys and mutable values of tree depth-first pre-order
973	pub fn iter_mut_pre_order(&mut self) -> IterMutOwnedPreOrder<'_, TP> {
974		self.walk_mut().into_iter_pre_order()
975	}
976
977	/// Iterate over keys and mutable values of tree depth-first in-order
978	pub fn iter_mut_in_order(&mut self) -> IterMutOwnedInOrder<'_, TP> {
979		self.walk_mut().into_iter_in_order()
980	}
981
982	/// Iterate over keys and mutable values of tree depth-first post-order
983	pub fn iter_mut_post_order(&mut self) -> IterMutOwnedPostOrder<'_, TP> {
984		self.walk_mut().into_iter_post_order()
985	}
986
987	/// Iterate over keys and mutable leaf values of tree in-order
988	pub fn iter_mut_leaf(&mut self) -> IterMutOwnedLeaf<'_, TP> {
989		self.walk_mut().into_iter_leafs()
990	}
991
992	/// Iterate over keys and mutable leaf values and uncovered keys of tree in-order
993	pub fn iter_mut_leaf_full(&mut self) -> IterMutOwnedLeafFull<'_, TP> {
994		self.walk_mut().into_iter_full_leafs()
995	}
996}