5 * rbtree - talloc-aware Red Black Tree
7 * This is an implementation of a red-black tree based on talloc.
8 * Talloc objects that are stored in the tree have nice properties
9 * such as when the object is talloc_free()d, the object is also
10 * automatically removed from the tree. This is done by making the
11 * nodes of the tree child objects of the talloc object stored in the
12 * tree, so that destructors are called to automatically remove the
15 * The object stored in the tree does NOT become a child object of the
16 * tree itself, so the same object can be stored under several keys at
17 * the same time, and even in several different trees at the same
20 * The example below is a trivial example program that shows how to
21 * use trees that are keyed by a uint32_t. The rb_tree code also contains
22 * support for managing trees that are keyed by an array of uint32. It
23 * is trivial to expand this to "key as string". Just pad the string with
24 * 0 to be a multiple of uint32_t and then chop it up as an array of
27 * This code originates from ctdb, where talloc based trees keyed are
28 * used in several places.
30 * License: GPL (3 or any later version)
31 * Author: Ronnie Sahlberg <ronniesahlberg@gmail.com>
35 * #include <ccan/talloc/talloc.h>
36 * #include <ccan/rbtree/rbtree.h>
38 * static void printtree(trbt_node_t *node, int levels)
41 * if(node==NULL)return;
42 * printtree(node->left, levels+1);
43 * for(i=0;i<levels;i++)printf(" ");
44 * printf("key:%d COLOR:%s\n",
45 * node->key32, node->rb_color==TRBT_BLACK?"BLACK":"RED");
46 * printtree(node->right, levels+1);
49 * static void print_tree(trbt_tree_t *tree)
51 * if(tree->root==NULL){
52 * printf("tree is empty\n");
56 * printtree(tree->root->left, 1);
57 * printf("key:%d COLOR:%s\n", tree->root->key32,
58 * tree->root->rb_color==TRBT_BLACK?"BLACK":"RED");
59 * printtree(tree->root->right, 1);
63 * int main(int argc, char *argv[])
65 * TALLOC_CTX *mem_ctx;
71 * printf("Example of tree keyed by UINT32\n");
72 * mem_ctx = talloc_new(NULL);
74 * // create a tree and store some talloc objects there
75 * tree=trbt_create(mem_ctx, 0);
76 * for (i=0; i<10; i++) {
77 * val = talloc_asprintf(mem_ctx,
78 * "Value string for key %d", i);
79 * trbt_insert32(tree, i, val);
81 * // show what the tree looks like
84 * printf("Lookup item with key 7\n");
85 * val = trbt_lookup32(tree, 7);
86 * printf("Item with key:7 has value:%s\n", (char *)val);
87 * printf("Talloc_free this item\n");
89 * printf("Item is automagically removed from the tree\n");
92 * talloc_free(mem_ctx);
96 int main(int argc, char *argv[])
101 if (strcmp(argv[1], "depends") == 0) {
102 printf("ccan/talloc\n");