-
Notifications
You must be signed in to change notification settings - Fork 2
/
btree.h
110 lines (87 loc) · 2.68 KB
/
btree.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#ifndef _BTREE_H_
#define _BTREE_H_
#include <stdbool.h>
#include "helpers.h"
#include "sllist.h"
#if !defined(BTREE_ORDER)
#define BTREE_ORDER 5
#elif BTREE_ORDER < 3
#error btree order is less than 3
#endif
#define BTREE_ASSERT(x, d) ALGO_ASSERT("btree", x, d)
struct btree_root;
typedef cmp_result_t (*btree_cmp_cbk_t)(void *, void *);
typedef void (*btree_assign_cbk_t)(void *, void *);
typedef struct btree_node * (*btree_zalloc_cbk_t)(struct btree_root *root);
typedef void (*btree_free_cbk_t)(struct btree_node *);
typedef void (*btree_traverse_cbk_t)(struct btree_node *, void *);
struct btree_node {
struct btree_node *parent;
struct btree_node *child[BTREE_ORDER];
unsigned long valid;
L1_ALIGNED;
char data[0];
};
struct btree_root {
struct btree_node *root;
unsigned long size;
unsigned long total;
btree_cmp_cbk_t cmp;
btree_assign_cbk_t assign;
btree_zalloc_cbk_t zalloc;
btree_free_cbk_t free;
};
#define BTREE_EMPTY_BRANCH ((struct btree_node *)NULL)
#define btree_empty_root(r) ((r)->root == BTREE_EMPTY_BRANCH)
static inline void btree_init_root(struct btree_root *root,
unsigned long size,
btree_cmp_cbk_t cmp,
btree_assign_cbk_t assign,
btree_zalloc_cbk_t zalloc,
btree_free_cbk_t free)
{
unsigned int i;
BTREE_ASSERT(BTREE_ORDER/2 != 0, "only odd btree order is supported");
root->root = BTREE_EMPTY_BRANCH;
root->size = size;
root->total = size*(BTREE_ORDER - 1);
root->cmp = cmp;
root->assign = assign;
root->zalloc = zalloc;
root->free = free;
}
typedef enum {
BTREE_ADD_SUCCESS,
BTREE_ADD_DUPLICATE,
BTREE_ADD_ALLOC,
} btree_add_result_t;
btree_add_result_t btree_add(struct btree_root *root, void *data);
bool btree_remove(struct btree_root *root, void *data);
bool btree_search(struct btree_root *root, void *key, void **data);
typedef enum {
btree_traverse_type_prefix,
btree_traverse_type_postfix
} btree_traverse_type_t;
void __btree_traverse_prefix(struct btree_node *nodep,
btree_traverse_cbk_t cbk,
void *data);
void __btree_traverse_postfix(struct btree_node *node,
btree_traverse_cbk_t cbk,
void *data);
static inline void btree_traverse(btree_traverse_type_t type,
struct btree_root *root,
btree_traverse_cbk_t cbk,
void *data)
{
if (BTREE_EMPTY_BRANCH != root->root) {
switch (type) {
case btree_traverse_type_prefix:
__btree_traverse_prefix(root->root, cbk, data);
break;
case btree_traverse_type_postfix:
__btree_traverse_postfix(root->root, cbk, data);
break;
}
}
}
#endif