bitstring_trees/
map.rs

1//! [`Map`] 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	Tree,
13	TreeProperties,
14};
15
16struct TpMap<K, V>(PhantomData<*const K>, PhantomData<*const V>)
17where
18	K: BitString + Clone,
19	V: Default + Clone + Eq;
20
21impl<K, V> TreeProperties for TpMap<K, V>
22where
23	K: BitString + Clone,
24	V: Default + Clone + Eq,
25{
26	type Key = K;
27	type LeafValue = V;
28	type LeafValueComparer = DefaultCompare;
29	type Value = ();
30
31	const EMPTY: bool = true;
32	const IGNORE_LEAFS: bool = false;
33	const LEAF_EMPTY: bool = false;
34}
35
36/// Map of bit strings (combined to prefixes) to values
37///
38/// Each bit string can only have a single value; sibling bit strings
39/// mapping to the same value are automatically merged internally.
40///
41/// This is implemented as a [`crate::tree::Tree`] where only leaf nodes carry values.
42#[derive(Clone)]
43pub struct Map<K, V>
44where
45	K: BitString + Clone,
46	V: Default + Clone + Eq,
47{
48	tree: Tree<TpMap<K, V>>,
49}
50
51impl<K, V> Default for Map<K, V>
52where
53	K: BitString + Clone,
54	V: Default + Clone + Eq,
55{
56	fn default() -> Self {
57		Self::new()
58	}
59}
60
61impl<K, V> core::fmt::Debug for Map<K, V>
62where
63	K: BitString + Clone + core::fmt::Debug,
64	V: Default + Clone + Eq + core::fmt::Debug,
65{
66	fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
67		f.debug_map().entries(self.iter()).finish()
68	}
69}
70
71impl<K, V> Map<K, V>
72where
73	K: BitString + Clone,
74	V: Default + Clone + Eq,
75{
76	/// New (empty) map.
77	pub const fn new() -> Self {
78		Self { tree: Tree::new() }
79	}
80
81	/// Set new value for all bit strings with given prefix
82	pub fn insert(&mut self, prefix: K, value: V) {
83		self.tree.set_leaf_value(prefix, value);
84	}
85
86	/// Unset values for all bit strings with given prefix
87	pub fn remove(&mut self, key: K) {
88		let mut walk = self.tree.walk_mut();
89		walk.goto_insert(&key);
90		match walk.current().node() {
91			None => (), // empty tree
92			Some(node) => {
93				match node.get_key().len().cmp(&key.len()) {
94					Ordering::Less => {
95						// node is a leaf and covers key; need to split and remove key
96						// create explicit node with key we want to remove
97						walk.insert(key);
98						// now remove it
99						walk.delete_current();
100					},
101					Ordering::Equal | Ordering::Greater => {
102						// remove subtree
103						walk.delete_current();
104					},
105				}
106			},
107		}
108	}
109
110	/// Lookup value for a bit string
111	///
112	/// If only a prefix for longer values is given this only finds
113	/// an aggregated value, i.e. lookups should usually be done
114	/// using a "full-length" bit string.
115	/// (E.g. lookup single hosts in a CIDR-map.)
116	pub fn get(&self, key: &K) -> Option<&V> {
117		let mut walk = self.tree.walk::<(), ()>();
118		walk.goto_insert(key);
119		match walk.current().node() {
120			None => None, // empty tree
121			Some(node) => {
122				match node.get_key().len().cmp(&key.len()) {
123					Ordering::Less => {
124						// node is a leaf and covers key
125						Some(node.get_leaf_value().expect("node must be a leaf"))
126					},
127					Ordering::Equal => node.get_leaf_value(),
128					Ordering::Greater => {
129						// key not fully contained
130						None
131					},
132				}
133			},
134		}
135	}
136
137	/// Iterate over all (aggregated) prefixes and their values
138	pub fn iter(&self) -> IterMap<'_, K, V> {
139		IterMap {
140			iter: self.tree.iter_leaf(),
141		}
142	}
143
144	/// Iterate over all (aggregated) prefixes and their mutable values
145	pub fn iter_mut(&mut self) -> IterMutMap<'_, K, V> {
146		IterMutMap {
147			iter: self.tree.iter_mut_leaf(),
148		}
149	}
150
151	/// Iterate over smallest list of bit strings that cover everything with a value or None if not mapped
152	pub fn iter_full(&self) -> IterMapFull<'_, K, V> {
153		IterMapFull {
154			iter: self.tree.iter_leaf_full(),
155		}
156	}
157}
158
159/// Iterate over all (aggregated) prefixes and their values
160pub struct IterMap<'s, K, V>
161where
162	K: BitString + Clone,
163	V: Default + Clone + Eq,
164{
165	iter: crate::tree::IterLeaf<'s, TpMap<K, V>>,
166}
167
168impl<'s, K, V> Iterator for IterMap<'s, K, V>
169where
170	K: BitString + Clone,
171	V: Default + Clone + Eq,
172{
173	type Item = (&'s K, &'s V);
174
175	fn next(&mut self) -> Option<Self::Item> {
176		let (node, value) = self.iter.next()?;
177		Some((node.get_key(), value))
178	}
179}
180
181/// Iterate over all (aggregated) prefixes and their mutable values
182pub struct IterMutMap<'s, K, V>
183where
184	K: BitString + Clone,
185	V: Default + Clone + Eq,
186{
187	iter: crate::tree::IterMutOwnedLeaf<'s, TpMap<K, V>>,
188}
189
190impl<'s, K, V> Iterator for IterMutMap<'s, K, V>
191where
192	K: BitString + Clone,
193	V: Default + Clone + Eq,
194{
195	type Item = (&'s K, &'s mut V);
196
197	fn next(&mut self) -> Option<Self::Item> {
198		self.iter.next()
199	}
200}
201
202/// Iterate over smallest list of bit strings that cover everything with a value or None if not mapped
203pub struct IterMapFull<'s, K, V>
204where
205	K: BitString + Clone,
206	V: Default + Clone + Eq,
207{
208	iter: crate::tree::IterLeafFull<'s, TpMap<K, V>>,
209}
210
211impl<'s, K, V> Iterator for IterMapFull<'s, K, V>
212where
213	K: BitString + Clone,
214	V: Default + Clone + Eq,
215{
216	type Item = (K, Option<&'s V>);
217
218	fn next(&mut self) -> Option<Self::Item> {
219		self.iter.next()
220	}
221}