Debian Codegraph @

subprojects/libcrbtree-3/src/c-rbtree.h

raw
1 #pragma once
2
3 /*
4 * c-rbtree: Standalone Red-Black-Tree Implementation in Standard ISO-C11
5 *
6 * Main public header of the c-rbtree library.
7 */
8
9 #ifdef __cplusplus
10 extern "C" {
11 #endif
12
13 /**
14 * DOC:
15 *
16 * The ``c-rbtree.h`` header exposes the full API of the c-rbtree library. It
17 * provides access to the Red-Black Tree structure as well as helper functions
18 * to perform standard tree operations.
19 *
20 * A tree is represented by the :c:struct:`CRBTree` structure. It contains a
21 * *single* field, which is a pointer to the root node. If NULL, the tree is
22 * empty. If non-NULL, there is at least a single element in the tree.
23 *
24 * Each node of the tree is represented by the :c:struct:`CRBNode` structure.
25 * It has three fields. The ``left`` and ``right`` members can be accessed by
26 * the API user directly to traverse the tree. The third member is a
27 * combination of the parent pointer and a set of flags. API users are required
28 * to embed the :c:struct:`CRBNode` object into their own objects and then use
29 * ``offsetof()`` (i.e., ``container_of()`` and friends) to turn
30 * :c:struct:`CRBNode` pointers into pointers to their own enclosing type:
31 */
32 /**/
33
34 #include <assert.h>
35 #include <stdalign.h>
36 #include <stddef.h>
37
38 typedef struct CRBNode CRBNode;
39 typedef struct CRBTree CRBTree;
40
41 /* implementation detail */
42 #define C_RBNODE_RED (0x1UL)
43 #define C_RBNODE_ROOT (0x2UL)
44 #define C_RBNODE_FLAG_MASK (0x3UL)
45
46 /**
47 * DOC: Tree Structure
48 *
49 * The tree structure of c-rbtree is directly exposed in its API. Callers are
50 * allowed to access the node and tree structures directly to traverse the
51 * tree. Tree modifications, however, should be performed via the functions
52 * provided by the library.
53 */
54 /**/
55
56 /**
57 * struct CRBNode - Node of a Red-Black Tree
58 *
59 * Each node in an RB-Tree must embed a :c:struct:`CRBNode` object. This object
60 * contains pointers to its left and right child, which can be freely accessed
61 * by the API user at any time. They are NULL, if the node does not have a
62 * left/right child.
63 *
64 * The ``__parent_and_flags`` field must never be accessed directly. It encodes
65 * the pointer to the parent node, and the color of the node. Use the accessor
66 * functions instead.
67 *
68 * There is no reason to initialize a :c:struct:`CRBNode` object before linking
69 * it. However, if you need a boolean state that tells you whether the node is
70 * linked or not, you should initialize the node via :c:func:`c_rbnode_init()`
71 * or :c:macro:`C_RBNODE_INIT()`.
72 */
73 struct CRBNode {
74 /* Anonymous union for alignment guarantees */
75 union {
76 /* Internal state encoding the parent pointer and state */
77 unsigned long __parent_and_flags;
78 /* enforce >=4-byte alignment for @__parent_and_flags */
79 alignas(4) unsigned char __align_dummy;
80 };
81 /** Left child, or NULL */
82 CRBNode *left;
83 /** Right child, or NULL */
84 CRBNode *right;
85 };
86
87 /**
88 * C_RBNODE_INIT() - Initialize RBNode Object
89 * @_var: Backpointer to the variable
90 *
91 * Set the contents of the specified node to its unlinked, unused state, ready
92 * to be linked into a tree.
93 *
94 * Return: Evaluates to the initializer for `_var`.
95 */
96 #define C_RBNODE_INIT(_var) { .__parent_and_flags = (unsigned long)&(_var) }
97
98 CRBNode *c_rbnode_leftmost(CRBNode *n);
99 CRBNode *c_rbnode_rightmost(CRBNode *n);
100 CRBNode *c_rbnode_leftdeepest(CRBNode *n);
101 CRBNode *c_rbnode_rightdeepest(CRBNode *n);
102 CRBNode *c_rbnode_next(CRBNode *n);
103 CRBNode *c_rbnode_prev(CRBNode *n);
104 CRBNode *c_rbnode_next_postorder(CRBNode *n);
105 CRBNode *c_rbnode_prev_postorder(CRBNode *n);
106
107 void c_rbnode_link(CRBNode *p, CRBNode **l, CRBNode *n);
108 void c_rbnode_unlink_stale(CRBNode *n);
109
110 /**
111 * struct CRBTree - Red-Black Tree Top-Level Structure
112 *
113 * Each Red-Black Tree is rooted in an CRBTree object. This object contains a
114 * pointer to the root node of the tree. The API user is free to access the
115 * ``root`` member at any time, and use it to traverse the tree.
116 *
117 * To initialize an RB-Tree, set it to NULL / all zero.
118 */
119 struct CRBTree {
120 /** Anonymous union for alignment guarantees */
121 union {
122 /** Pointer to the root node, or NULL */
123 CRBNode *root;
124 /* enforce >=4-byte alignment for @root */
125 alignas(4) unsigned char __align_dummy;
126 };
127 };
128
129 /**
130 * C_RBTREE_INIT() - Initialize RBTree Object
131 *
132 * Set the contents of the specified tree to its pristine, empty state.
133 *
134 * Return: Evaluates to the initializer for a :c:struct:`CRBTree` object.
135 */
136 #define C_RBTREE_INIT {}
137
138 CRBNode *c_rbtree_first(CRBTree *t);
139 CRBNode *c_rbtree_last(CRBTree *t);
140 CRBNode *c_rbtree_first_postorder(CRBTree *t);
141 CRBNode *c_rbtree_last_postorder(CRBTree *t);
142
143 void c_rbtree_move(CRBTree *to, CRBTree *from);
144 void c_rbtree_add(CRBTree *t, CRBNode *p, CRBNode **l, CRBNode *n);
145
146 /**
147 * c_rbnode_init() - Mark a node as unlinked
148 * @n: Node to operate on
149 *
150 * This marks the node ``n`` as unlinked. The node will be set to a valid state
151 * that can never happen if the node is linked in a tree. Furthermore, this
152 * state is fully known to the implementation, and as such handled gracefully
153 * in all cases.
154 *
155 * You are *NOT* required to call this on your node. :c:func:`c_rbtree_add()`
156 * ca handle uninitialized nodes just fine. However, calling this allows to use
157 * :c:func:`c_rbnode_is_linked()` to check for the state of a node.
158 * Furthermore, iterators and accessors can be called on initialized (yet
159 * unlinked) nodes.
160 *
161 * Use the :c:macro:`C_RBNODE_INIT` macro if you want to initialize static
162 * variables.
163 */
164 static inline void c_rbnode_init(CRBNode *n) {
165 *n = (CRBNode)C_RBNODE_INIT(*n);
166 }
167
168 /**
169 * c_rbnode_entry() - Get parent container of tree node
170 * @_what: Tree node, or NULL
171 * @_t: Type of parent container
172 * @_m: Member name of tree node in ``_t``
173 *
174 * If the tree node ``_what`` is embedded into a surrounding structure, this
175 * will turn the tree node pointer ``_what`` into a pointer to the parent
176 * container (using ``offsetof(3)``, or sometimes called
177 * ``container_of(3)``).
178 *
179 * If ``_what`` is NULL, this will also return NULL.
180 *
181 * Return: Pointer to parent container, or NULL.
182 */
183 #define c_rbnode_entry(_what, _t, _m) \
184 /* \
185 * Note: This was carefully designed to avoid multiple evaluation of \
186 * `_what`, but avoid context-expression-extensions. That is why \
187 * it uses the possibly odd style of \
188 * `(x ?: offsetof(...)) - offsetof(...))`. \
189 */ \
190 ((_t *)(void *)(((unsigned long)(void *)(_what) ?: \
191 offsetof(_t, _m)) - offsetof(_t, _m)))
192
193 /**
194 * c_rbnode_parent() - Return parent pointer
195 * @n: Node to access
196 *
197 * This returns a pointer to the parent of the given node ``n``. If ``n`` does
198 * not have a parent, NULL is returned. If ``n`` is not linked, ``n`` itself is
199 * returned.
200 *
201 * You should not call this on unlinked or uninitialized nodes! If you do, you
202 * better know its semantics.
203 *
204 * Return: Pointer to parent.
205 */
206 static inline CRBNode *c_rbnode_parent(CRBNode *n) {
207 return (n->__parent_and_flags & C_RBNODE_ROOT) ?
208 NULL :
209 (void *)(n->__parent_and_flags & ~C_RBNODE_FLAG_MASK);
210 }
211
212 /**
213 * c_rbnode_is_linked() - Check whether a node is linked
214 * @n: Node to check, or NULL
215 *
216 * This checks whether the passed node is linked. If you pass NULL, or if the
217 * node is not linked into a tree, this will return false. Otherwise, this
218 * returns true.
219 *
220 * Note that you must have either linked the node or initialized it, before
221 * calling this function. Never call this function on uninitialized nodes.
222 * Furthermore, removing a node via :c:func:`c_rbnode_unlink_stale()` does *NOT*
223 * mark the node as unlinked. You have to call :c:func:`c_rbnode_init()`
224 * yourself after removal, or use :c:func:`c_rbnode_unlink()`.
225 *
226 * Return: true if the node is linked, false if not.
227 */
228 static inline _Bool c_rbnode_is_linked(CRBNode *n) {
229 return n && c_rbnode_parent(n) != n;
230 }
231
232 /**
233 * c_rbnode_unlink() - Safely remove node from tree and reinitialize it
234 * @n: Node to remove, or NULL
235 *
236 * This is almost the same as :c:func:`c_rbnode_unlink_stale()`, but extends it
237 * slightly, to be more convenient to use in many cases:
238 *
239 * - If ``n`` is unlinked or NULL, this is a no-op.
240 *
241 * - ``n`` is reinitialized after being removed.
242 */
243 static inline void c_rbnode_unlink(CRBNode *n) {
244 if (c_rbnode_is_linked(n)) {
245 c_rbnode_unlink_stale(n);
246 c_rbnode_init(n);
247 }
248 }
249
250 /**
251 * c_rbtree_init() - Initialize a new RB-Tree
252 * @t: Tree to operate on
253 *
254 * This initializes a new, empty RB-Tree. An RB-Tree must be initialized before
255 * any other functions are called on it. Alternatively, you can zero its memory
256 * or assign :c:macro:`C_RBTREE_INIT`.
257 */
258 static inline void c_rbtree_init(CRBTree *t) {
259 *t = (CRBTree)C_RBTREE_INIT;
260 }
261
262 /**
263 * c_rbtree_is_empty() - Check whether an RB-tree is empty
264 * @t: Tree to operate on
265 *
266 * This checks whether the passed RB-Tree is empty.
267 *
268 * Return: True if tree is empty, false otherwise.
269 */
270 static inline _Bool c_rbtree_is_empty(CRBTree *t) {
271 return !t->root;
272 }
273
274 /**
275 * DOC: Search
276 *
277 * While the API supports direct traversal via the open-coded structures, it
278 * can be cumbersome to use at times. If you, instead, provide a callback to
279 * compare entries in the tree, you can use the following helpers to search the
280 * tree for specific entries, or slots to insert new entries.
281 */
282 /**/
283
284 /**
285 * CRBCompareFunc - Function type to compare a node to a key
286 *
287 * If you use the tree-traversal helpers (which are optional), you need to
288 * provide this callback so they can compare nodes in a tree to the key you
289 * look for.
290 *
291 * The tree is provided as optional context ``t`` to this callback. The key you
292 * look for is provided as ``k``, the current node that should be compared to
293 * is provided as ``n``. This function should work like ``strcmp()``, that is,
294 * return <0 if ``key`` orders before ``n``, 0 if both compare equal, and >0 if
295 * it orders after ``n``.
296 */
297 typedef int (*CRBCompareFunc) (CRBTree *t, void *k, CRBNode *n);
298
299 /**
300 * c_rbtree_find_node() - Find node
301 * @t: Tree to search through
302 * @f: Comparison function
303 * @k: Key to search for
304 *
305 * This searches through ``t`` for a node that compares equal to ``k``. The
306 * function ``f`` must be provided by the caller, which is used to compare
307 * nodes to ``k``. See the documentation of :c:type:`CRBCompareFunc` for
308 * details.
309 *
310 * If there are multiple entries that compare equal to ``k``, this will return
311 * a pseudo-randomly picked node. If you need stable lookup functions for trees
312 * where duplicate entries are allowed, you better code your own lookup.
313 *
314 * Return: Pointer to matching node, or NULL.
315 */
316 static inline CRBNode *c_rbtree_find_node(CRBTree *t, CRBCompareFunc f, const void *k) {
317 CRBNode *i;
318
319 assert(t);
320 assert(f);
321
322 i = t->root;
323 while (i) {
324 int v = f(t, (void *)k, i);
325 if (v < 0)
326 i = i->left;
327 else if (v > 0)
328 i = i->right;
329 else
330 return i;
331 }
332
333 return NULL;
334 }
335
336 /**
337 * c_rbtree_find_entry() - Find entry
338 * @_t: Tree to search through
339 * @_f: Comparison function
340 * @_k: Key to search for
341 * @_s: Type of the structure that embeds the nodes
342 * @_m: Name of the node-member in type @_t
343 *
344 * This is very similar to :c:func:`c_rbtree_find_node()`, but instead of
345 * returning a pointer to the :c:struct:`CRBNode`, it returns a pointer to the
346 * surrounding object. This object must embed the :c:struct:`CRBNode` object.
347 * The type of the surrounding object must be given as ``_s``, and the name of
348 * the embedded :c:struct:`CRBNode` member as ``_m``.
349 *
350 * See :c:func:`c_rbtree_find_node()` and :c:macro:`c_rbnode_entry()` for more
351 * details.
352 *
353 * Return: Pointer to found entry, NULL if not found.
354 */
355 #define c_rbtree_find_entry(_t, _f, _k, _s, _m) \
356 c_rbnode_entry(c_rbtree_find_node((_t), (_f), (_k)), _s, _m)
357
358 /**
359 * c_rbtree_find_slot() - Find slot to insert new node
360 * @t: Tree to search through
361 * @f: Comparison function
362 * @k: Key to search for
363 * @p: Output storage for parent pointer
364 *
365 * This searches through ``t`` just like :c:func:`c_rbtree_find_node()` does.
366 * However, instead of returning a pointer to a node that compares equal to
367 * ``k``, this searches for a slot to insert a node with key ``k``. A pointer
368 * to the slot is returned, and a pointer to the parent of the slot is stored
369 * in ``p``. Both can be passed directly to :c:func:`c_rbtree_add()`, together
370 * with your node to insert.
371 *
372 * If there already is a node in the tree, that compares equal to ``k``, this
373 * will return NULL and store the conflicting node in ``p``. In all other
374 * cases, this will return a pointer (non-NULL) to the empty slot to insert the
375 * node at. ``p`` will point to the parent node of that slot.
376 *
377 * If you want trees that allow duplicate nodes, you better code your own
378 * insertion function.
379 *
380 * Return: Pointer to slot to insert node, or NULL on conflicts.
381 */
382 static inline CRBNode **c_rbtree_find_slot(CRBTree *t, CRBCompareFunc f, const void *k, CRBNode **p) {
383 CRBNode **i;
384
385 assert(t);
386 assert(f);
387 assert(p);
388
389 i = &t->root;
390 *p = NULL;
391 while (*i) {
392 int v = f(t, (void *)k, *i);
393 *p = *i;
394 if (v < 0)
395 i = &(*i)->left;
396 else if (v > 0)
397 i = &(*i)->right;
398 else
399 return NULL;
400 }
401
402 return i;
403 }
404
405 /**
406 * DOC: Iterators
407 *
408 * The ``c_rbtree_for_each*()`` macros provide simple for-loop wrappers to
409 * iterate an RB-Tree. They come in a set of flavours:
410 *
411 * :entry: This combines :c:macro:`c_rbnode_entry()` with the loop iterator, so
412 * the iterator always has the type of the surrounding object, rather
413 * than :c:type:`CRBNode`.
414 *
415 * :safe: The loop iterator always keeps track of the next element to
416 * visit. This means, you can safely modify the current element,
417 * while retaining loop-integrity.
418 * You still must not touch any other entry of the tree. Otherwise,
419 * the loop-iterator will be corrupted. Also remember to only
420 * modify the tree in a way compatible with your iterator-order.
421 * That is, if you use in-order iteration (default), you can unlink
422 * your current object, including re-balancing the tree. However,
423 * if you use post-order, you must not trigger a tree rebalance
424 * operation, since it is not an invariant of post-order iteration.
425 *
426 * :postorder: Rather than the default in-order iteration, this iterates
427 * the tree in post-order.
428 *
429 * :unlink: This unlinks the current element from the tree before the loop
430 * code is run. Note that the tree is not rebalanced. That is,
431 * you must never break out of the loop. If you do so, the tree
432 * is corrupted.
433 */
434 /**/
435
436 #define c_rbtree_for_each(_iter, _tree) \
437 for (_iter = c_rbtree_first(_tree); \
438 _iter; \
439 _iter = c_rbnode_next(_iter))
440
441 #define c_rbtree_for_each_entry(_iter, _tree, _m) \
442 for (_iter = c_rbnode_entry(c_rbtree_first(_tree), __typeof__(*_iter), _m); \
443 _iter; \
444 _iter = c_rbnode_entry(c_rbnode_next(&_iter->_m), __typeof__(*_iter), _m))
445
446 #define c_rbtree_for_each_safe(_iter, _safe, _tree) \
447 for (_iter = c_rbtree_first(_tree), _safe = c_rbnode_next(_iter); \
448 _iter; \
449 _iter = _safe, _safe = c_rbnode_next(_safe))
450
451 #define c_rbtree_for_each_entry_safe(_iter, _safe, _tree, _m) \
452 for (_iter = c_rbnode_entry(c_rbtree_first(_tree), __typeof__(*_iter), _m), \
453 _safe = _iter ? c_rbnode_entry(c_rbnode_next(&_iter->_m), __typeof__(*_iter), _m) : NULL; \
454 _iter; \
455 _iter = _safe, \
456 _safe = _safe ? c_rbnode_entry(c_rbnode_next(&_safe->_m), __typeof__(*_iter), _m) : NULL)
457
458 #define c_rbtree_for_each_postorder(_iter, _tree) \
459 for (_iter = c_rbtree_first_postorder(_tree); \
460 _iter; \
461 _iter = c_rbnode_next_postorder(_iter)) \
462
463 #define c_rbtree_for_each_entry_postorder(_iter, _tree, _m) \
464 for (_iter = c_rbnode_entry(c_rbtree_first_postorder(_tree), __typeof__(*_iter), _m); \
465 _iter; \
466 _iter = c_rbnode_entry(c_rbnode_next_postorder(&_iter->_m), __typeof__(*_iter), _m))
467
468 #define c_rbtree_for_each_safe_postorder(_iter, _safe, _tree) \
469 for (_iter = c_rbtree_first_postorder(_tree), _safe = c_rbnode_next_postorder(_iter); \
470 _iter; \
471 _iter = _safe, _safe = c_rbnode_next_postorder(_safe))
472
473 #define c_rbtree_for_each_entry_safe_postorder(_iter, _safe, _tree, _m) \
474 for (_iter = c_rbnode_entry(c_rbtree_first_postorder(_tree), __typeof__(*_iter), _m), \
475 _safe = _iter ? c_rbnode_entry(c_rbnode_next_postorder(&_iter->_m), __typeof__(*_iter), _m) : NULL; \
476 _iter; \
477 _iter = _safe, \
478 _safe = _safe ? c_rbnode_entry(c_rbnode_next_postorder(&_safe->_m), __typeof__(*_iter), _m) : NULL)
479
480 #define c_rbtree_for_each_safe_postorder_unlink(_iter, _safe, _tree) \
481 for (_iter = c_rbtree_first_postorder(_tree), _safe = c_rbnode_next_postorder(_iter); \
482 _iter ? ((*_iter = (CRBNode)C_RBNODE_INIT(*_iter)), 1) : (((_tree)->root = NULL), 0); \
483 _iter = _safe, _safe = c_rbnode_next_postorder(_safe)) \
484
485 #define c_rbtree_for_each_entry_safe_postorder_unlink(_iter, _safe, _tree, _m) \
486 for (_iter = c_rbnode_entry(c_rbtree_first_postorder(_tree), __typeof__(*_iter), _m), \
487 _safe = _iter ? c_rbnode_entry(c_rbnode_next_postorder(&_iter->_m), __typeof__(*_iter), _m) : NULL; \
488 _iter ? ((_iter->_m = (CRBNode)C_RBNODE_INIT(_iter->_m)), 1) : (((_tree)->root = NULL), 0); \
489 _iter = _safe, \
490 _safe = _safe ? c_rbnode_entry(c_rbnode_next_postorder(&_safe->_m), __typeof__(*_iter), _m) : NULL)
491
492 #ifdef __cplusplus
493 }
494 #endif