bitstring_trees/
map.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
//! [`Map`] of bit string prefixes

use core::{
	cmp::Ordering,
	marker::PhantomData,
};

use bitstring::BitString;

use crate::tree::{
	DefaultCompare,
	Tree,
	TreeProperties,
};

struct TpMap<K, V>(PhantomData<*const K>, PhantomData<*const V>)
where
	K: BitString + Clone,
	V: Default + Clone + Eq;

impl<K, V> TreeProperties for TpMap<K, V>
where
	K: BitString + Clone,
	V: Default + Clone + Eq,
{
	type Key = K;
	type LeafValue = V;
	type LeafValueComparer = DefaultCompare;
	type Value = ();

	const EMPTY: bool = true;
	const IGNORE_LEAFS: bool = false;
	const LEAF_EMPTY: bool = false;
}

/// Map of bit strings (combined to prefixes) to values
///
/// Each bit string can only have a single value; sibling bit strings
/// mapping to the same value are automatically merged internally.
///
/// This is implemented as a [`crate::tree::Tree`] where only leaf nodes carry values.
#[derive(Clone)]
pub struct Map<K, V>
where
	K: BitString + Clone,
	V: Default + Clone + Eq,
{
	tree: Tree<TpMap<K, V>>,
}

impl<K, V> Default for Map<K, V>
where
	K: BitString + Clone,
	V: Default + Clone + Eq,
{
	fn default() -> Self {
		Self::new()
	}
}

impl<K, V> core::fmt::Debug for Map<K, V>
where
	K: BitString + Clone + core::fmt::Debug,
	V: Default + Clone + Eq + core::fmt::Debug,
{
	fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
		f.debug_map().entries(self.iter()).finish()
	}
}

impl<K, V> Map<K, V>
where
	K: BitString + Clone,
	V: Default + Clone + Eq,
{
	/// New (empty) map.
	pub const fn new() -> Self {
		Self { tree: Tree::new() }
	}

	/// Set new value for all bit strings with given prefix
	pub fn insert(&mut self, prefix: K, value: V) {
		self.tree.set_leaf_value(prefix, value);
	}

	/// Unset values for all bit strings with given prefix
	pub fn remove(&mut self, key: K) {
		let mut walk = self.tree.walk_mut();
		walk.goto_insert(&key);
		match walk.current().node() {
			None => (), // empty tree
			Some(node) => {
				match node.get_key().len().cmp(&key.len()) {
					Ordering::Less => {
						// node is a leaf and covers key; need to split and remove key
						// create explicit node with key we want to remove
						walk.insert(key);
						// now remove it
						walk.delete_current();
					},
					Ordering::Equal | Ordering::Greater => {
						// remove subtree
						walk.delete_current();
					},
				}
			},
		}
	}

	/// Lookup value for a bit string
	///
	/// If only a prefix for longer values is given this only finds
	/// an aggregated value, i.e. lookups should usually be done
	/// using a "full-length" bit string.
	/// (E.g. lookup single hosts in a CIDR-map.)
	pub fn get(&self, key: &K) -> Option<&V> {
		let mut walk = self.tree.walk::<(), ()>();
		walk.goto_insert(key);
		match walk.current().node() {
			None => None, // empty tree
			Some(node) => {
				match node.get_key().len().cmp(&key.len()) {
					Ordering::Less => {
						// node is a leaf and covers key
						Some(node.get_leaf_value().expect("node must be a leaf"))
					},
					Ordering::Equal => node.get_leaf_value(),
					Ordering::Greater => {
						// key not fully contained
						None
					},
				}
			},
		}
	}

	/// Iterate over all (aggregated) prefixes and their values
	pub fn iter(&self) -> IterMap<'_, K, V> {
		IterMap {
			iter: self.tree.iter_leaf(),
		}
	}

	/// Iterate over all (aggregated) prefixes and their mutable values
	pub fn iter_mut(&mut self) -> IterMutMap<'_, K, V> {
		IterMutMap {
			iter: self.tree.iter_mut_leaf(),
		}
	}

	/// Iterate over smallest list of bit strings that cover everything with a value or None if not mapped
	pub fn iter_full(&self) -> IterMapFull<'_, K, V> {
		IterMapFull {
			iter: self.tree.iter_leaf_full(),
		}
	}
}

/// Iterate over all (aggregated) prefixes and their values
pub struct IterMap<'s, K, V>
where
	K: BitString + Clone,
	V: Default + Clone + Eq,
{
	iter: crate::tree::IterLeaf<'s, TpMap<K, V>>,
}

impl<'s, K, V> Iterator for IterMap<'s, K, V>
where
	K: BitString + Clone,
	V: Default + Clone + Eq,
{
	type Item = (&'s K, &'s V);

	fn next(&mut self) -> Option<Self::Item> {
		let (node, value) = self.iter.next()?;
		Some((node.get_key(), value))
	}
}

/// Iterate over all (aggregated) prefixes and their mutable values
pub struct IterMutMap<'s, K, V>
where
	K: BitString + Clone,
	V: Default + Clone + Eq,
{
	iter: crate::tree::IterMutOwnedLeaf<'s, TpMap<K, V>>,
}

impl<'s, K, V> Iterator for IterMutMap<'s, K, V>
where
	K: BitString + Clone,
	V: Default + Clone + Eq,
{
	type Item = (&'s K, &'s mut V);

	fn next(&mut self) -> Option<Self::Item> {
		self.iter.next()
	}
}

/// Iterate over smallest list of bit strings that cover everything with a value or None if not mapped
pub struct IterMapFull<'s, K, V>
where
	K: BitString + Clone,
	V: Default + Clone + Eq,
{
	iter: crate::tree::IterLeafFull<'s, TpMap<K, V>>,
}

impl<'s, K, V> Iterator for IterMapFull<'s, K, V>
where
	K: BitString + Clone,
	V: Default + Clone + Eq,
{
	type Item = (K, Option<&'s V>);

	fn next(&mut self) -> Option<Self::Item> {
		self.iter.next()
	}
}