29 #ifndef __BASE_TRIE_HH__
30 #define __BASE_TRIE_HH__
34 #include <type_traits>
53 template <
class Key,
class Value>
57 static_assert(std::is_integral_v<Key>,
"Key has to be an integral type");
135 static const unsigned MaxBits =
sizeof(Key) * 8;
151 if (kid && kid->matches(key) && (kid->mask & new_mask) == kid->mask) {
171 const Key msb = 1ULL << (
MaxBits - 1);
172 return orig | (orig >> 1) | msb;
190 if (node->kids[0] && node->kids[0]->matches(key))
191 node = node->kids[0];
192 else if (node->kids[1] && node->kids[1]->matches(key))
193 node = node->kids[1];
219 Key new_mask = ~(Key)0;
228 while (
goesAfter(&node, node->kids[0], key, new_mask) ||
229 goesAfter(&node, node->kids[1], key, new_mask))
233 Key cur_mask = node->mask;
235 if (cur_mask == new_mask) {
236 assert(!node->value);
241 for (
unsigned int i = 0;
i < 2;
i++) {
242 Node *&kid = node->kids[
i];
246 new_node =
new Node(key, new_mask,
val);
247 new_node->parent = node;
257 last_mask = cur_mask;
259 done = ((key & cur_mask) != (kid->key & cur_mask)) ||
260 last_mask == new_mask;
262 cur_mask = last_mask;
265 if (cur_mask == node->mask)
269 new_node =
new Node(key, cur_mask, NULL);
270 new_node->parent = node;
271 kid->parent = new_node;
272 new_node->kids[0] = kid;
276 if (cur_mask == new_mask) {
277 new_node->value =
val;
282 new_node =
new Node(key, new_mask,
val);
283 new_node->parent = kid;
284 kid->kids[1] = new_node;
288 panic(
"Reached the end of the Trie insert function!\n");
327 panic(
"Trie: Can't remove root node.\n");
329 Node *parent = node->parent;
333 node->kids[0]->parent = parent;
335 if (parent->kids[0] == node)
336 parent->kids[0] = node->kids[0];
337 else if (parent->kids[1] == node)
338 parent->kids[1] = node->kids[0];
340 panic(
"Trie: Inconsistent parent/kid relationship.\n");
342 if (parent->kids[1] && !parent->kids[0]) {
343 parent->kids[0] = parent->kids[1];
344 parent->kids[1] = NULL;
349 if (!parent->kids[1] && !parent->value && parent->parent)
388 dump(
const char *title, std::ostream &
os=std::cout)
390 ccprintf(
os,
"**************************************************\n");
391 ccprintf(
os,
"*** Start of Trie: %s\n", title);
392 ccprintf(
os,
"*** (parent, me, key, mask, value pointer)\n");
393 ccprintf(
os,
"**************************************************\n");