1 /*
2  * Copyright © 2017 Faith Ekstrand
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20  * DEALINGS IN THE SOFTWARE.
21  */
22 
23 #ifndef RB_TREE_H
24 #define RB_TREE_H
25 
26 #include <stdbool.h>
27 #include <stddef.h>
28 #include <stdint.h>
29 #include <stdlib.h>
30 
31 #ifdef __cplusplus
32 extern "C" {
33 #endif
34 
35 /** A red-black tree node
36  *
37  * This struct represents a node in the red-black tree.  This struct should
38  * be embedded as a member in whatever structure you wish to put in the
39  * tree.
40  */
41 struct rb_node {
42     /** Parent and color of this node
43      *
44      * The least significant bit represents the color and is set to 1 for
45      * black and 0 for red.  The other bits are the pointer to the parent
46      * and that pointer can be retrieved by masking off the bottom bit and
47      * casting to a pointer.
48      */
49     uintptr_t parent;
50 
51     /** Left child of this node, null for a leaf */
52     struct rb_node *left;
53 
54     /** Right child of this node, null for a leaf */
55     struct rb_node *right;
56 };
57 
58 /** Return the parent node of the given node or NULL if it is the root */
59 static inline struct rb_node *
rb_node_parent(struct rb_node * n)60 rb_node_parent(struct rb_node *n)
61 {
62     return (struct rb_node *)(n->parent & ~(uintptr_t)1);
63 }
64 
65 /** A red-black tree
66  *
67  * This struct represents the red-black tree itself.  It is just a pointer
68  * to the root node with no other metadata.
69  */
70 struct rb_tree {
71     struct rb_node *root;
72 };
73 
74 /** Initialize a red-black tree */
75 static inline void
rb_tree_init(struct rb_tree * T)76 rb_tree_init(struct rb_tree *T)
77 {
78     T->root = NULL;
79 }
80 
81 
82 /** Returns true if the red-black tree is empty */
83 static inline bool
rb_tree_is_empty(const struct rb_tree * T)84 rb_tree_is_empty(const struct rb_tree *T)
85 {
86     return T->root == NULL;
87 }
88 
89 /** Get the first (left-most) node in the tree or NULL */
90 struct rb_node *rb_tree_first(struct rb_tree *T);
91 
92 /** Get the last (right-most) node in the tree or NULL */
93 struct rb_node *rb_tree_last(struct rb_tree *T);
94 
95 /** Get the next node (to the right) in the tree or NULL */
96 struct rb_node *rb_node_next(struct rb_node *node);
97 
98 /** Get the next previous (to the left) in the tree or NULL */
99 struct rb_node *rb_node_prev(struct rb_node *node);
100 
101 #ifdef __cplusplus
102 /* This macro will not work correctly if `t' uses virtual inheritance. */
103 #define rb_tree_offsetof(t, f, p) \
104    (((char *) &((t *) p)->f) - ((char *) p))
105 #else
106 #define rb_tree_offsetof(t, f, p) offsetof(t, f)
107 #endif
108 
109 /** Retrieve the data structure containing a node
110  *
111  * \param   type    The type of the containing data structure
112  *
113  * \param   node    A pointer to a rb_node
114  *
115  * \param   field   The rb_node field in the containing data structure
116  */
117 #define rb_node_data(type, node, field) \
118     ((type *)(((char *)(node)) - rb_tree_offsetof(type, field, node)))
119 
120 /** Insert a node into a tree at a particular location
121  *
122  * This function should probably not be used directly as it relies on the
123  * caller to ensure that the parent node is correct.  Use rb_tree_insert
124  * instead.
125  *
126  * \param   T           The red-black tree into which to insert the new node
127  *
128  * \param   parent      The node in the tree that will be the parent of the
129  *                      newly inserted node
130  *
131  * \param   node        The node to insert
132  *
133  * \param   insert_left If true, the new node will be the left child of
134  *                      \p parent, otherwise it will be the right child
135  */
136 void rb_tree_insert_at(struct rb_tree *T, struct rb_node *parent,
137                        struct rb_node *node, bool insert_left);
138 
139 /** Insert a node into a tree
140  *
141  * \param   T       The red-black tree into which to insert the new node
142  *
143  * \param   node    The node to insert
144  *
145  * \param   cmp     A comparison function to use to order the nodes.
146  */
147 static inline void
rb_tree_insert(struct rb_tree * T,struct rb_node * node,int (* cmp)(const struct rb_node *,const struct rb_node *))148 rb_tree_insert(struct rb_tree *T, struct rb_node *node,
149                int (*cmp)(const struct rb_node *, const struct rb_node *))
150 {
151     /* This function is declared inline in the hopes that the compiler can
152      * optimize away the comparison function pointer call.
153      */
154     struct rb_node *y = NULL;
155     struct rb_node *x = T->root;
156     bool left = false;
157     while (x != NULL) {
158         y = x;
159         left = cmp(x, node) < 0;
160         if (left)
161             x = x->left;
162         else
163             x = x->right;
164     }
165 
166     rb_tree_insert_at(T, y, node, left);
167 }
168 
169 /** Remove a node from a tree
170  *
171  * \param   T       The red-black tree from which to remove the node
172  *
173  * \param   node    The node to remove
174  */
175 void rb_tree_remove(struct rb_tree *T, struct rb_node *z);
176 
177 /** Search the tree for a node
178  *
179  * If a node with a matching key exists, the first matching node found will
180  * be returned.  If no matching node exists, NULL is returned.
181  *
182  * \param   T       The red-black tree to search
183  *
184  * \param   key     The key to search for
185  *
186  * \param   cmp     A comparison function to use to order the nodes
187  */
188 static inline struct rb_node *
rb_tree_search(struct rb_tree * T,const void * key,int (* cmp)(const struct rb_node *,const void *))189 rb_tree_search(struct rb_tree *T, const void *key,
190                int (*cmp)(const struct rb_node *, const void *))
191 {
192     /* This function is declared inline in the hopes that the compiler can
193      * optimize away the comparison function pointer call.
194      */
195     struct rb_node *x = T->root;
196     while (x != NULL) {
197         int c = cmp(x, key);
198         if (c < 0) {
199             x = x->left;
200         } else if (c > 0) {
201             x = x->right;
202         } else {
203             /* x is the first *encountered* node matching the key. There may
204              * be other nodes in the left subtree that also match the key.
205              */
206             while (true) {
207                 struct rb_node *prev = rb_node_prev(x);
208 
209                 if (prev == NULL || cmp(prev, key) != 0)
210                     return x;
211 
212                 x = prev;
213             }
214         }
215     }
216 
217     return x;
218 }
219 
220 /** Sloppily search the tree for a node
221  *
222  * This function searches the tree for a given node.  If a node with a
223  * matching key exists, that first encountered matching node found (there may
224  * be other matching nodes in the left subtree) will be returned.  If no node
225  * with an exactly matching key exists, the node returned will be either the
226  * right-most node comparing less than \p key or the right-most node comparing
227  * greater than \p key.  If the tree is empty, NULL is returned.
228  *
229  * \param   T       The red-black tree to search
230  *
231  * \param   key     The key to search for
232  *
233  * \param   cmp     A comparison function to use to order the nodes
234  */
235 static inline struct rb_node *
rb_tree_search_sloppy(struct rb_tree * T,const void * key,int (* cmp)(const struct rb_node *,const void *))236 rb_tree_search_sloppy(struct rb_tree *T, const void *key,
237                       int (*cmp)(const struct rb_node *, const void *))
238 {
239     /* This function is declared inline in the hopes that the compiler can
240      * optimize away the comparison function pointer call.
241      */
242     struct rb_node *y = NULL;
243     struct rb_node *x = T->root;
244     while (x != NULL) {
245         y = x;
246         int c = cmp(x, key);
247         if (c < 0)
248             x = x->left;
249         else if (c > 0)
250             x = x->right;
251         else
252             return x;
253     }
254 
255     return y;
256 }
257 
258 #define rb_node_next_or_null(n) ((n) == NULL ? NULL : rb_node_next(n))
259 #define rb_node_prev_or_null(n) ((n) == NULL ? NULL : rb_node_prev(n))
260 
261 /** Iterate over the nodes in the tree
262  *
263  * \param   type    The type of the containing data structure
264  *
265  * \param   node    The variable name for current node in the iteration;
266  *                  this will be declared as a pointer to \p type
267  *
268  * \param   T       The red-black tree
269  *
270  * \param   field   The rb_node field in containing data structure
271  */
272 #define rb_tree_foreach(type, iter, T, field) \
273    for (type *iter, *__node = (type *)rb_tree_first(T); \
274         __node != NULL && \
275         (iter = rb_node_data(type, (struct rb_node *)__node, field), true); \
276         __node = (type *)rb_node_next((struct rb_node *)__node))
277 
278 /** Iterate over the nodes in the tree, allowing the current node to be freed
279  *
280  * \param   type    The type of the containing data structure
281  *
282  * \param   node    The variable name for current node in the iteration;
283  *                  this will be declared as a pointer to \p type
284  *
285  * \param   T       The red-black tree
286  *
287  * \param   field   The rb_node field in containing data structure
288  */
289 #define rb_tree_foreach_safe(type, iter, T, field) \
290    for (type *iter, \
291              *__node = (type *)rb_tree_first(T), \
292              *__next = (type *)rb_node_next_or_null((struct rb_node *)__node); \
293         __node != NULL && \
294         (iter = rb_node_data(type, (struct rb_node *)__node, field), true); \
295         __node = __next, \
296         __next = (type *)rb_node_next_or_null((struct rb_node *)__node))
297 
298 /** Iterate over the nodes in the tree in reverse
299  *
300  * \param   type    The type of the containing data structure
301  *
302  * \param   node    The variable name for current node in the iteration;
303  *                  this will be declared as a pointer to \p type
304  *
305  * \param   T       The red-black tree
306  *
307  * \param   field   The rb_node field in containing data structure
308  */
309 #define rb_tree_foreach_rev(type, iter, T, field) \
310    for (type *iter, *__node = (type *)rb_tree_last(T); \
311         __node != NULL && \
312         (iter = rb_node_data(type, (struct rb_node *)__node, field), true); \
313         __node = (type *)rb_node_prev((struct rb_node *)__node))
314 
315 /** Iterate over the nodes in the tree in reverse, allowing the current node to be freed
316  *
317  * \param   type    The type of the containing data structure
318  *
319  * \param   node    The variable name for current node in the iteration;
320  *                  this will be declared as a pointer to \p type
321  *
322  * \param   T       The red-black tree
323  *
324  * \param   field   The rb_node field in containing data structure
325  */
326 #define rb_tree_foreach_rev_safe(type, iter, T, field) \
327    for (type *iter, \
328              *__node = (type *)rb_tree_last(T), \
329              *__prev = (type *)rb_node_prev_or_null((struct rb_node *)__node); \
330         __node != NULL && \
331         (iter = rb_node_data(type, (struct rb_node *)__node, field), true); \
332         __node = __prev, \
333         __prev = (type *)rb_node_prev_or_null((struct rb_node *)__node))
334 
335 /** Validate a red-black tree
336  *
337  * This function walks the tree and validates that this is a valid red-
338  * black tree.  If anything is wrong, it will assert-fail.
339  */
340 void rb_tree_validate(struct rb_tree *T);
341 
342 #ifdef __cplusplus
343 } /* extern C */
344 #endif
345 
346 #endif /* RB_TREE_H */
347