compiler.h: add offsetof() and container_of()
[nasm/perl-rewrite.git] / rbtree.c
blobadf2b8b462b3a02fe463eb7f81223cb610d26b2f
1 /*
2 * rbtree.c
4 * Simple implementation of a left-leaning red-black tree with 64-bit
5 * integer keys. The search operation will return the highest node <=
6 * the key; only search, insert, and full-tree deletion is supported,
7 * but additional standard llrbtree operations can be coded up at will.
9 * See http://www.cs.princeton.edu/~rs/talks/LLRB/RedBlack.pdf for
10 * information about left-leaning red-black trees.
13 #include "rbtree.h"
14 #include "nasmlib.h"
16 const struct rbtree *rb_search(const struct rbtree *tree, uint64_t key)
18 const struct rbtree *best = NULL;
20 while (tree) {
21 if (tree->key == key)
22 return tree;
23 else if (tree->key > key)
24 tree = tree->left;
25 else {
26 best = tree;
27 tree = tree->right;
30 return best;
33 static bool is_red(struct rbtree *h)
35 return h && h->red;
38 static struct rbtree *rotate_left(struct rbtree *h)
40 struct rbtree *x = h->right;
41 h->right = x->left;
42 x->left = h;
43 x->red = x->left->red;
44 x->left->red = true;
45 return x;
48 static struct rbtree *rotate_right(struct rbtree *h)
50 struct rbtree *x = h->left;
51 h->left = x->right;
52 x->right = h;
53 x->red = x->right->red;
54 x->right->red = true;
55 return x;
58 static void color_flip(struct rbtree *h)
60 h->red = !h->red;
61 h->left->red = !h->left->red;
62 h->right->red = !h->right->red;
65 struct rbtree *rb_insert(struct rbtree *tree, uint64_t key, void *data)
67 if (!tree) {
68 struct rbtree *node = nasm_malloc(sizeof *node);
70 node->key = key;
71 node->data = data;
72 node->red = true;
73 return node;
76 if (is_red(tree->left) && is_red(tree->right))
77 color_flip(tree);
79 if (key < tree->key)
80 tree->left = rb_insert(tree->left, key, data);
81 else
82 tree->right = rb_insert(tree->right, key, data);
84 if (is_red(tree->right))
85 tree = rotate_left(tree);
87 if (is_red(tree->left) && is_red(tree->left->left))
88 tree = rotate_right(tree);
90 return tree;
93 void rb_free(struct rbtree *tree)
95 if (tree) {
96 rb_free(tree->left);
97 rb_free(tree->right);
98 nasm_free(tree);