29 #ifndef __BASE_TRIE_HH__
30 #define __BASE_TRIE_HH__
34 #include <type_traits>
50 template <
class Key,
class Value>
54 static_assert(std::is_integral<Key>::value,
55 "Key has to be an integral type");
73 Node(Key _key, Key _mask, Value *_val) :
133 static const unsigned MaxBits =
sizeof(Key) * 8;
147 goesAfter(Node **parent, Node *kid, Key key, Key new_mask)
149 if (kid && kid->matches(key) && (kid->mask & new_mask) == kid->mask) {
170 return orig | (orig >> 1) | msb;
188 if (node->kids[0] && node->kids[0]->matches(key))
189 node = node->
kids[0];
190 else if (node->kids[1] && node->kids[1]->matches(key))
191 node = node->
kids[1];
217 Key new_mask = ~(Key)0;
226 while (
goesAfter(&node, node->kids[0], key, new_mask) ||
227 goesAfter(&node, node->kids[1], key, new_mask))
231 Key cur_mask = node->mask;
233 if (cur_mask == new_mask) {
234 assert(!node->value);
239 for (
unsigned int i = 0;
i < 2;
i++) {
240 Node *&kid = node->kids[
i];
244 new_node =
new Node(key, new_mask,
val);
245 new_node->parent = node;
255 last_mask = cur_mask;
257 done = ((key & cur_mask) != (kid->key & cur_mask)) ||
258 last_mask == new_mask;
260 cur_mask = last_mask;
263 if (cur_mask == node->mask)
267 new_node =
new Node(key, cur_mask, NULL);
268 new_node->parent = node;
269 kid->parent = new_node;
270 new_node->kids[0] = kid;
274 if (cur_mask == new_mask) {
275 new_node->value =
val;
280 new_node =
new Node(key, new_mask,
val);
281 new_node->parent = kid;
282 kid->kids[1] = new_node;
286 panic(
"Reached the end of the Trie insert function!\n");
318 Value *
val = node->value;
325 panic(
"Trie: Can't remove root node.\n");
327 Node *parent = node->parent;
331 node->kids[0]->parent = parent;
333 if (parent->kids[0] == node)
334 parent->kids[0] = node->kids[0];
335 else if (parent->kids[1] == node)
336 parent->kids[1] = node->kids[0];
338 panic(
"Trie: Inconsistent parent/kid relationship.\n");
340 if (parent->kids[1] && !parent->kids[0]) {
341 parent->kids[0] = parent->kids[1];
342 parent->kids[1] = NULL;
347 if (!parent->kids[1] && !parent->value && parent->parent)
386 dump(
const char *title, std::ostream &
os=std::cout)
388 ccprintf(
os,
"**************************************************\n");
389 ccprintf(
os,
"*** Start of Trie: %s\n", title);
390 ccprintf(
os,
"*** (parent, me, key, mask, value pointer)\n");
391 ccprintf(
os,
"**************************************************\n");