4 * @brief Bitwise trie tree implementation for sparse array.
8 * @copyright Copyright (c) 2022
12 #include <lunaix/ds/btrie.h>
13 #include <lunaix/mm/valloc.h>
14 #include <lunaix/spike.h>
16 #define BTRIE_INSERT 1
19 __btrie_traversal(struct btrie* root, u32_t index, int options)
21 index = index >> root->truncated;
22 u32_t lz = index ? ROUNDDOWN(31 - clz(index), BTRIE_BITS) : 0;
23 u32_t bitmask = ((1 << BTRIE_BITS) - 1) << lz;
25 struct btrie_node* tree = root->btrie_root;
27 // Time complexity: O(log_2(log_2(N))) where N is the index to lookup
28 while (bitmask && tree) {
29 i = (index & bitmask) >> lz;
30 struct btrie_node *subtree = 0, *pos, *n;
32 llist_for_each(pos, n, &tree->children, siblings)
34 if (pos->index == i) {
40 if (!subtree && (options & BTRIE_INSERT)) {
41 struct btrie_node* new_tree = vzalloc(sizeof(struct btrie_node));
43 new_tree->parent = tree;
44 llist_init_head(&new_tree->children);
46 llist_append(&tree->children, &new_tree->siblings);
47 llist_append(&root->btrie_root->nodes, &new_tree->nodes);
52 bitmask = bitmask >> BTRIE_BITS;
60 btrie_init(struct btrie* btrie, u32_t trunc_bits)
62 btrie->btrie_root = vzalloc(sizeof(struct btrie_node));
63 llist_init_head(&btrie->btrie_root->nodes);
64 llist_init_head(&btrie->btrie_root->children);
65 btrie->truncated = trunc_bits;
69 btrie_get(struct btrie* root, u32_t index)
71 struct btrie_node* node = __btrie_traversal(root, index, 0);
79 btrie_set(struct btrie* root, u32_t index, void* data)
81 struct btrie_node* node = __btrie_traversal(root, index, BTRIE_INSERT);
86 __btrie_rm_recursive(struct btrie_node* node)
88 struct btrie_node* parent = node->parent;
91 llist_delete(&node->siblings);
92 llist_delete(&node->nodes);
94 if (llist_empty(&parent->children) && !parent->data) {
95 __btrie_rm_recursive(parent);
101 btrie_remove(struct btrie* root, u32_t index)
103 struct btrie_node* node = __btrie_traversal(root, index, 0);
107 void* data = node->data;
108 if (!llist_empty(&node->children)) {
111 __btrie_rm_recursive(node);
117 btrie_release(struct btrie* tree)
119 struct btrie_node *pos, *n;
120 llist_for_each(pos, n, &tree->btrie_root->nodes, nodes)
125 vfree(tree->btrie_root);