Debian Codegraph @

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

raw
1 /*
2 * RB-Tree Implementation
3 *
4 * This implements the insertion/removal of elements in RB-Trees. You're highly
5 * recommended to have an RB-Tree documentation at hand when reading this. Both
6 * insertion and removal can be split into a handful of situations that can
7 * occur. Those situations are enumerated as "Case 1" to "Case n" here, and
8 * follow closely the cases described in most RB-Tree documentations. This file
9 * does not explain why it is enough to handle just those cases, nor does it
10 * provide a proof of correctness. Dig out your algorithm 101 handbook if
11 * you're interested.
12 *
13 * This implementation is *not* straightforward. Usually, a handful of
14 * rotation, reparent, swap and link helpers can be used to implement the
15 * rebalance operations. However, those often perform unnecessary writes.
16 * Therefore, this implementation hard-codes all the operations. You're highly
17 * recommended to look at the two basic helpers before reading the code:
18 * c_rbnode_swap_child()
19 * c_rbnode_set_parent_and_flags()
20 * Those are the only helpers used, hence, you should really know what they do
21 * before digging into the code.
22 *
23 * For a highlevel documentation of the API, see the header file and docbook
24 * comments.
25 */
26
27 #include <assert.h>
28 #include <c-stdaux.h>
29 #include <stdalign.h>
30 #include <stddef.h>
31 #include "c-rbtree.h"
32 #include "c-rbtree-private.h"
33
34 /*
35 * We use the lower 2 bits of CRBNode pointers to store flags. Make sure
36 * CRBNode is 4-byte aligned, so the lower 2 bits are actually unused. We also
37 * sometimes store a pointer to the root-node, so make sure this one is also 4
38 * byte aligned.
39 *
40 * Additionally, we want to avoid an alignment that is bigger than the
41 * alignment guaranteed by the system allocator or supported by the system
42 * linker. As there is no standard way to check this, we simply verify against
43 * `alignof(max_align_t)`, as this alignment must be supported by the
44 * toolchain.
45 *
46 * m64k is special here, as it only has a 2-byte max-alignment, but still
47 * guarantees a >=4-byte alignment on allocations. So hard-code the maximum for
48 * it.
49 */
50 #ifdef __m68k__
51 # define C_RBTREE_MAX_ALIGN (C_MAX(4, alignof(max_align_t)))
52 #else
53 # define C_RBTREE_MAX_ALIGN (alignof(max_align_t))
54 #endif
55 static_assert(alignof(CRBNode) <= C_RBTREE_MAX_ALIGN, "Invalid RBNode alignment");
56 static_assert(alignof(CRBNode) >= 4, "Invalid CRBNode alignment");
57 static_assert(alignof(CRBTree) <= C_RBTREE_MAX_ALIGN, "Invalid RBTree alignment");
58 static_assert(alignof(CRBTree) >= 4, "Invalid CRBTree alignment");
59
60 /**
61 * DOC: Traversal
62 *
63 * If you prefer open-coding the tree traversal over the built-in iterators,
64 * c-rbtree provides a set of helpers to find starting position and end nodes
65 * for different kind of tree traversals.
66 */
67 /**/
68
69 /**
70 * c_rbnode_leftmost() - Return leftmost child
71 * @n: Current node, or NULL
72 *
73 * This returns the leftmost child of ``n``. If ``n`` is NULL, this will return
74 * NULL. In all other cases, this function returns a valid pointer. That is, if
75 * ``n`` does not have any left children, this returns ``n``.
76 *
77 * Worst case runtime (n: number of elements in tree): O(log(n))
78 *
79 * Return: Pointer to leftmost child, or NULL.
80 */
81 _c_public_ CRBNode *c_rbnode_leftmost(CRBNode *n) {
82 if (n)
83 while (n->left)
84 n = n->left;
85 return n;
86 }
87
88 /**
89 * c_rbnode_rightmost() - Return rightmost child
90 * @n: Current node, or NULL
91 *
92 * This returns the rightmost child of ``n``. If ``n`` is NULL, this will
93 * return NULL. In all other cases, this function returns a valid pointer. That
94 * is, if ``n`` does not have any right children, this returns ``n``.
95 *
96 * Worst case runtime (n: number of elements in tree): O(log(n))
97 *
98 * Return: Pointer to rightmost child, or NULL.
99 */
100 _c_public_ CRBNode *c_rbnode_rightmost(CRBNode *n) {
101 if (n)
102 while (n->right)
103 n = n->right;
104 return n;
105 }
106
107 /**
108 * c_rbnode_leftdeepest() - Return left-deepest child
109 * @n: Current node, or NULL
110 *
111 * This returns the left-deepest child of ``n``. If ``n`` is NULL, this will
112 * return NULL. In all other cases, this function returns a valid pointer. That
113 * is, if ``n`` does not have any children, this returns ``n``.
114 *
115 * The left-deepest child is defined as the deepest child without any left
116 * (grand-...)siblings.
117 *
118 * Worst case runtime (n: number of elements in tree): O(log(n))
119 *
120 * Return: Pointer to left-deepest child, or NULL.
121 */
122 _c_public_ CRBNode *c_rbnode_leftdeepest(CRBNode *n) {
123 if (n) {
124 for (;;) {
125 if (n->left)
126 n = n->left;
127 else if (n->right)
128 n = n->right;
129 else
130 break;
131 }
132 }
133 return n;
134 }
135
136 /**
137 * c_rbnode_rightdeepest() - Return right-deepest child
138 * @n: Current node, or NULL
139 *
140 * This returns the right-deepest child of ``n``. If ``n`` is NULL, this will
141 * return NULL. In all other cases, this function returns a valid pointer. That
142 * is, if ``n`` does not have any children, this returns ``n``.
143 *
144 * The right-deepest child is defined as the deepest child without any right
145 * (grand-...)siblings.
146 *
147 * Worst case runtime (n: number of elements in tree): O(log(n))
148 *
149 * Return: Pointer to right-deepest child, or NULL.
150 */
151 _c_public_ CRBNode *c_rbnode_rightdeepest(CRBNode *n) {
152 if (n) {
153 for (;;) {
154 if (n->right)
155 n = n->right;
156 else if (n->left)
157 n = n->left;
158 else
159 break;
160 }
161 }
162 return n;
163 }
164
165 /**
166 * c_rbnode_next() - Return next node
167 * @n: Current node, or NULL
168 *
169 * An RB-Tree always defines a linear order of its elements. This function
170 * returns the logically next node to ``n``. If ``n`` is NULL, the last node or
171 * unlinked, this returns NULL.
172 *
173 * Worst case runtime (n: number of elements in tree): O(log(n))
174 *
175 * Return: Pointer to next node, or NULL.
176 */
177 _c_public_ CRBNode *c_rbnode_next(CRBNode *n) {
178 CRBNode *p;
179
180 if (!c_rbnode_is_linked(n))
181 return NULL;
182 if (n->right)
183 return c_rbnode_leftmost(n->right);
184
185 while ((p = c_rbnode_parent(n)) && n == p->right)
186 n = p;
187
188 return p;
189 }
190
191 /**
192 * c_rbnode_prev() - Return previous node
193 * @n: Current node, or NULL
194 *
195 * An RB-Tree always defines a linear order of its elements. This function
196 * returns the logically previous node to ``n``. If ``n`` is NULL, the first
197 * node or unlinked, this returns NULL.
198 *
199 * Worst case runtime (n: number of elements in tree): O(log(n))
200 *
201 * Return: Pointer to previous node, or NULL.
202 */
203 _c_public_ CRBNode *c_rbnode_prev(CRBNode *n) {
204 CRBNode *p;
205
206 if (!c_rbnode_is_linked(n))
207 return NULL;
208 if (n->left)
209 return c_rbnode_rightmost(n->left);
210
211 while ((p = c_rbnode_parent(n)) && n == p->left)
212 n = p;
213
214 return p;
215 }
216
217 /**
218 * c_rbnode_next_postorder() - Return next node in post-order
219 * @n: Current node, or NULL
220 *
221 * This returns the next node to ``n``, based on a left-to-right post-order
222 * traversal. If ``n`` is NULL, the root node, or unlinked, this returns NULL.
223 *
224 * This implements a left-to-right post-order traversal: First visit the left
225 * child of a node, then the right, and lastly the node itself. Children are
226 * traversed recursively.
227 *
228 * This function can be used to implement a left-to-right post-order traversal:
229 *
230 * ::
231 *
232 * for (n = c_rbtree_first_postorder(t); n; n = c_rbnode_next_postorder(n))
233 * visit(n);
234 *
235 * Worst case runtime (n: number of elements in tree): O(log(n))
236 *
237 * Return: Pointer to next node, or NULL.
238 */
239 _c_public_ CRBNode *c_rbnode_next_postorder(CRBNode *n) {
240 CRBNode *p;
241
242 if (!c_rbnode_is_linked(n))
243 return NULL;
244
245 p = c_rbnode_parent(n);
246 if (p && n == p->left && p->right)
247 return c_rbnode_leftdeepest(p->right);
248
249 return p;
250 }
251
252 /**
253 * c_rbnode_prev_postorder() - Return previous node in post-order
254 * @n: Current node, or NULL
255 *
256 * This returns the previous node to ``n``, based on a left-to-right post-order
257 * traversal. That is, it is the inverse operation to
258 * :c:func:`c_rbnode_next_postorder()`. If ``n`` is NULL, the left-deepest
259 * node, or unlinked, this returns NULL.
260 *
261 * This function returns the logical previous node in a directed post-order
262 * traversal. That is, it effectively does a pre-order traversal (since a
263 * reverse post-order traversal is a pre-order traversal). This function does
264 * NOT do a right-to-left post-order traversal! In other words, the following
265 * invariant is guaranteed, if ``c_rbnode_next_postorder(n)`` is non-NULL:
266 *
267 * ::
268 *
269 * n == c_rbnode_prev_postorder(c_rbnode_next_postorder(n))
270 *
271 * This function can be used to implement a right-to-left pre-order traversal,
272 * using the fact that a reverse post-order traversal is also a valid pre-order
273 * traversal:
274 *
275 * ::
276 *
277 * for (n = c_rbtree_last_postorder(t); n; n = c_rbnode_prev_postorder(n))
278 * visit(n);
279 *
280 * This would effectively perform a right-to-left pre-order traversal: first
281 * visit a parent, then its right child, then its left child. Both children are
282 * traversed recursively.
283 *
284 * Worst case runtime (n: number of elements in tree): O(log(n))
285 *
286 * Return: Pointer to previous node in post-order, or NULL.
287 */
288 _c_public_ CRBNode *c_rbnode_prev_postorder(CRBNode *n) {
289 CRBNode *p;
290
291 if (!c_rbnode_is_linked(n))
292 return NULL;
293 if (n->right)
294 return n->right;
295 if (n->left)
296 return n->left;
297
298 while ((p = c_rbnode_parent(n))) {
299 if (p->left && n != p->left)
300 return p->left;
301 n = p;
302 }
303
304 return NULL;
305 }
306
307 /**
308 * c_rbtree_first() - Return first node
309 * @t: Tree to operate on
310 *
311 * An RB-Tree always defines a linear order of its elements. This function
312 * returns the logically first node in ``t``. If ``t`` is empty, NULL is
313 * returned.
314 *
315 * Fixed runtime (n: number of elements in tree): O(log(n))
316 *
317 * Return: Pointer to first node, or NULL.
318 */
319 _c_public_ CRBNode *c_rbtree_first(CRBTree *t) {
320 c_assert(t);
321 return c_rbnode_leftmost(t->root);
322 }
323
324 /**
325 * c_rbtree_last() - Return last node
326 * @t: Tree to operate on
327 *
328 * An RB-Tree always defines a linear order of its elements. This function
329 * returns the logically last node in ``t``. If ``t`` is empty, NULL is
330 * returned.
331 *
332 * Fixed runtime (n: number of elements in tree): O(log(n))
333 *
334 * Return: Pointer to last node, or NULL.
335 */
336 _c_public_ CRBNode *c_rbtree_last(CRBTree *t) {
337 c_assert(t);
338 return c_rbnode_rightmost(t->root);
339 }
340
341 /**
342 * c_rbtree_first_postorder() - Return first node in post-order
343 * @t: Tree to operate on
344 *
345 * This returns the first node of a left-to-right post-order traversal. That
346 * is, it returns the left-deepest leaf. If the tree is empty, this returns
347 * NULL.
348 *
349 * This can also be interpreted as the last node of a right-to-left pre-order
350 * traversal.
351 *
352 * Fixed runtime (n: number of elements in tree): O(log(n))
353 *
354 * Return: Pointer to first node in post-order, or NULL.
355 */
356 _c_public_ CRBNode *c_rbtree_first_postorder(CRBTree *t) {
357 c_assert(t);
358 return c_rbnode_leftdeepest(t->root);
359 }
360
361 /**
362 * c_rbtree_last_postorder() - Return last node in post-order
363 * @t: Tree to operate on
364 *
365 * This returns the last node of a left-to-right post-order traversal. That is,
366 * it always returns the root node, or NULL if the tree is empty.
367 *
368 * This can also be interpreted as the first node of a right-to-left pre-order
369 * traversal.
370 *
371 * Fixed runtime (n: number of elements in tree): O(1)
372 *
373 * Return: Pointer to last node in post-order, or NULL.
374 */
375 _c_public_ CRBNode *c_rbtree_last_postorder(CRBTree *t) {
376 c_assert(t);
377 return t->root;
378 }
379
380 /**
381 * DOC: Tree Modification
382 *
383 * Insertion into and removal from an RB-Tree require rebalancing to make sure
384 * the tree stays balanced. The following functions ensure the tree integrity
385 * is kept.
386 */
387 /**/
388
389 static inline void c_rbtree_store(CRBNode **ptr, CRBNode *addr) {
390 /*
391 * We use volatile accesses whenever we STORE left or right members
392 * of a node. This guarantees that any parallel, lockless lookup gets
393 * to see those stores in the correct order, which itself guarantees
394 * that there're no temporary loops during tree rotation.
395 * Note that you still need to properly synchronize your accesses via
396 * seqlocks, rcu, whatever. We just guarantee that you get *some*
397 * result on a lockless traversal and never run into endless loops, or
398 * undefined behavior.
399 */
400 *(volatile CRBNode **)ptr = addr;
401 }
402
403 /*
404 * Set the flags and parent of a node. This should be treated as a simple
405 * assignment of the 'flags' and 'parent' fields of the node. No other magic is
406 * applied. But since both fields share its backing memory, this helper
407 * function is provided.
408 */
409 static inline void c_rbnode_set_parent_and_flags(CRBNode *n, CRBNode *p, unsigned long flags) {
410 n->__parent_and_flags = (unsigned long)p | flags;
411 }
412
413 /*
414 * Nodes in the tree do not separately store a point to the tree root. That is,
415 * there is no way to access the tree-root in O(1) given an arbitrary node.
416 * Fortunately, this is usually not required. The only situation where this is
417 * needed is when rotating the root-node itself.
418 *
419 * In case of the root node, c_rbnode_parent() returns NULL. We use this fact
420 * to re-use the parent-pointer storage of the root node to point to the
421 * CRBTree root. This way, we can rotate the root-node (or add/remove it)
422 * without requiring a separate tree-root pointer.
423 *
424 * However, to keep the tree-modification functions simple, we hide this detail
425 * whenever possible. This means, c_rbnode_parent() will continue to return
426 * NULL, and tree modifications will boldly reset the pointer to NULL on
427 * rotation. Hence, the only way to retain this pointer is to call
428 * c_rbnode_pop_root() on a possible root-node before rotating. This returns
429 * NULL if the node in question is not the root node. Otherwise, it returns the
430 * tree-root, and clears the pointer/flag from the node in question. This way,
431 * you can perform tree operations as usual. Afterwards, use
432 * c_rbnode_push_root() to restore the root-pointer on any possible new root.
433 */
434 static inline CRBTree *c_rbnode_pop_root(CRBNode *n) {
435 CRBTree *t = NULL;
436
437 if (c_rbnode_is_root(n)) {
438 t = c_rbnode_raw(n);
439 n->__parent_and_flags = c_rbnode_flags(n) & ~C_RBNODE_ROOT;
440 }
441
442 return t;
443 }
444
445 /* counter-part to c_rbnode_pop_root() */
446 static inline CRBTree *c_rbnode_push_root(CRBNode *n, CRBTree *t) {
447 if (t) {
448 if (n)
449 n->__parent_and_flags = (unsigned long)t
450 | c_rbnode_flags(n)
451 | C_RBNODE_ROOT;
452 c_rbtree_store(&t->root, n);
453 }
454
455 return NULL;
456 }
457
458 /*
459 * This function partially swaps a child node with another one. That is, this
460 * function changes the parent of @old to point to @new. That is, you use it
461 * when swapping @old with @new, to update the parent's left/right pointer.
462 * This function does *NOT* perform a full swap, nor does it touch any 'parent'
463 * pointer.
464 *
465 * The sole purpose of this function is to shortcut left/right conditionals
466 * like this:
467 *
468 * ::
469 *
470 * if (old == old->parent->left)
471 * old->parent->left = new;
472 * else
473 * old->parent->right = new;
474 *
475 * That's it! If @old is the root node, this will do nothing. The caller must
476 * employ c_rbnode_pop_root() and c_rbnode_push_root().
477 */
478 static inline void c_rbnode_swap_child(CRBNode *old, CRBNode *new) {
479 CRBNode *p = c_rbnode_parent(old);
480
481 if (p) {
482 if (p->left == old)
483 c_rbtree_store(&p->left, new);
484 else
485 c_rbtree_store(&p->right, new);
486 }
487 }
488
489 /**
490 * c_rbtree_move() - Move tree
491 * @to: Destination tree
492 * @from: Source tree
493 *
494 * This imports the entire tree from ``from`` into ``to``. ``to`` must be
495 * empty! ``from`` will be empty afterwards.
496 *
497 * Note that this operates in O(1) time. Only the root-entry is updated to
498 * point to the new tree-root.
499 */
500 _c_public_ void c_rbtree_move(CRBTree *to, CRBTree *from) {
501 CRBTree *t;
502
503 c_assert(!to->root);
504
505 if (from->root) {
506 t = c_rbnode_pop_root(from->root);
507 c_assert(t == from);
508
509 to->root = from->root;
510 from->root = NULL;
511
512 c_rbnode_push_root(to->root, to);
513 }
514 }
515
516 static inline void c_rbtree_paint_terminal(CRBNode *n) {
517 CRBNode *p, *g, *gg, *x;
518 CRBTree *t;
519
520 /*
521 * Case 4:
522 * This path assumes @n is red, @p is red, but the uncle is unset or
523 * black. This implies @g exists and is black.
524 *
525 * This case requires up to 2 rotations to restore the tree invariants.
526 * That is, it runs in O(1) time and fully restores the RB-Tree
527 * invariants, all at the cost of performing at mots 2 rotations.
528 */
529
530 p = c_rbnode_parent(n);
531 g = c_rbnode_parent(p);
532 gg = c_rbnode_parent(g);
533
534 c_assert(c_rbnode_is_red(p));
535 c_assert(c_rbnode_is_black(g));
536 c_assert(p == g->left || !g->left || c_rbnode_is_black(g->left));
537 c_assert(p == g->right || !g->right || c_rbnode_is_black(g->right));
538
539 if (p == g->left) {
540 if (n == p->right) {
541 /*
542 * We're the right red child of a red parent, which is
543 * a left child. Rotate on parent and consider us to be
544 * the old parent and the old parent to be us, making us
545 * the left child instead of the right child so we can
546 * handle it the same as below. Rotating two red nodes
547 * changes none of the invariants.
548 */
549 x = n->left;
550 c_rbtree_store(&p->right, x);
551 c_rbtree_store(&n->left, p);
552 if (x)
553 c_rbnode_set_parent_and_flags(x, p, c_rbnode_flags(x));
554 c_rbnode_set_parent_and_flags(p, n, c_rbnode_flags(p));
555 p = n;
556 }
557
558 /* 'n' is invalid from here on! */
559
560 /*
561 * We're the red left child of a red parent, black grandparent
562 * and uncle. Rotate parent on grandparent and switch their
563 * colors, making the parent black and the grandparent red. The
564 * root of this subtree was changed from the grandparent to the
565 * parent, but the color remained black, so the number of black
566 * nodes on each path stays the same. However, we got rid of
567 * the double red path as we are still the (red) child of the
568 * parent, which has now turned black. Note that had we been
569 * the right child, rather than the left child, we would now be
570 * the left child of the old grandparent, and we would still
571 * have a double red path. As the new grandparent remains
572 * black, we're done.
573 */
574 x = p->right;
575 t = c_rbnode_pop_root(g);
576 c_rbtree_store(&g->left, x);
577 c_rbtree_store(&p->right, g);
578 c_rbnode_swap_child(g, p);
579 if (x)
580 c_rbnode_set_parent_and_flags(x, g, c_rbnode_flags(x) & ~C_RBNODE_RED);
581 c_rbnode_set_parent_and_flags(p, gg, c_rbnode_flags(p) & ~C_RBNODE_RED);
582 c_rbnode_set_parent_and_flags(g, p, c_rbnode_flags(g) | C_RBNODE_RED);
583 c_rbnode_push_root(p, t);
584 } else /* if (p == g->right) */ { /* same as above, but mirrored */
585 if (n == p->left) {
586 x = n->right;
587 c_rbtree_store(&p->left, n->right);
588 c_rbtree_store(&n->right, p);
589 if (x)
590 c_rbnode_set_parent_and_flags(x, p, c_rbnode_flags(x));
591 c_rbnode_set_parent_and_flags(p, n, c_rbnode_flags(p));
592 p = n;
593 }
594
595 x = p->left;
596 t = c_rbnode_pop_root(g);
597 c_rbtree_store(&g->right, x);
598 c_rbtree_store(&p->left, g);
599 c_rbnode_swap_child(g, p);
600 if (x)
601 c_rbnode_set_parent_and_flags(x, g, c_rbnode_flags(x) & ~C_RBNODE_RED);
602 c_rbnode_set_parent_and_flags(p, gg, c_rbnode_flags(p) & ~C_RBNODE_RED);
603 c_rbnode_set_parent_and_flags(g, p, c_rbnode_flags(g) | C_RBNODE_RED);
604 c_rbnode_push_root(p, t);
605 }
606 }
607
608 static inline CRBNode *c_rbtree_paint_path(CRBNode *n) {
609 CRBNode *p, *g, *u;
610
611 for (;;) {
612 p = c_rbnode_parent(n);
613 if (!p) {
614 /*
615 * Case 1:
616 * We reached the root. Mark it black and be done. As
617 * all leaf-paths share the root, the ratio of black
618 * nodes on each path stays the same.
619 */
620 c_rbnode_set_parent_and_flags(n, c_rbnode_raw(n), c_rbnode_flags(n) & ~C_RBNODE_RED);
621 return NULL;
622 } else if (c_rbnode_is_black(p)) {
623 /*
624 * Case 2:
625 * The parent is already black. As our node is red, we
626 * did not change the number of black nodes on any
627 * path, nor do we have multiple consecutive red nodes.
628 * There is nothing to be done.
629 */
630 return NULL;
631 }
632
633 g = c_rbnode_parent(p);
634 u = (p == g->left) ? g->right : g->left;
635 if (!u || !c_rbnode_is_red(u)) {
636 /*
637 * Case 4:
638 * The parent is red, but its uncle is black. By
639 * rotating the parent above the uncle, we distribute
640 * the red nodes and thus restore the tree invariants.
641 * No recursive fixup will be needed afterwards. Hence,
642 * just let the caller know about @n and make them do
643 * the rotations.
644 */
645 return n;
646 }
647
648 /*
649 * Case 3:
650 * Parent and uncle are both red, and grandparent is black.
651 * Repaint parent and uncle black, the grandparent red and
652 * recurse into the grandparent. Note that this is the only
653 * recursive case. That is, this step restores the tree
654 * invariants for the sub-tree below @p (including @n), but
655 * needs to continue the re-coloring two levels up.
656 */
657 c_rbnode_set_parent_and_flags(p, g, c_rbnode_flags(p) & ~C_RBNODE_RED);
658 c_rbnode_set_parent_and_flags(u, g, c_rbnode_flags(u) & ~C_RBNODE_RED);
659 c_rbnode_set_parent_and_flags(g, c_rbnode_raw(g), c_rbnode_flags(g) | C_RBNODE_RED);
660 n = g;
661 }
662 }
663
664 static inline void c_rbtree_paint(CRBNode *n) {
665 /*
666 * When a new node is inserted into an RB-Tree, we always link it as a
667 * tail-node and paint it red. This way, the node will not violate the
668 * rb-tree invariants regarding the number of black nodes on all paths.
669 *
670 * However, a red node must never have another bordering red-node (ie.,
671 * child or parent). Since the node is newly linked, it does not have
672 * any children. Therefore, all we need to do is fix the path upwards
673 * through all parents until we hit a black parent or can otherwise fix
674 * the coloring.
675 *
676 * This function first walks up the path from @n towards the tree root
677 * (done in c_rbtree_paint_path()). This recolors its parent/uncle, if
678 * possible, until it hits a sub-tree that cannot be fixed via
679 * re-coloring. After c_rbtree_paint_path() returns, there are two
680 * possible outcomes:
681 *
682 * 1) @n is NULL, in which case the tree invariants were
683 * restored by mere recoloring. Nothing is to be done.
684 *
685 * 2) @n is non-NULL, but points to a red ancestor of the
686 * original node. In this case we need to restore the tree
687 * invariants via a simple left or right rotation. This will
688 * be done by c_rbtree_paint_terminal().
689 *
690 * As a summary, this function runs O(log(n)) re-coloring operations in
691 * the worst case, followed by O(1) rotations as final restoration. The
692 * amortized cost, however, is O(1), since re-coloring only recurses
693 * upwards if it hits a red uncle (which can only happen if a previous
694 * operation terminated its operation on that layer).
695 * While amortized painting of inserted nodes is O(1), finding the
696 * correct spot to link the node (before painting it) still requires a
697 * search in the binary tree in O(log(n)).
698 */
699 n = c_rbtree_paint_path(n);
700 if (n)
701 c_rbtree_paint_terminal(n);
702 }
703
704 /**
705 * c_rbnode_link() - Link node into tree
706 * @p: Parent node to link under
707 * @l: Left/right slot of ``p`` to link at
708 * @n: Node to add
709 *
710 * This links ``n`` into an tree underneath another node. The caller must
711 * provide the exact spot where to link the node. That is, the caller must
712 * traverse the tree based on their search order. Once they hit a leaf where to
713 * insert the node, call this function to link it and rebalance the tree.
714 *
715 * For this to work, the caller must provide a pointer to the parent node. If
716 * the tree might be empty, you must resort to :c:func:`c_rbtree_add()`.
717 *
718 * In most cases you are better off using :c:func:`c_rbtree_add()`. See there
719 * for details how tree-insertion works.
720 */
721 _c_public_ void c_rbnode_link(CRBNode *p, CRBNode **l, CRBNode *n) {
722 c_assert(p);
723 c_assert(l);
724 c_assert(n);
725 c_assert(l == &p->left || l == &p->right);
726
727 c_rbnode_set_parent_and_flags(n, p, C_RBNODE_RED);
728 c_rbtree_store(&n->left, NULL);
729 c_rbtree_store(&n->right, NULL);
730 c_rbtree_store(l, n);
731
732 c_rbtree_paint(n);
733 }
734
735 /**
736 * c_rbtree_add() - Add node to tree
737 * @t: Tree to operate one
738 * @p: Parent node to link under, or NULL
739 * @l: Left/right slot of @p (or root) to link at
740 * @n: Node to add
741 *
742 * This links @n into the tree given as ``t``. The caller must provide the
743 * exact spot where to link the node. That is, the caller must traverse the
744 * tree based on their search order. Once they hit a leaf where to insert the
745 * node, call this function to link it and rebalance the tree.
746 *
747 * A typical insertion would look like this (``t`` is your tree, ``n`` is your
748 * node)::
749 *
750 * CRBNode **i, *p;
751 *
752 * i = &t->root;
753 * p = NULL;
754 * while (*i) {
755 * p = *i;
756 * if (compare(n, *i) < 0)
757 * i = &(*i)->left;
758 * else
759 * i = &(*i)->right;
760 * }
761 *
762 * c_rbtree_add(t, p, i, n);
763 *
764 * Once the node is linked into the tree, a simple lookup on the same tree can
765 * be coded like this::
766 *
767 * CRBNode *i;
768 *
769 * i = t->root;
770 * while (i) {
771 * int v = compare(n, i);
772 * if (v < 0)
773 * i = (*i)->left;
774 * else if (v > 0)
775 * i = (*i)->right;
776 * else
777 * break;
778 * }
779 *
780 * When you add nodes to a tree, the memory contents of the node do not matter.
781 * That is, there is no need to initialize the node via
782 * :c:func:`c_rbnode_init()`.
783 * However, if you relink nodes multiple times during their lifetime, it is
784 * usually very convenient to use :c:func:`c_rbnode_init()` and
785 * :c:func:`c_rbnode_unlink()` (rather than :c:func:`c_rbnode_unlink_stale()`).
786 * In those cases, you should validate that a node is unlinked before you call
787 * :c:func:`c_rbtree_add()`.
788 */
789 _c_public_ void c_rbtree_add(CRBTree *t, CRBNode *p, CRBNode **l, CRBNode *n) {
790 c_assert(t);
791 c_assert(l);
792 c_assert(n);
793 c_assert(!p || l == &p->left || l == &p->right);
794 c_assert(p || l == &t->root);
795
796 c_rbnode_set_parent_and_flags(n, p, C_RBNODE_RED);
797 c_rbtree_store(&n->left, NULL);
798 c_rbtree_store(&n->right, NULL);
799
800 if (p)
801 c_rbtree_store(l, n);
802 else
803 c_rbnode_push_root(n, t);
804
805 c_rbtree_paint(n);
806 }
807
808 static inline void c_rbnode_rebalance_terminal(CRBNode *p, CRBNode *previous) {
809 CRBNode *s, *x, *y, *g;
810 CRBTree *t;
811
812 if (previous == p->left) {
813 s = p->right;
814 if (c_rbnode_is_red(s)) {
815 /*
816 * Case 2:
817 * We have a red node as sibling. Rotate it onto our
818 * side so we can later on turn it black. This way, we
819 * gain the additional black node in our path.
820 */
821 t = c_rbnode_pop_root(p);
822 g = c_rbnode_parent(p);
823 x = s->left;
824 c_rbtree_store(&p->right, x);
825 c_rbtree_store(&s->left, p);
826 c_rbnode_swap_child(p, s);
827 c_rbnode_set_parent_and_flags(x, p, c_rbnode_flags(x) & ~C_RBNODE_RED);
828 c_rbnode_set_parent_and_flags(s, g, c_rbnode_flags(s) & ~C_RBNODE_RED);
829 c_rbnode_set_parent_and_flags(p, s, c_rbnode_flags(p) | C_RBNODE_RED);
830 c_rbnode_push_root(s, t);
831 s = x;
832 }
833
834 x = s->right;
835 if (!x || c_rbnode_is_black(x)) {
836 y = s->left;
837 if (!y || c_rbnode_is_black(y)) {
838 /*
839 * Case 3+4:
840 * Our sibling is black and has only black
841 * children. Flip it red and turn parent black.
842 * This way we gained a black node in our path.
843 * Note that the parent must be red, otherwise
844 * it must have been handled by our caller.
845 */
846 c_assert(c_rbnode_is_red(p));
847 c_rbnode_set_parent_and_flags(s, p, c_rbnode_flags(s) | C_RBNODE_RED);
848 c_rbnode_set_parent_and_flags(p, c_rbnode_parent(p), c_rbnode_flags(p) & ~C_RBNODE_RED);
849 return;
850 }
851
852 /*
853 * Case 5:
854 * Left child of our sibling is red, right one is black.
855 * Rotate on parent so the right child of our sibling is
856 * now red, and we can fall through to case 6.
857 */
858 x = y->right;
859 c_rbtree_store(&s->left, y->right);
860 c_rbtree_store(&y->right, s);
861 c_rbtree_store(&p->right, y);
862 if (x)
863 c_rbnode_set_parent_and_flags(x, s, c_rbnode_flags(x) & ~C_RBNODE_RED);
864 x = s;
865 s = y;
866 }
867
868 /*
869 * Case 6:
870 * The right child of our sibling is red. Rotate left and flip
871 * colors, which gains us an additional black node in our path,
872 * that was previously on our sibling.
873 */
874 t = c_rbnode_pop_root(p);
875 g = c_rbnode_parent(p);
876 y = s->left;
877 c_rbtree_store(&p->right, y);
878 c_rbtree_store(&s->left, p);
879 c_rbnode_swap_child(p, s);
880 c_rbnode_set_parent_and_flags(x, s, c_rbnode_flags(x) & ~C_RBNODE_RED);
881 if (y)
882 c_rbnode_set_parent_and_flags(y, p, c_rbnode_flags(y));
883 c_rbnode_set_parent_and_flags(s, g, c_rbnode_flags(p));
884 c_rbnode_set_parent_and_flags(p, s, c_rbnode_flags(p) & ~C_RBNODE_RED);
885 c_rbnode_push_root(s, t);
886 } else /* if (previous == p->right) */ { /* same as above, but mirrored */
887 s = p->left;
888 if (c_rbnode_is_red(s)) {
889 t = c_rbnode_pop_root(p);
890 g = c_rbnode_parent(p);
891 x = s->right;
892 c_rbtree_store(&p->left, x);
893 c_rbtree_store(&s->right, p);
894 c_rbnode_swap_child(p, s);
895 c_rbnode_set_parent_and_flags(x, p, c_rbnode_flags(x) & ~C_RBNODE_RED);
896 c_rbnode_set_parent_and_flags(s, g, c_rbnode_flags(s) & ~C_RBNODE_RED);
897 c_rbnode_set_parent_and_flags(p, s, c_rbnode_flags(p) | C_RBNODE_RED);
898 c_rbnode_push_root(s, t);
899 s = x;
900 }
901
902 x = s->left;
903 if (!x || c_rbnode_is_black(x)) {
904 y = s->right;
905 if (!y || c_rbnode_is_black(y)) {
906 c_assert(c_rbnode_is_red(p));
907 c_rbnode_set_parent_and_flags(s, p, c_rbnode_flags(s) | C_RBNODE_RED);
908 c_rbnode_set_parent_and_flags(p, c_rbnode_parent(p), c_rbnode_flags(p) & ~C_RBNODE_RED);
909 return;
910 }
911
912 x = y->left;
913 c_rbtree_store(&s->right, y->left);
914 c_rbtree_store(&y->left, s);
915 c_rbtree_store(&p->left, y);
916 if (x)
917 c_rbnode_set_parent_and_flags(x, s, c_rbnode_flags(x) & ~C_RBNODE_RED);
918 x = s;
919 s = y;
920 }
921
922 t = c_rbnode_pop_root(p);
923 g = c_rbnode_parent(p);
924 y = s->right;
925 c_rbtree_store(&p->left, y);
926 c_rbtree_store(&s->right, p);
927 c_rbnode_swap_child(p, s);
928 c_rbnode_set_parent_and_flags(x, s, c_rbnode_flags(x) & ~C_RBNODE_RED);
929 if (y)
930 c_rbnode_set_parent_and_flags(y, p, c_rbnode_flags(y));
931 c_rbnode_set_parent_and_flags(s, g, c_rbnode_flags(p));
932 c_rbnode_set_parent_and_flags(p, s, c_rbnode_flags(p) & ~C_RBNODE_RED);
933 c_rbnode_push_root(s, t);
934 }
935 }
936
937 static inline CRBNode *c_rbnode_rebalance_path(CRBNode *p, CRBNode **previous) {
938 CRBNode *s, *nl, *nr;
939
940 while (p) {
941 s = (*previous == p->left) ? p->right : p->left;
942 nl = s->left;
943 nr = s->right;
944
945 /*
946 * If the sibling under @p is black and exclusively has black
947 * children itself (i.e., nephews/nieces in @nl/@nr), then we
948 * can easily re-color to fix this sub-tree, and continue one
949 * layer up. However, if that's not the case, we have tree
950 * rotations at our hands to move one of the black nodes into
951 * our path, then turning the red node black to fully restore
952 * the RB-Tree invariants again. This fixup will be done by the
953 * caller, so we just let them know where to do that.
954 */
955 if (c_rbnode_is_red(s) ||
956 (nl && c_rbnode_is_red(nl)) ||
957 (nr && c_rbnode_is_red(nr)))
958 return p;
959
960 /*
961 * Case 3+4:
962 * Sibling is black, and all nephews/nieces are black. Flip
963 * sibling red. This way the sibling lost a black node in its
964 * path, thus getting even with our path. However, paths not
965 * going through @p haven't been fixed up, hence we proceed
966 * recursively one layer up.
967 * Before we continue one layer up, there are two possible
968 * terminations: If the parent is red, we can turn it black.
969 * This terminates the rebalancing, since the entire point of
970 * rebalancing is that everything below @p has one black node
971 * less than everything else. Lastly, if there is no layer
972 * above, we hit the tree root and nothing is left to be done.
973 */
974 c_rbnode_set_parent_and_flags(s, p, c_rbnode_flags(s) | C_RBNODE_RED);
975 if (c_rbnode_is_red(p)) {
976 c_rbnode_set_parent_and_flags(p, c_rbnode_parent(p), c_rbnode_flags(p) & ~C_RBNODE_RED);
977 return NULL;
978 }
979
980 *previous = p;
981 p = c_rbnode_parent(p);
982 }
983
984 return NULL;
985 }
986
987 static inline void c_rbnode_rebalance(CRBNode *n) {
988 CRBNode *previous = NULL;
989
990 /*
991 * Rebalance a tree after a node was removed. This function must be
992 * called on the parent of the leaf that was removed. It will first
993 * perform a recursive re-coloring on the parents of @n, until it
994 * either hits the tree-root, or a condition where a tree-rotation is
995 * needed to restore the RB-Tree invariants.
996 */
997
998 n = c_rbnode_rebalance_path(n, &previous);
999 if (n)
1000 c_rbnode_rebalance_terminal(n, previous);
1001 }
1002
1003 /**
1004 * c_rbnode_unlink_stale() - Remove node from tree
1005 * @n: Node to remove
1006 *
1007 * This removes the given node from its tree. Once unlinked, the tree is
1008 * rebalanced.
1009 *
1010 * This does *NOT* reset ``n`` to being unlinked. If you need this, use
1011 * :c:func:`c_rbtree_unlink()`.
1012 */
1013 _c_public_ void c_rbnode_unlink_stale(CRBNode *n) {
1014 CRBTree *t;
1015
1016 c_assert(n);
1017 c_assert(c_rbnode_is_linked(n));
1018
1019 /*
1020 * There are three distinct cases during node removal of a tree:
1021 * * The node has no children, in which case it can simply be removed.
1022 * * The node has exactly one child, in which case the child displaces
1023 * its parent.
1024 * * The node has two children, in which case there is guaranteed to
1025 * be a successor to the node (successor being the node ordered
1026 * directly after it). This successor is the leftmost descendant of
1027 * the node's right child, so it cannot have a left child of its own.
1028 * Therefore, we can simply swap the node with its successor (including
1029 * color) and remove the node from its new place, which will be one of
1030 * the first two cases.
1031 *
1032 * Whenever the node we removed was black, we have to rebalance the
1033 * tree. Note that this affects the actual node we _remove_, not @n (in
1034 * case we swap it).
1035 */
1036
1037 if (!n->left && !n->right) {
1038 /*
1039 * Case 1.0
1040 * The node has no children, it is a leaf-node and we
1041 * can simply unlink it. If it was also black, we have
1042 * to rebalance.
1043 */
1044 t = c_rbnode_pop_root(n);
1045 c_rbnode_swap_child(n, NULL);
1046 c_rbnode_push_root(NULL, t);
1047
1048 if (c_rbnode_is_black(n))
1049 c_rbnode_rebalance(c_rbnode_parent(n));
1050 } else if (!n->left && n->right) {
1051 /*
1052 * Case 1.1:
1053 * The node has exactly one child, and it is on the
1054 * right. The child *must* be red (otherwise, the right
1055 * path has more black nodes than the non-existing left
1056 * path), and the node to be removed must hence be
1057 * black. We simply replace the node with its child,
1058 * turning the red child black, and thus no rebalancing
1059 * is required.
1060 */
1061 t = c_rbnode_pop_root(n);
1062 c_rbnode_swap_child(n, n->right);
1063 c_rbnode_set_parent_and_flags(n->right, c_rbnode_parent(n), c_rbnode_flags(n->right) & ~C_RBNODE_RED);
1064 c_rbnode_push_root(n->right, t);
1065 } else if (n->left && !n->right) {
1066 /*
1067 * Case 1.2:
1068 * The node has exactly one child, and it is on the left. Treat
1069 * it as mirrored case of Case 1.1 (i.e., replace the node by
1070 * its child).
1071 */
1072 t = c_rbnode_pop_root(n);
1073 c_rbnode_swap_child(n, n->left);
1074 c_rbnode_set_parent_and_flags(n->left, c_rbnode_parent(n), c_rbnode_flags(n->left) & ~C_RBNODE_RED);
1075 c_rbnode_push_root(n->left, t);
1076 } else /* if (n->left && n->right) */ {
1077 CRBNode *s, *p, *c, *next = NULL;
1078
1079 /* Cache possible tree-root during tree-rotations. */
1080 t = c_rbnode_pop_root(n);
1081
1082 /*
1083 * Case 1.3:
1084 * We are dealing with a full interior node with a child on
1085 * both sides. We want to find its successor and swap it,
1086 * then remove the node similar to Case 1. For performance
1087 * reasons we don't perform the full swap, but skip links
1088 * that are about to be removed, anyway.
1089 *
1090 * First locate the successor, remember its child and the
1091 * parent the original node should have been linked on,
1092 * before being removed. Then link up both the successor's
1093 * new children and old child.
1094 *
1095 * s: successor
1096 * p: parent
1097 * c: right (and only potential) child of successor
1098 * next: next node to rebalance on
1099 */
1100 s = n->right;
1101 if (!s->left) {
1102 /*
1103 * The immediate right child is the successor,
1104 * the successor's right child remains linked
1105 * as before.
1106 */
1107 p = s;
1108 c = s->right;
1109 } else {
1110 s = c_rbnode_leftmost(s);
1111 p = c_rbnode_parent(s);
1112 c = s->right;
1113
1114 /*
1115 * The new parent pointer of the successor's
1116 * child is set below.
1117 */
1118 c_rbtree_store(&p->left, c);
1119
1120 c_rbtree_store(&s->right, n->right);
1121 c_rbnode_set_parent_and_flags(n->right, s, c_rbnode_flags(n->right));
1122 }
1123
1124 /*
1125 * In both the above cases, the successor's left child
1126 * needs to be replaced with the left child of the node
1127 * that is being removed.
1128 */
1129 c_rbtree_store(&s->left, n->left);
1130 c_rbnode_set_parent_and_flags(n->left, s, c_rbnode_flags(n->left));
1131
1132 /*
1133 * As in cases 1.1 and 1.0 above, if successor was a
1134 * black leaf, we need to rebalance the tree, otherwise
1135 * it must have a red child, so simply recolor that black
1136 * and continue. Note that @next must be stored here, as
1137 * the original color of the successor is forgotten below.
1138 */
1139 if (c)
1140 c_rbnode_set_parent_and_flags(c, p, c_rbnode_flags(c) & ~C_RBNODE_RED);
1141 else
1142 next = c_rbnode_is_black(s) ? p : NULL;
1143
1144 /*
1145 * Update the successor, to inherit the parent and color
1146 * from the node being removed.
1147 */
1148 if (c_rbnode_is_red(n))
1149 c_rbnode_set_parent_and_flags(s, c_rbnode_parent(n), c_rbnode_flags(s) | C_RBNODE_RED);
1150 else
1151 c_rbnode_set_parent_and_flags(s, c_rbnode_parent(n), c_rbnode_flags(s) & ~C_RBNODE_RED);
1152
1153 /*
1154 * Update the parent of the node being removed. Note that this
1155 * needs to happen after the parent of the successor is set
1156 * above, as that call would clear the root pointer, if set.
1157 */
1158 c_rbnode_swap_child(n, s);
1159
1160 /* Possibly restore saved tree-root. */
1161 c_rbnode_push_root(s, t);
1162
1163 if (next)
1164 c_rbnode_rebalance(next);
1165 }
1166 }