bitstring_trees/
full_map.rs

1//! [`FullMap`] of bit string prefixes
2
3use core::{
4	cmp::Ordering,
5	marker::PhantomData,
6};
7
8use bitstring::BitString;
9
10use crate::tree::{
11	DefaultCompare,
12	Node,
13	Tree,
14	TreeProperties,
15	WalkedDirection,
16};
17
18struct TpFullMap<K: BitString + Clone, V>(PhantomData<*const K>, PhantomData<*const V>);
19
20impl<K: BitString + Clone, V> TreeProperties for TpFullMap<K, V> {
21	type Key = K;
22	type LeafValue = ();
23	type LeafValueComparer = DefaultCompare;
24	type Value = Option<V>;
25
26	const EMPTY: bool = false;
27	const IGNORE_LEAFS: bool = true;
28	const LEAF_EMPTY: bool = true;
29}
30
31/// Map bit string prefixes to values
32///
33/// This allows overriding values based on "better matching" longer prefixes in an efficient way.
34///
35/// Network routing tables are usually implemented that way: there often is a default
36/// route for `0.0.0.0/0` and then a "more specific" for the LAN, e.g. `192.168.0.0/24`.
37/// (I.e. a route is a map entry for a prefix to a "nexthop specification", as in how
38/// to forward a packet matching the entry. The "most specific" (longest) matching
39/// route is used.)
40///
41/// This is implemented as a [`crate::tree::Tree`] where all nodes can have an optional value;
42/// branches where no node has a value are pruned.
43#[derive(Clone)]
44pub struct FullMap<K: BitString + Clone, V> {
45	tree: Tree<TpFullMap<K, V>>,
46}
47
48impl<K: BitString + Clone, V> Default for FullMap<K, V> {
49	fn default() -> Self {
50		Self::new()
51	}
52}
53
54impl<K, V> core::fmt::Debug for FullMap<K, V>
55where
56	K: BitString + Clone + core::fmt::Debug,
57	V: core::fmt::Debug,
58{
59	fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
60		f.debug_map().entries(self.iter()).finish()
61	}
62}
63
64impl<K, V> FullMap<K, V>
65where
66	K: BitString + Clone,
67{
68	/// New (empty) map.
69	pub const fn new() -> Self {
70		Self { tree: Tree::new() }
71	}
72
73	/// Gets the given key's corresponding entry in the map for in-place manipulation.
74	pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
75		let mut walk = self.tree.walk_mut();
76		walk.goto_insert(&key);
77		if let Some(node) = walk.current().node() {
78			if node.get_key().len() == key.len() && node.get_value().is_some() {
79				return Entry::Occupied(OccupiedEntry { walk });
80			}
81		}
82		Entry::Vacant(VacantEntry { walk, key })
83	}
84
85	fn occupied<'s>(&'s mut self, key: &K) -> Option<OccupiedEntry<'s, K, V>> {
86		let mut walk = self.tree.walk_mut();
87		walk.goto_insert(key);
88		if let Some(node) = walk.current().node() {
89			if node.get_key().len() == key.len() && node.get_value().is_some() {
90				return Some(OccupiedEntry { walk });
91			}
92		}
93		None
94	}
95
96	/// Inserts a key-value pair into the map.
97	///
98	/// If the map did not have this key present, None is returned.
99	///
100	/// If the map did have this key present, the value is updated, and the old value is returned.
101	pub fn insert(&mut self, key: K, value: V) -> Option<V> {
102		self.entry(key).replace(value).1
103	}
104
105	/// Removes a key from the map, returning the stored key and value if the key
106	/// was previously in the map.
107	pub fn remove(&mut self, key: &K) -> Option<V> {
108		Some(self.occupied(key)?.remove())
109	}
110
111	/// Returns a reference to the value corresponding to the key.
112	pub fn get(&self, key: &K) -> Option<&V> {
113		self.tree.get(key)?.get_value().as_ref()
114	}
115
116	/// Returns a mutable reference to the value corresponding to the key.
117	pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
118		self.tree.get_mut(key)?.get_value_mut().as_mut()
119	}
120
121	/// Returns a reference to the key-value pair for the longest prefix of the key in the map.
122	pub fn most_specific(&self, key: &K) -> Option<(&K, &V)> {
123		// TODO: could probably also implement it using walk.goto + check, or manually
124		self.path(key.clone()).last()
125	}
126
127	/// Remove all prefixes equal or longer than given key
128	pub fn remove_tree(&mut self, key: K) {
129		let mut walk = self.tree.walk_mut();
130		walk.goto_insert(&key);
131		match walk.current().node() {
132			None => (), // empty tree
133			Some(node) => {
134				match node.get_key().len().cmp(&key.len()) {
135					Ordering::Less => {
136						// node is a leaf and covers key; need to split and remove key
137						// create explicit node with key we want to remove
138						walk.insert(key);
139						// now remove it
140						walk.delete_current();
141					},
142					Ordering::Equal | Ordering::Greater => {
143						// remove subtree
144						walk.delete_current();
145					},
146				}
147			},
148		}
149	}
150
151	/// Iterate over all prefixes and their values on the path to a key
152	pub fn path(&self, key: K) -> IterPath<'_, K, V> {
153		IterPath {
154			iter: self.tree.iter_path(key),
155		}
156	}
157
158	/// Iterate over all prefixes and their mutable values on the path to a key
159	///
160	// TODO: return a `WalkMutPath` wrapper with IntoIterator impl?
161	pub fn path_mut(&mut self, key: K) -> IterPathMut<'_, K, V> {
162		IterPathMut {
163			iter: self.tree.iter_mut_path(key).into_iter(),
164		}
165	}
166
167	/// Iterate over all (aggregated) prefixes and their values
168	pub fn iter(&self) -> IterMap<'_, K, V> {
169		IterMap {
170			iter: self.tree.iter_in_order(),
171		}
172	}
173
174	/// Iterate over all (aggregated) prefixes and their mutable values
175	pub fn iter_mut(&mut self) -> IterMutMap<'_, K, V> {
176		IterMutMap {
177			iter: self.tree.iter_mut_in_order(),
178		}
179	}
180}
181
182// basically copied from alloc::collections::btree::map::entry:
183/// A view into a single entry in a map, which may either be vacant or occupied.
184///
185/// This enum is constructed from the [`entry`] method on [`FullMap`].
186///
187/// [`entry`]: FullMap::entry
188pub enum Entry<'s, K: BitString + Clone, V> {
189	/// A vacant entry.
190	Vacant(VacantEntry<'s, K, V>),
191	/// An occupied entry.
192	Occupied(OccupiedEntry<'s, K, V>),
193}
194
195impl<'s, K: BitString + Clone, V> Entry<'s, K, V> {
196	/// Ensures a value is in the entry by inserting the default if empty, and returns
197	/// a mutable reference to the value in the entry.
198	pub fn or_insert(self, default: V) -> &'s mut V {
199		match self {
200			Self::Occupied(entry) => entry.into_mut(),
201			Self::Vacant(entry) => entry.insert(default),
202		}
203	}
204
205	/// Ensures a value is in the entry by inserting the result of the default function if empty,
206	/// and returns a mutable reference to the value in the entry.
207	pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'s mut V {
208		match self {
209			Self::Occupied(entry) => entry.into_mut(),
210			Self::Vacant(entry) => entry.insert(default()),
211		}
212	}
213
214	/// Ensures a value is in the entry by inserting, if empty, the result of the default function.
215	/// This method allows for generating key-derived values for insertion by providing the default
216	/// function a reference to the key that was moved during the `.entry(key)` method call.
217	///
218	/// The reference to the moved key is provided so that cloning or copying the key is
219	/// unnecessary, unlike with `.or_insert_with(|| ... )`.
220	#[inline]
221	pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'s mut V {
222		match self {
223			Self::Occupied(entry) => entry.into_mut(),
224			Self::Vacant(entry) => {
225				let value = default(entry.key());
226				entry.insert(value)
227			},
228		}
229	}
230
231	/// Returns a reference to this entry's key.
232	pub fn key(&self) -> &K {
233		match self {
234			Self::Occupied(entry) => entry.key(),
235			Self::Vacant(entry) => entry.key(),
236		}
237	}
238
239	/// Provides in-place mutable access to an occupied entry before any
240	/// potential inserts into the map.
241	pub fn and_modify<F>(mut self, f: F) -> Self
242	where
243		F: FnOnce(&mut V),
244	{
245		if let Self::Occupied(ref mut entry) = self {
246			f(entry.get_mut())
247		}
248		self
249	}
250
251	/// Ensures a value is in the entry by inserting the default value if empty,
252	/// and returns a mutable reference to the value in the entry.
253	pub fn or_default(self) -> &'s mut V
254	where
255		V: Default,
256	{
257		match self {
258			Self::Occupied(entry) => entry.into_mut(),
259			Self::Vacant(entry) => entry.insert(Default::default()),
260		}
261	}
262
263	/// Sets or inserts the value of the entry with the [`Entry`]'s key,
264	/// and returns a mutable reference to it.
265	pub fn insert(self, value: V) -> &'s mut V {
266		match self {
267			Self::Occupied(entry) => {
268				let vref = entry.into_mut();
269				*vref = value;
270				vref
271			},
272			Self::Vacant(entry) => entry.insert(value),
273		}
274	}
275
276	/// Sets or inserts the value of the entry with the [`Entry`]'s key,
277	/// and returns the occupied entry.
278	pub fn set(self, value: V) -> OccupiedEntry<'s, K, V> {
279		self.replace(value).0
280	}
281
282	/// Sets or inserts the value of the entry with the [`Entry`]'s key,
283	/// and returns the occupied entry and previous value (if present).
284	pub fn replace(self, value: V) -> (OccupiedEntry<'s, K, V>, Option<V>) {
285		match self {
286			Self::Occupied(mut entry) => {
287				let old = entry.insert(value);
288				(entry, Some(old))
289			},
290			Self::Vacant(entry) => {
291				let VacantEntry { mut walk, key } = entry;
292				walk.insert(key);
293				let node = walk
294					.current_mut()
295					.node()
296					.expect("after insert walk should be at a node");
297				*node.get_value_mut() = Some(value);
298				(OccupiedEntry { walk }, None)
299			},
300		}
301	}
302}
303
304/// A view into a vacant entry in a [`FullMap`]. It is part of the [`Entry`] enum.
305pub struct VacantEntry<'s, K: BitString + Clone + 's, V: 's> {
306	walk: crate::tree::WalkMutOwned<'s, TpFullMap<K, V>, WalkedDirection>,
307	key: K,
308}
309
310impl<'s, K: BitString + Clone, V> VacantEntry<'s, K, V> {
311	/// Gets a reference to the key that would be used when inserting a value
312	/// through the VacantEntry.
313	pub fn key(&self) -> &K {
314		&self.key
315	}
316
317	/// Take ownership of the key.
318	pub fn into_key(self) -> K {
319		self.key
320	}
321
322	/// Sets the value of the entry with the `VacantEntry`'s key,
323	/// and returns a mutable reference to it.
324	pub fn insert(self, value: V) -> &'s mut V {
325		let Self { mut walk, key } = self;
326		walk.insert(key);
327		let node = walk
328			.into_current_mut()
329			.node()
330			.expect("after insert walk should be at a node");
331		*node.get_value_mut() = Some(value);
332		node.get_value_mut().as_mut().expect("value can't be empty")
333	}
334}
335
336/// A view into an occupied entry in a [`FullMap`]. It is part of the [`Entry`] enum.
337pub struct OccupiedEntry<'s, K: BitString + Clone + 's, V: 's> {
338	walk: crate::tree::WalkMutOwned<'s, TpFullMap<K, V>, WalkedDirection>,
339}
340
341impl<'s, K: BitString + Clone, V> OccupiedEntry<'s, K, V> {
342	fn node(&self) -> &Node<TpFullMap<K, V>> {
343		self.walk
344			.current()
345			.node()
346			.expect("OccupiedEntry should have a node")
347	}
348
349	fn node_mut(&mut self) -> &mut Node<TpFullMap<K, V>> {
350		self.walk
351			.current_mut()
352			.node()
353			.expect("OccupiedEntry should have a node")
354	}
355
356	fn node_into(self) -> &'s mut Node<TpFullMap<K, V>> {
357		self.walk
358			.into_current_mut()
359			.node()
360			.expect("OccupiedEntry should have a node")
361	}
362
363	/// Gets a reference to the value in the entry.
364	pub fn get(&self) -> &V {
365		self.node()
366			.get_value()
367			.as_ref()
368			.expect("OccupiedEntry should have a value")
369	}
370
371	/// Gets a mutable reference to the value in the entry.
372	///
373	/// If you need a reference to the [`OccupiedEntry`] that may outlive the destruction of the Entry value, see [`into_mut`].
374	///
375	/// [`into_mut`]: OccupiedEntry::into_mut
376	pub fn get_mut(&mut self) -> &mut V {
377		self.node_mut()
378			.get_value_mut()
379			.as_mut()
380			.expect("OccupiedEntry should have a value")
381	}
382
383	/// Converts the entry into a mutable reference to its value.
384	///
385	/// If you need multiple references to the [`OccupiedEntry`], see [`get_mut`].
386	///
387	/// [`get_mut`]: OccupiedEntry::get_mut
388	pub fn into_mut(self) -> &'s mut V {
389		self.node_into()
390			.get_value_mut()
391			.as_mut()
392			.expect("OccupiedEntry should have a value")
393	}
394
395	/// Gets a reference to the key in the entry.
396	pub fn key(&self) -> &K {
397		self.node().get_key()
398	}
399
400	/// Sets the value of the entry with the [`OccupiedEntry`]'s key,
401	/// and returns the entry's old value.
402	pub fn insert(&mut self, value: V) -> V {
403		core::mem::replace(self.get_mut(), value)
404	}
405
406	/// Takes the value of the entry out of the map, and returns it.
407	pub fn remove(mut self) -> V {
408		let value = self
409			.node_mut()
410			.get_value_mut()
411			.take()
412			.expect("OccupiedEntry should have a value");
413		self.walk.compact_if_empty(Option::is_none);
414		value
415	}
416}
417
418/// Iterate over all prefixes and their values on the path to a key
419pub struct IterPath<'s, K: BitString + Clone, V> {
420	iter: crate::tree::IterPath<'s, TpFullMap<K, V>>,
421}
422
423impl<'s, K: BitString + Clone, V> Iterator for IterPath<'s, K, V> {
424	type Item = (&'s K, &'s V);
425
426	fn next(&mut self) -> Option<Self::Item> {
427		loop {
428			let node = self.iter.next()?;
429			// skip (inner) nodes that don't have a value
430			if let Some(value) = node.get_value() {
431				return Some((node.get_key(), value));
432			}
433		}
434	}
435}
436
437/// Iterate over all prefixes and their values on the path to a key
438pub struct IterPathMut<'s, K: BitString + Clone, V> {
439	iter: crate::tree::IterMutPath<'s, TpFullMap<K, V>>,
440}
441
442impl<'s, K: BitString + Clone, V> Iterator for IterPathMut<'s, K, V> {
443	type Item = (&'s K, &'s mut V);
444
445	fn next(&mut self) -> Option<Self::Item> {
446		loop {
447			let (key, value, _) = self.iter.next()?;
448			// skip (inner) nodes that don't have a value
449			if let Some(value) = value {
450				return Some((key, value));
451			}
452		}
453	}
454}
455
456/// Iterate over all prefixes and their values
457pub struct IterMap<'s, K: BitString + Clone, V> {
458	iter: crate::tree::IterInOrder<'s, TpFullMap<K, V>>,
459}
460
461impl<'s, K: BitString + Clone, V> Iterator for IterMap<'s, K, V> {
462	type Item = (&'s K, &'s V);
463
464	fn next(&mut self) -> Option<Self::Item> {
465		loop {
466			let node = self.iter.next()?;
467			// skip (inner) nodes that don't have a value
468			if let Some(value) = node.get_value() {
469				return Some((node.get_key(), value));
470			}
471		}
472	}
473}
474
475/// Iterate over all (aggregated) prefixes and their mutable values
476pub struct IterMutMap<'s, K: BitString + Clone, V> {
477	iter: crate::tree::IterMutOwnedInOrder<'s, TpFullMap<K, V>>,
478}
479
480impl<'s, K: BitString + Clone, V> Iterator for IterMutMap<'s, K, V> {
481	type Item = (&'s K, &'s mut V);
482
483	fn next(&mut self) -> Option<Self::Item> {
484		loop {
485			let (key, value, _) = self.iter.next()?;
486			// skip (inner) nodes that don't have a value
487			if let Some(value) = value.as_mut() {
488				return Some((key, value));
489			}
490		}
491	}
492}