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.
16 const struct rbtree
*rb_search(const struct rbtree
*tree
, uint64_t key
)
18 const struct rbtree
*best
= NULL
;
23 else if (tree
->key
> key
)
33 static bool is_red(struct rbtree
*h
)
38 static struct rbtree
*rotate_left(struct rbtree
*h
)
40 struct rbtree
*x
= h
->right
;
43 x
->red
= x
->left
->red
;
48 static struct rbtree
*rotate_right(struct rbtree
*h
)
50 struct rbtree
*x
= h
->left
;
53 x
->red
= x
->right
->red
;
58 static void color_flip(struct rbtree
*h
)
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
)
68 struct rbtree
*node
= nasm_malloc(sizeof *node
);
76 if (is_red(tree
->left
) && is_red(tree
->right
))
80 tree
->left
= rb_insert(tree
->left
, key
, data
);
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
);
93 void rb_free(struct rbtree
*tree
)