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<Key>::value,
58 "Key has to be an integral type");
136 static const unsigned MaxBits =
sizeof(Key) * 8;
152 if (kid && kid->matches(key) && (kid->mask & new_mask) == kid->mask) {
172 const Key msb = 1ULL << (
MaxBits - 1);
173 return orig | (orig >> 1) | msb;
191 if (node->kids[0] && node->kids[0]->matches(key))
192 node = node->kids[0];
193 else if (node->kids[1] && node->kids[1]->matches(key))
194 node = node->kids[1];
220 Key new_mask = ~(Key)0;
229 while (
goesAfter(&node, node->kids[0], key, new_mask) ||
230 goesAfter(&node, node->kids[1], key, new_mask))
234 Key cur_mask = node->mask;
236 if (cur_mask == new_mask) {
237 assert(!node->value);
242 for (
unsigned int i = 0;
i < 2;
i++) {
243 Node *&kid = node->kids[
i];
247 new_node =
new Node(key, new_mask,
val);
248 new_node->parent = node;
258 last_mask = cur_mask;
260 done = ((key & cur_mask) != (kid->key & cur_mask)) ||
261 last_mask == new_mask;
263 cur_mask = last_mask;
266 if (cur_mask == node->mask)
270 new_node =
new Node(key, cur_mask, NULL);
271 new_node->parent = node;
272 kid->parent = new_node;
273 new_node->kids[0] = kid;
277 if (cur_mask == new_mask) {
278 new_node->value =
val;
283 new_node =
new Node(key, new_mask,
val);
284 new_node->parent = kid;
285 kid->kids[1] = new_node;
289 panic(
"Reached the end of the Trie insert function!\n");
328 panic(
"Trie: Can't remove root node.\n");
330 Node *parent = node->parent;
334 node->kids[0]->parent = parent;
336 if (parent->kids[0] == node)
337 parent->kids[0] = node->kids[0];
338 else if (parent->kids[1] == node)
339 parent->kids[1] = node->kids[0];
341 panic(
"Trie: Inconsistent parent/kid relationship.\n");
343 if (parent->kids[1] && !parent->kids[0]) {
344 parent->kids[0] = parent->kids[1];
345 parent->kids[1] = NULL;
350 if (!parent->kids[1] && !parent->value && parent->parent)
389 dump(
const char *title, std::ostream &
os=std::cout)
391 ccprintf(
os,
"**************************************************\n");
392 ccprintf(
os,
"*** Start of Trie: %s\n", title);
393 ccprintf(
os,
"*** (parent, me, key, mask, value pointer)\n");
394 ccprintf(
os,
"**************************************************\n");