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, unsigned long index, int options)
22 unsigned long bitmask;
24 struct btrie_node* tree = root->btrie_root;
26 lz = index ? ICEIL(msbitl - clzl(index), root->order) : 0;
27 lz = lz * root->order;
28 bitmask = ((1 << root->order) - 1) << lz;
30 // Time complexity: O(log_2(log_2(N))) where N is the index to lookup
31 while (bitmask && tree) {
32 i = (index & bitmask) >> lz;
33 struct btrie_node *subtree = 0, *pos, *n;
35 llist_for_each(pos, n, &tree->children, siblings)
37 if (pos->index == i) {
43 if (!subtree && (options & BTRIE_INSERT)) {
44 struct btrie_node* new_tree = vzalloc(sizeof(struct btrie_node));
46 new_tree->parent = tree;
47 llist_init_head(&new_tree->children);
49 llist_append(&tree->children, &new_tree->siblings);
50 llist_append(&root->btrie_root->nodes, &new_tree->nodes);
55 bitmask = bitmask >> root->order;
63 btrie_init(struct btrie* btrie, unsigned int order)
65 btrie->btrie_root = vzalloc(sizeof(struct btrie_node));
66 llist_init_head(&btrie->btrie_root->nodes);
67 llist_init_head(&btrie->btrie_root->children);
72 btrie_get(struct btrie* root, unsigned long index)
74 struct btrie_node* node = __btrie_traversal(root, index, 0);
82 btrie_set(struct btrie* root, unsigned long index, void* data)
84 struct btrie_node* node = __btrie_traversal(root, index, BTRIE_INSERT);
89 __btrie_rm_recursive(struct btrie_node* node)
91 struct btrie_node* parent = node->parent;
94 llist_delete(&node->siblings);
95 llist_delete(&node->nodes);
97 if (llist_empty(&parent->children) && !parent->data) {
98 __btrie_rm_recursive(parent);
104 btrie_remove(struct btrie* root, unsigned long index)
106 struct btrie_node* node = __btrie_traversal(root, index, 0);
110 void* data = node->data;
111 if (!llist_empty(&node->children)) {
114 __btrie_rm_recursive(node);
120 btrie_release(struct btrie* tree)
122 struct btrie_node *pos, *n;
123 llist_for_each(pos, n, &tree->btrie_root->nodes, nodes)
128 vfree(tree->btrie_root);