]> mj.ucw.cz Git - libucw.git/blob - lib/redblack.h
Use thread ID for temporary file creation.
[libucw.git] / lib / redblack.h
1 /*
2  *      UCW Library -- Red-black trees
3  *
4  *      (c) 2002--2005, Robert Spalek <robert@ucw.cz>
5  *
6  *      Skeleton based on hash-tables by:
7  *
8  *      (c) 2002, Martin Mares <mj@ucw.cz>
9  *
10  */
11
12 /*
13  * Data structure description:
14  *
15  * A red-black tree is a binary search tree, where records are stored
16  * in nodes (may be also leaves).  Every node has a colour.  The
17  * following restrictions hold:
18  *
19  * - a parent of a red node is black
20  * - every path from the root to a node with less than 2 children
21  *   contains the same number of black nodes
22  *
23  * A usual interpretation is, that leaves are intervals between records
24  * and contain no data.  Every leaf is black.  This is equivalent, but
25  * saves the space.
26  */
27
28 /*
29  *  This is not a normal header file, it's a generator of red-black trees.
30  *  Each time you include it with parameters set in the corresponding
31  *  preprocessor macros, it generates a tree structure with the parameters
32  *  given.
33  *
34  *  You need to specify:
35  *
36  *  TREE_NODE           data type where a node dwells (usually a struct).
37  *  TREE_PREFIX(x)      macro to add a name prefix (used on all global names
38  *                      defined by the tree generator).
39  *
40  *  Then decide on type of keys:
41  *
42  *  TREE_KEY_ATOMIC=f   use node->f as a key of an atomic type (i.e.,
43  *                      a type which can be compared using '>', `==', and '<')
44  *                      & TREE_ATOMIC_TYPE (defaults to int).
45  *  | TREE_KEY_STRING=f use node->f as a string key, allocated
46  *                      separately from the rest of the node.
47  *  | TREE_KEY_ENDSTRING=f use node->f as a string key, allocated
48  *                      automatically at the end of the node struct
49  *                      (to be declared as "char f[1]" at the end).
50  *  | TREE_KEY_COMPLEX  use a multi-component key; as the name suggests,
51  *                      the passing of parameters is a bit complex then.
52  *                      The TREE_KEY_COMPLEX(x) macro should expand to
53  *                      `x k1, x k2, ... x kn' and you should also define:
54  *    & TREE_KEY_DECL   declaration of function parameters in which key
55  *                      should be passed to all tree operations.
56  *                      That is, `type1 k1, type2 k2, ... typen kn'.
57  *                      With complex keys, TREE_GIVE_CMP is mandatory.
58  *
59  *  Then specify what operations you request (all names are automatically
60  *  prefixed by calling TREE_PREFIX):
61  *
62  *  <always defined>    init() -- initialize the tree.
63  *  TREE_WANT_CLEANUP   cleanup() -- deallocate the tree.
64  *  TREE_WANT_FIND      node *find(key) -- find first node with the specified
65  *                      key, return NULL if no such node exists.
66  *  TREE_WANT_FIND_NEXT node *find_next(node *start) -- find next node with the
67  *                      specified key, return NULL if no such node exists.
68  *                      Implies TREE_DUPLICATES.
69  *  TREE_WANT_SEARCH    node *search(key) -- find the node with the specified
70  *                      or, if it does not exist, the nearest one.
71  *  TREE_WANT_SEARCH_DOWN node *search_down(key) -- find either the node with
72  *                      specified value, or if it does not exist, the node
73  *                      with nearest smaller value.
74  *  TREE_WANT_BOUNDARY  node *boundary(uns direction) -- finds smallest
75  *                      (direction==0) or largest (direction==1) node.
76  *  TREE_WANT_ADJACENT  node *adjacent(node *, uns direction) -- finds next
77  *                      (direction==1) or previous (direction==0) node.
78  *  TREE_WANT_NEW       node *new(key) -- create new node with given key.
79  *                      If it already exists, it is created as the last one.
80  *  TREE_WANT_LOOKUP    node *lookup(key) -- find node with given key,
81  *                      if it doesn't exist, create it. Defining
82  *                      TREE_GIVE_INIT_DATA is strongly recommended.
83  *  TREE_WANT_DELETE    int delete(key) -- delete and deallocate node
84  *                      with a given key. Returns success.
85  *  TREE_WANT_REMOVE    remove(node *) -- delete and deallocate given node.
86  *
87  *  TREE_WANT_DUMP      dump() -- dumps the whole tree to stdout
88  *
89  *  You can also supply several functions:
90  *
91  *  TREE_GIVE_CMP       int cmp(key1, key2) -- return -1, 0, and 1 according to
92  *                      the relation of keys.  By default, we use <, ==, > for
93  *                      atomic types and either strcmp or strcasecmp for
94  *                      strings.
95  *  TREE_GIVE_EXTRA_SIZE int extra_size(key) -- returns how many bytes after the
96  *                      node should be allocated for dynamic data. Default=0
97  *                      or length of the string with TREE_KEY_ENDSTRING.
98  *  TREE_GIVE_INIT_KEY  void init_key(node *,key) -- initialize key in a newly
99  *                      created node. Defaults: assignment for atomic keys
100  *                      and static strings, strcpy for end-allocated strings.
101  *  TREE_GIVE_INIT_DATA void init_data(node *) -- initialize data fields in a
102  *                      newly created node. Very useful for lookup operations.
103  *  TREE_GIVE_ALLOC     void *alloc(unsigned int size) -- allocate space for
104  *                      a node. Default is either normal or pooled allocation
105  *                      depending on whether we want deletions.
106  *                      void free(void *) -- the converse.
107  *
108  *  ... and a couple of extra parameters:
109  *
110  *  TREE_NOCASE         string comparisons should be case-insensitive.
111  *  TREE_ATOMIC_TYPE=t  Atomic values are of type `t' instead of int.
112  *  TREE_USE_POOL=pool  Allocate all nodes from given mempool.
113  *                      Collides with delete/remove functions.
114  *  TREE_GLOBAL         Functions are exported (i.e., not static).
115  *  TREE_CONSERVE_SPACE Use as little space as possible at the price of a
116  *                      little slowdown.
117  *  TREE_DUPLICATES     Records with duplicate keys are allowed.
118  *  TREE_MAX_DEPTH      Maximal depth of a tree (for stack allocation).
119  *
120  *  If you set TREE_WANT_ITERATOR, you also get a iterator macro at no
121  *  extra charge:
122  *
123  *  TREE_FOR_ALL(tree_prefix, tree_pointer, variable)
124  *    {
125  *      // node *variable gets declared automatically
126  *      do_something_with_node(variable);
127  *      // use TREE_BREAK and TREE_CONTINUE instead of break and continue
128  *      // you must not alter contents of the tree here
129  *    }
130  *  TREE_END_FOR;
131  *
132  *  Then include "lib/redblack.h" and voila, you have a tree suiting all your
133  *  needs (at least those which you've revealed :) ).
134  *
135  *  After including this file, all parameter macros are automatically
136  *  undef'd.
137  */
138
139 #include <string.h>
140
141 #if !defined(TREE_NODE) || !defined(TREE_PREFIX)
142 #error Some of the mandatory configuration macros are missing.
143 #endif
144
145 #define P(x) TREE_PREFIX(x)
146
147 /* Declare buckets and the tree.  */
148
149 typedef TREE_NODE P(node);
150
151 #if defined(TREE_WANT_FIND_NEXT) || defined(TREE_WANT_ADJACENT) || defined(TREE_WANT_ITERATOR) || defined(TREE_WANT_REMOVE)
152 #       define TREE_STORE_PARENT
153 #endif
154
155 typedef struct P(bucket) {
156         struct P(bucket) *son[2];
157 #ifdef TREE_STORE_PARENT
158         struct P(bucket) *parent;
159 #endif
160 #if !defined(TREE_CONSERVE_SPACE) && (defined(TREE_GIVE_EXTRA_SIZE) || defined(TREE_KEY_ENDSTRING))
161         uns red_flag:1;
162 #endif
163         P(node) n;
164 #if !defined(TREE_CONSERVE_SPACE) && !defined(TREE_GIVE_EXTRA_SIZE) && !defined(TREE_KEY_ENDSTRING)
165         uns red_flag:1;
166 #endif
167 } P(bucket);
168
169 struct P(tree) {
170         uns count;
171         uns height;                     /* of black nodes */
172         P(bucket) *root;
173 };
174
175 typedef struct P(stack_entry) {
176         P(bucket) *buck;
177         uns son;
178 } P(stack_entry);
179
180 #define T struct P(tree)
181
182 /* Preset parameters */
183
184 #if defined(TREE_KEY_ATOMIC)
185
186 #define TREE_KEY(x) x TREE_KEY_ATOMIC
187
188 #ifndef TREE_ATOMIC_TYPE
189 #       define TREE_ATOMIC_TYPE int
190 #endif
191 #define TREE_KEY_DECL TREE_ATOMIC_TYPE TREE_KEY()
192
193 #ifndef TREE_GIVE_CMP
194 #       define TREE_GIVE_CMP
195         static inline int P(cmp) (TREE_ATOMIC_TYPE x, TREE_ATOMIC_TYPE y)
196         {
197                 if (x < y)
198                         return -1;
199                 else if (x > y)
200                         return 1;
201                 else
202                         return 0;
203         }
204 #endif
205
206 #ifndef TREE_GIVE_INIT_KEY
207 #       define TREE_GIVE_INIT_KEY
208         static inline void P(init_key) (P(node) *n, TREE_ATOMIC_TYPE k)
209         { TREE_KEY(n->) = k; }
210 #endif
211
212 #elif defined(TREE_KEY_STRING) || defined(TREE_KEY_ENDSTRING)
213
214 #ifdef TREE_KEY_STRING
215 #       define TREE_KEY(x) x TREE_KEY_STRING
216 #       ifndef TREE_GIVE_INIT_KEY
217 #               define TREE_GIVE_INIT_KEY
218                 static inline void P(init_key) (P(node) *n, char *k)
219                 { TREE_KEY(n->) = k; }
220 #       endif
221 #else
222 #       define TREE_KEY(x) x TREE_KEY_ENDSTRING
223 #       define TREE_GIVE_EXTRA_SIZE
224         static inline int P(extra_size) (char *k)
225         { return strlen(k); }
226 #       ifndef TREE_GIVE_INIT_KEY
227 #               define TREE_GIVE_INIT_KEY
228                 static inline void P(init_key) (P(node) *n, char *k)
229                 { strcpy(TREE_KEY(n->), k); }
230 #       endif
231 #endif
232 #define TREE_KEY_DECL char *TREE_KEY()
233
234 #ifndef TREE_GIVE_CMP
235 #       define TREE_GIVE_CMP
236         static inline int P(cmp) (char *x, char *y)
237         {
238 #               ifdef TREE_NOCASE
239                         return strcasecmp(x,y);
240 #               else
241                         return strcmp(x,y);
242 #               endif
243         }
244 #endif
245
246 #elif defined(TREE_KEY_COMPLEX)
247
248 #define TREE_KEY(x) TREE_KEY_COMPLEX(x)
249
250 #else
251 #error You forgot to set the tree key type.
252 #endif
253
254 #ifndef TREE_CONSERVE_SPACE
255         static inline uns P(red_flag) (P(bucket) *node)
256         { return node->red_flag; }
257         static inline void P(set_red_flag) (P(bucket) *node, uns flag)
258         { node->red_flag = flag; }
259         static inline P(bucket) * P(tree_son) (P(bucket) *node, uns id)
260         { return node->son[id]; }
261         static inline void P(set_tree_son) (P(bucket) *node, uns id, P(bucket) *son)
262         { node->son[id] = son; }
263 #else
264         /* Pointers are aligned, hence we can use lower bits.  */
265         static inline uns P(red_flag) (P(bucket) *node)
266         { return ((addr_int_t) node->son[0]) & 1L; }
267         static inline void P(set_red_flag) (P(bucket) *node, uns flag)
268         { node->son[0] = (void*) ( (((addr_int_t) node->son[0]) & ~1L) | (flag & 1L) ); }
269         static inline P(bucket) * P(tree_son) (P(bucket) *node, uns id)
270         { return (void *) (((addr_int_t) node->son[id]) & ~1L); }
271         static inline void P(set_tree_son) (P(bucket) *node, uns id, P(bucket) *son)
272         { node->son[id] = (void *) ((addr_int_t) son | (((addr_int_t) node->son[id]) & 1L) ); }
273 #endif
274
275 /* Defaults for missing parameters.  */
276
277 #ifndef TREE_GIVE_CMP
278 #error Unable to determine how to compare two keys.
279 #endif
280
281 #ifdef TREE_GIVE_EXTRA_SIZE
282 /* This trickery is needed to avoid `unused parameter' warnings */
283 #       define TREE_EXTRA_SIZE P(extra_size)
284 #else
285 /*
286  *  Beware, C macros are expanded iteratively, not recursively,
287  *  hence we get only a _single_ argument, although the expansion
288  *  of TREE_KEY contains commas.
289  */
290 #       define TREE_EXTRA_SIZE(x) 0
291 #endif
292
293 #ifndef TREE_GIVE_INIT_KEY
294 #       error Unable to determine how to initialize keys.
295 #endif
296
297 #ifndef TREE_GIVE_INIT_DATA
298 static inline void P(init_data) (P(node) *n UNUSED)
299 {
300 }
301 #endif
302
303 #include <stdlib.h>
304
305 #ifndef TREE_GIVE_ALLOC
306 #       ifdef TREE_USE_POOL
307                 static inline void * P(alloc) (unsigned int size)
308                 { return mp_alloc_fast(TREE_USE_POOL, size); }
309 #               define TREE_SAFE_FREE(x)
310 #       else
311                 static inline void * P(alloc) (unsigned int size)
312                 { return xmalloc(size); }
313
314                 static inline void P(free) (void *x)
315                 { xfree(x); }
316 #       endif
317 #endif
318
319 #ifndef TREE_SAFE_FREE
320 #       define TREE_SAFE_FREE(x)        P(free) (x)
321 #endif
322
323 #ifdef TREE_GLOBAL
324 #       define STATIC
325 #else
326 #       define STATIC static
327 #endif
328
329 #ifndef TREE_MAX_DEPTH
330 #       define TREE_MAX_DEPTH 64
331 #endif
332
333 #if defined(TREE_WANT_FIND_NEXT) && !defined(TREE_DUPLICATES)
334 #       define TREE_DUPLICATES
335 #endif
336
337 #ifdef TREE_WANT_LOOKUP
338 #ifndef TREE_WANT_FIND
339 #       define TREE_WANT_FIND
340 #endif
341 #ifndef TREE_WANT_NEW
342 #       define TREE_WANT_NEW
343 #endif
344 #endif
345
346 /* Now the operations */
347
348 STATIC void P(init) (T *t)
349 {
350         t->count = t->height = 0;
351         t->root = NULL;
352 }
353
354 #ifdef TREE_WANT_CLEANUP
355 static void P(cleanup_subtree) (T *t, P(bucket) *node)
356 {
357         if (!node)
358                 return;
359         P(cleanup_subtree) (t, P(tree_son) (node, 0));
360         P(cleanup_subtree) (t, P(tree_son) (node, 1));
361         P(free) (node);
362         t->count--;
363 }
364
365 STATIC void P(cleanup) (T *t)
366 {
367         P(cleanup_subtree) (t, t->root);
368         ASSERT(!t->count);
369         t->height = 0;
370 }
371 #endif
372
373 static uns P(fill_stack) (P(stack_entry) *stack, uns max_depth, P(bucket) *node, TREE_KEY_DECL, uns son_id UNUSED)
374 {
375         uns i;
376         stack[0].buck = node;
377         for (i=0; stack[i].buck; i++)
378         {
379                 int cmp;
380                 cmp = P(cmp) (TREE_KEY(), TREE_KEY(stack[i].buck->n.));
381                 if (cmp == 0)
382                         break;
383                 else if (cmp < 0)
384                         stack[i].son = 0;
385                 else
386                         stack[i].son = 1;
387                 ASSERT(i+1 < max_depth);
388                 stack[i+1].buck = P(tree_son) (stack[i].buck, stack[i].son);
389         }
390 #ifdef TREE_DUPLICATES
391         if (stack[i].buck)
392         {
393                 uns idx;
394                 /* Find first/last of equal keys according to son_id.  */
395                 idx = P(fill_stack) (stack+i+1, max_depth-i-1,
396                         P(tree_son) (stack[i].buck, son_id), TREE_KEY(), son_id);
397                 if (stack[i+1+idx].buck)
398                 {
399                         stack[i].son = son_id;
400                         i = i+1+idx;
401                 }
402         }
403 #endif
404         stack[i].son = 10;
405         return i;
406 }
407
408 #ifdef TREE_WANT_FIND
409 STATIC P(node) * P(find) (T *t, TREE_KEY_DECL)
410 {
411         P(stack_entry) stack[TREE_MAX_DEPTH];
412         uns depth;
413         depth = P(fill_stack) (stack, TREE_MAX_DEPTH, t->root, TREE_KEY(), 0);
414         return stack[depth].buck ? &stack[depth].buck->n : NULL;
415 }
416 #endif
417
418 #ifdef TREE_WANT_SEARCH_DOWN
419 STATIC P(node) * P(search_down) (T *t, TREE_KEY_DECL)
420 {
421         P(node) *last_right=NULL;
422         P(bucket) *node=t->root;
423         while(node)
424         {
425                 int cmp;
426                 cmp = P(cmp) (TREE_KEY(), TREE_KEY(node->n.));
427                 if (cmp == 0)
428                         return &node->n;
429                 else if (cmp < 0)
430                         node=P(tree_son) (node, 0);
431                 else
432                 {
433                         last_right=&node->n;
434                         node=P(tree_son) (node, 1);
435                 }
436         }
437         return last_right;
438 }
439 #endif
440
441 #ifdef TREE_WANT_BOUNDARY
442 STATIC P(node) * P(boundary) (T *t, uns direction)
443 {
444         P(bucket) *n = t->root, *ns;
445         if (!n)
446                 return NULL;
447         else
448         {
449                 uns son = !!direction;
450                 while ((ns = P(tree_son) (n, son)))
451                         n = ns;
452                 return &n->n;
453         }
454 }
455 #endif
456
457 #ifdef TREE_STORE_PARENT
458 STATIC P(node) * P(adjacent) (P(node) *start, uns direction)
459 {
460         P(bucket) *node = SKIP_BACK(P(bucket), n, start);
461         P(bucket) *next = P(tree_son) (node, direction);
462         if (next)
463         {
464                 while (1)
465                 {
466                         node = P(tree_son) (next, 1 - direction);
467                         if (!node)
468                                 break;
469                         next = node;
470                 }
471         }
472         else
473         {
474                 next = node->parent;
475                 while (next && node == P(tree_son) (next, direction))
476                 {
477                         node = next;
478                         next = node->parent;
479                 }
480                 if (!next)
481                         return NULL;
482                 ASSERT(node == P(tree_son) (next, 1 - direction));
483         }
484         return &next->n;
485 }
486 #endif
487
488 #if defined(TREE_DUPLICATES) || defined(TREE_WANT_DELETE) || defined(TREE_WANT_REMOVE)
489 static int P(find_next_node) (P(stack_entry) *stack, uns max_depth, uns direction)
490 {
491         uns depth = 0;
492         if (stack[0].buck)
493         {
494                 ASSERT(depth+1 < max_depth);
495                 stack[depth].son = direction;
496                 stack[depth+1].buck = P(tree_son) (stack[depth].buck, direction);
497                 depth++;
498                 while (stack[depth].buck)
499                 {
500                         ASSERT(depth+1 < max_depth);
501                         stack[depth].son = 1 - direction;
502                         stack[depth+1].buck = P(tree_son) (stack[depth].buck, 1 - direction);
503                         depth++;
504                 }
505         }
506         return depth;
507 }
508 #endif
509
510 #ifdef TREE_WANT_FIND_NEXT
511 STATIC P(node) * P(find_next) (P(node) *start)
512 {
513         P(node) *next = P(adjacent) (start, 1);
514         if (next && P(cmp) (TREE_KEY(start->), TREE_KEY(next->)) == 0)
515                 return next;
516         else
517                 return NULL;
518
519 }
520 #endif
521
522 #ifdef TREE_WANT_SEARCH
523 STATIC P(node) * P(search) (T *t, TREE_KEY_DECL)
524 {
525         P(stack_entry) stack[TREE_MAX_DEPTH];
526         uns depth;
527         depth = P(fill_stack) (stack, TREE_MAX_DEPTH, t->root, TREE_KEY(), 0);
528         if (!stack[depth].buck)
529         {
530                 if (depth > 0)
531                         depth--;
532                 else
533                         return NULL;
534         }
535         return &stack[depth].buck->n;
536 }
537 #endif
538
539 #if 0
540 #define TREE_TRACE(txt...) do { printf(txt); fflush(stdout); } while (0)
541 #else
542 #define TREE_TRACE(txt...)
543 #endif
544
545 static inline P(bucket) * P(rotation) (P(bucket) *node, uns son_id)
546 {
547         /* Destroys red_flag's in node, son.  Returns new root.  */
548         P(bucket) *son = P(tree_son) (node, son_id);
549         TREE_TRACE("Rotation (node %d, son %d), direction %d\n", node->n.key, son->n.key, son_id);
550         node->son[son_id] = P(tree_son) (son, 1-son_id);
551         son->son[1-son_id] = node;
552 #ifdef TREE_STORE_PARENT
553         if (node->son[son_id])
554                 node->son[son_id]->parent = node;
555         son->parent = node->parent;
556         node->parent = son;
557 #endif
558         return son;
559 }
560
561 static void P(rotate_after_insert) (T *t, P(stack_entry) *stack, uns depth)
562 {
563         P(bucket) *node;
564         P(bucket) *parent, *grand, *uncle;
565         int s1, s2;
566 try_it_again:
567         node = stack[depth].buck;
568         ASSERT(P(red_flag) (node));
569         /* At this moment, node became red.  The paths sum have
570          * been preserved, but we have to check the parental
571          * condition.  */
572         if (depth == 0)
573         {
574                 ASSERT(t->root == node);
575                 return;
576         }
577         parent = stack[depth-1].buck;
578         if (!P(red_flag) (parent))
579                 return;
580         if (depth == 1)
581         {
582                 ASSERT(t->root == parent);
583                 P(set_red_flag) (parent, 0);
584                 t->height++;
585                 return;
586         }
587         grand = stack[depth-2].buck;
588         ASSERT(!P(red_flag) (grand));
589         /* The parent is also red, the grandparent exists and it
590          * is black.  */
591         s1 = stack[depth-1].son;
592         s2 = stack[depth-2].son;
593         uncle = P(tree_son) (grand, 1-s2);
594         if (uncle && P(red_flag) (uncle))
595         {
596                 /* Red parent and uncle, black grandparent.
597                  * Exchange and try another iteration. */
598                 P(set_red_flag) (parent, 0);
599                 P(set_red_flag) (uncle, 0);
600                 P(set_red_flag) (grand, 1);
601                 depth -= 2;
602                 TREE_TRACE("Swapping colours (parent %d, uncle %d, grand %d), passing thru\n", parent->n.key, uncle->n.key, grand->n.key);
603                 goto try_it_again;
604         }
605         /* Black uncle and grandparent, we need to rotate.  Test
606          * the direction.  */
607         if (s1 == s2)
608         {
609                 node = P(rotation) (grand, s2);
610                 P(set_red_flag) (parent, 0);
611                 P(set_red_flag) (grand, 1);
612         }
613         else
614         {
615                 grand->son[s2] = P(rotation) (parent, s1);
616                 node = P(rotation) (grand, s2);
617                 P(set_red_flag) (grand, 1);
618                 P(set_red_flag) (parent, 1);
619                 P(set_red_flag) (node, 0);
620         }
621         if (depth >= 3)
622                 P(set_tree_son) (stack[depth-3].buck, stack[depth-3].son, node);
623         else
624                 t->root = node;
625 }
626
627 #ifdef TREE_WANT_NEW
628 STATIC P(node) * P(new) (T *t, TREE_KEY_DECL)
629 {
630         P(stack_entry) stack[TREE_MAX_DEPTH];
631         P(bucket) *added;
632         uns depth;
633         depth = P(fill_stack) (stack, TREE_MAX_DEPTH, t->root, TREE_KEY(), 1);
634 #ifdef TREE_DUPLICATES
635         /* It is the last found value, hence everything in the right subtree is
636          * strongly _bigger_.  */
637         depth += P(find_next_node) (stack+depth, TREE_MAX_DEPTH-depth, 1);
638 #endif
639         ASSERT(!stack[depth].buck);
640         /* We are in a leaf, hence we can easily append a new leaf to it.  */
641         added = P(alloc) (sizeof(struct P(bucket)) + TREE_EXTRA_SIZE(TREE_KEY()) );
642         added->son[0] = added->son[1] = NULL;
643         stack[depth].buck = added;
644         if (depth > 0)
645         {
646 #ifdef TREE_STORE_PARENT
647                 added->parent = stack[depth-1].buck;
648 #endif
649                 P(set_tree_son) (stack[depth-1].buck, stack[depth-1].son, added);
650         }
651         else
652         {
653 #ifdef TREE_STORE_PARENT
654                 added->parent = NULL;
655 #endif
656                 t->root = added;
657         }
658         P(set_red_flag) (added, 1);     /* Set it red to not disturb the path sum.  */
659         P(init_key) (&added->n, TREE_KEY());
660         P(init_data) (&added->n);
661         t->count++;
662         /* Let us reorganize the red_flag's and the structure of the tree.  */
663         P(rotate_after_insert) (t, stack, depth);
664         return &added->n;
665 }
666 #endif
667
668 #ifdef TREE_WANT_LOOKUP
669 STATIC P(node) * P(lookup) (T *t, TREE_KEY_DECL)
670 {
671         P(node) *node;
672         node = P(find) (t, TREE_KEY());
673         if (node)
674                 return node;
675         return P(new) (t, TREE_KEY());
676 }
677 #endif
678
679 #if defined(TREE_WANT_REMOVE) || defined(TREE_WANT_DELETE)
680 static void P(rotate_after_delete) (T *t, P(stack_entry) *stack, int depth)
681 {
682         uns iteration = 0;
683         P(bucket) *parent, *sibling, *instead;
684         uns parent_red, del_son, sibl_red;
685 missing_black:
686         if (depth < 0)
687         {
688                 t->height--;
689                 return;
690         }
691         parent = stack[depth].buck;
692         parent_red = P(red_flag) (parent);
693         del_son = stack[depth].son;
694         /* For the 1st iteration: we have deleted parent->son[del_son], which
695          * was a black node with no son.  Hence there is one mising black
696          * vertex in that path, which we are going to fix now.
697          *
698          * For other iterations: in that path, there is also missing a black
699          * node.  */
700         if (!iteration)
701                 ASSERT(!P(tree_son) (parent, del_son));
702         sibling = P(tree_son) (parent, 1-del_son);
703         ASSERT(sibling);
704         sibl_red = P(red_flag) (sibling);
705         instead = NULL;
706         if (!sibl_red)
707         {
708                 P(bucket) *son[2];
709                 uns red[2];
710                 son[0] = P(tree_son) (sibling, 0);
711                 son[1] = P(tree_son) (sibling, 1);
712                 red[0] = son[0] ? P(red_flag) (son[0]) : 0;
713                 red[1] = son[1] ? P(red_flag) (son[1]) : 0;
714                 if (!red[0] && !red[1])
715                 {
716                         P(set_red_flag) (sibling, 1);
717                         P(set_red_flag) (parent, 0);
718                         if (parent_red)
719                                 return;
720                         else
721                         {
722                                 depth--;
723                                 iteration++;
724                                 TREE_TRACE("Swapping colours (parent %d, sibling %d), passing thru\n", parent->n.key, sibling->n.key);
725                                 goto missing_black;
726                         }
727                 } else if (!red[del_son])
728                 {
729                         instead = P(rotation) (parent, 1-del_son);
730                         P(set_red_flag) (instead, parent_red);
731                         P(set_red_flag) (parent, 0);
732                         P(set_red_flag) (son[1-del_son], 0);
733                 } else /* red[del_son] */
734                 {
735                         parent->son[1-del_son] = P(rotation) (sibling, del_son);
736                         instead = P(rotation) (parent, 1-del_son);
737                         P(set_red_flag) (instead, parent_red);
738                         P(set_red_flag) (parent, 0);
739                         P(set_red_flag) (sibling, 0);
740                 }
741         } else /* sibl_red */
742         {
743                 P(bucket) *grand[2], *son;
744                 uns red[2];
745                 ASSERT(!parent_red);
746                 son = P(tree_son) (sibling, del_son);
747                 ASSERT(son && !P(red_flag) (son));
748                 grand[0] = P(tree_son) (son, 0);
749                 grand[1] = P(tree_son) (son, 1);
750                 red[0] = grand[0] ? P(red_flag) (grand[0]) : 0;
751                 red[1] = grand[1] ? P(red_flag) (grand[1]) : 0;
752                 if (!red[0] && !red[1])
753                 {
754                         instead = P(rotation) (parent, 1-del_son);
755                         P(set_red_flag) (instead, 0);
756                         P(set_red_flag) (parent, 0);
757                         P(set_red_flag) (son, 1);
758                 }
759                 else if (!red[del_son])
760                 {
761                         parent->son[1-del_son] = P(rotation) (sibling, del_son);
762                         instead = P(rotation) (parent, 1-del_son);
763                         P(set_red_flag) (instead, 0);
764                         P(set_red_flag) (parent, 0);
765                         P(set_red_flag) (sibling, 1);
766                         P(set_red_flag) (grand[1-del_son], 0);
767                 } else /* red[del_son] */
768                 {
769                         sibling->son[del_son] = P(rotation) (son, del_son);
770                         parent->son[1-del_son] = P(rotation) (sibling, del_son);
771                         instead = P(rotation) (parent, 1-del_son);
772                         P(set_red_flag) (instead, 0);
773                         P(set_red_flag) (parent, 0);
774                         P(set_red_flag) (sibling, 1);
775                         P(set_red_flag) (son, 0);
776                 }
777         }
778         /* We have performed all desired rotations and need to store the new
779          * pointer to the subtree.  */
780         ASSERT(instead);
781         if (depth > 0)
782                 P(set_tree_son) (stack[depth-1].buck, stack[depth-1].son, instead);
783         else
784                 t->root = instead;
785 }
786
787 static void P(remove_by_stack) (T *t, P(stack_entry) *stack, uns depth)
788 {
789         P(bucket) *node = stack[depth].buck;
790         P(bucket) *son;
791         uns i;
792         for (i=0; i<depth; i++)
793                 ASSERT(P(tree_son) (stack[i].buck, stack[i].son) == stack[i+1].buck);
794         if (P(tree_son) (node, 0) && P(tree_son) (node, 1))
795         {
796                 P(bucket) *xchg;
797                 uns flag_node, flag_xchg;
798                 uns d = P(find_next_node) (stack+depth, TREE_MAX_DEPTH-depth, 1);
799
800                 ASSERT(d >= 2);
801                 d--;
802                 xchg = stack[depth+d].buck;
803                 flag_node = P(red_flag) (node);
804                 flag_xchg = P(red_flag) (xchg);
805                 ASSERT(!P(tree_son) (xchg, 0));
806                 son = P(tree_son) (xchg, 1);
807                 stack[depth].buck = xchg;       /* Magic iff d == 1.  */
808                 stack[depth+d].buck = node;
809                 xchg->son[0] = P(tree_son) (node, 0);
810                 xchg->son[1] = P(tree_son) (node, 1);
811                 if (depth > 0)
812                         P(set_tree_son) (stack[depth-1].buck, stack[depth-1].son, xchg);
813                 else
814                         t->root = xchg;
815                 node->son[0] = NULL;
816                 node->son[1] = son;
817                 P(set_tree_son) (stack[depth+d-1].buck, stack[depth+d-1].son, node);
818 #ifdef TREE_STORE_PARENT
819                 xchg->parent = depth > 0 ? stack[depth-1].buck : NULL;
820                 xchg->son[0]->parent = xchg;
821                 xchg->son[1]->parent = xchg;
822                 node->parent = stack[depth+d-1].buck;
823                 if (son)
824                         son->parent = node;
825 #endif
826                 P(set_red_flag) (xchg, flag_node);
827                 P(set_red_flag) (node, flag_xchg);
828                 depth += d;
829         }
830         else if (P(tree_son) (node, 0))
831                 son = P(tree_son) (node, 0);
832         else
833                 son = P(tree_son) (node, 1);
834         /* At this moment, stack[depth].buck == node and it has at most one son
835          * and it is stored in the variable son.  */
836         t->count--;
837         if (depth > 0)
838         {
839                 P(set_tree_son) (stack[depth-1].buck, stack[depth-1].son, son);
840 #ifdef TREE_STORE_PARENT
841                 if (son)
842                         son->parent = stack[depth-1].buck;
843 #endif
844         }
845         else
846         {
847                 t->root = son;
848 #ifdef TREE_STORE_PARENT
849                 if (son)
850                         son->parent = NULL;
851 #endif
852         }
853         if (P(red_flag) (node))
854         {
855                 ASSERT(!son);
856                 return;
857         }
858         TREE_SAFE_FREE(node);
859         /* We have deleted a black node.  */
860         if (son)
861         {
862                 ASSERT(P(red_flag) (son));
863                 P(set_red_flag) (son, 0);
864                 return;
865         }
866         P(rotate_after_delete) (t, stack, (int) depth - 1);
867 }
868 #endif
869
870 #ifdef TREE_WANT_REMOVE
871 STATIC void P(remove) (T *t, P(node) *Node)
872 {
873         P(stack_entry) stack[TREE_MAX_DEPTH];
874         P(bucket) *node = SKIP_BACK(P(bucket), n, Node);
875         uns depth = 0, i;
876         stack[0].buck = node;
877         stack[0].son = 10;
878         while (node->parent)
879         {
880                 depth++;
881                 ASSERT(depth < TREE_MAX_DEPTH);
882                 stack[depth].buck = node->parent;
883                 stack[depth].son = P(tree_son) (node->parent, 0) == node ? 0 : 1;
884                 node = node->parent;
885         }
886         for (i=0; i<(depth+1)/2; i++)
887         {
888                 P(stack_entry) tmp = stack[i];
889                 stack[i] = stack[depth-i];
890                 stack[depth-i] = tmp;
891         }
892         P(remove_by_stack) (t, stack, depth);
893 }
894 #endif
895
896 #ifdef TREE_WANT_DELETE
897 STATIC int P(delete) (T *t, TREE_KEY_DECL)
898 {
899         P(stack_entry) stack[TREE_MAX_DEPTH];
900         uns depth;
901         depth = P(fill_stack) (stack, TREE_MAX_DEPTH, t->root, TREE_KEY(), 1);
902         if (stack[depth].buck)
903         {
904                 P(remove_by_stack) (t, stack, depth);
905                 return 1;
906         }
907         else
908                 return 0;
909 }
910 #endif
911
912 #ifdef TREE_WANT_DUMP
913 static void P(dump_subtree) (struct fastbuf *fb, T *t, P(bucket) *node, P(bucket) *parent, int cmp_res, int level, uns black)
914 {
915         uns flag;
916         int i;
917         if (!node)
918         {
919                 ASSERT(black == t->height);
920                 return;
921         }
922         flag = P(red_flag) (node);
923 #ifdef TREE_STORE_PARENT
924         ASSERT(node->parent == parent);
925 #endif
926         if (parent)
927         {
928                 ASSERT(!flag || !P(red_flag) (parent));
929                 cmp_res *= P(cmp) (TREE_KEY(node->n.), TREE_KEY(parent->n.));
930 #ifdef TREE_DUPLICATES
931                 ASSERT(cmp_res >= 0);
932 #else
933                 ASSERT(cmp_res > 0);
934 #endif
935         }
936         P(dump_subtree) (fb, t, P(tree_son) (node, 0), node, -1, level+1, black + (1-flag));
937         if (fb)
938         {
939                 char tmp[20];
940                 for (i=0; i<level; i++)
941                         bputs(fb, "  ");
942                 sprintf(tmp, "L%d %c\t", level, flag ? 'R' : 'B');
943                 bputs(fb, tmp);
944                 P(dump_key) (fb, &node->n);
945                 P(dump_data) (fb, &node->n);
946                 bputs(fb, "\n");
947         }
948         P(dump_subtree) (fb, t, P(tree_son) (node, 1), node, +1, level+1, black + (1-flag));
949 }
950
951 STATIC void P(dump) (struct fastbuf *fb, T *t)
952 {
953         if (fb)
954         {
955                 char tmp[50];
956                 sprintf(tmp, "Tree of %d nodes and height %d\n", t->count, t->height);
957                 bputs(fb, tmp);
958         }
959         P(dump_subtree) (fb, t, t->root, NULL, 0, 0, 0);
960         if (fb)
961         {
962                 bputs(fb, "\n");
963                 bflush(fb);
964         }
965 }
966 #endif
967
968 /* And the iterator */
969
970 #ifdef TREE_WANT_ITERATOR
971 static P(node) * P(first_node) (T *t, uns direction)
972 {
973         P(bucket) *node = t->root, *prev = NULL;
974         while (node)
975         {
976                 prev = node;
977                 node = P(tree_son) (node, direction);
978         }
979         return prev ? &prev->n : NULL;
980 }
981
982 #ifndef TREE_FOR_ALL
983
984 #define TREE_FOR_ALL(t_px, t_ptr, t_var)                                                \
985 do                                                                                      \
986 {                                                                                       \
987         GLUE_(t_px,node) *t_var = GLUE_(t_px,first_node)(t_ptr, 0);                     \
988         for (; t_var; t_var = GLUE_(t_px,adjacent)(t_var, 1))                           \
989         {
990 #define TREE_END_FOR } } while(0)
991 #define TREE_BREAK break
992 #define TREE_CONTINUE continue
993
994 #endif
995 #endif
996
997 /* Finally, undefine all the parameters */
998
999 #undef P
1000 #undef T
1001
1002 #undef TREE_NODE
1003 #undef TREE_PREFIX
1004 #undef TREE_KEY_ATOMIC
1005 #undef TREE_KEY_STRING
1006 #undef TREE_KEY_ENDSTRING
1007 #undef TREE_KEY_COMPLEX
1008 #undef TREE_KEY_DECL
1009 #undef TREE_WANT_CLEANUP
1010 #undef TREE_WANT_FIND
1011 #undef TREE_WANT_FIND_NEXT
1012 #undef TREE_WANT_SEARCH
1013 #undef TREE_WANT_SEARCH_DOWN
1014 #undef TREE_WANT_BOUNDARY
1015 #undef TREE_WANT_ADJACENT
1016 #undef TREE_WANT_NEW
1017 #undef TREE_WANT_LOOKUP
1018 #undef TREE_WANT_DELETE
1019 #undef TREE_WANT_REMOVE
1020 #undef TREE_WANT_DUMP
1021 #undef TREE_WANT_ITERATOR
1022 #undef TREE_GIVE_CMP
1023 #undef TREE_GIVE_EXTRA_SIZE
1024 #undef TREE_GIVE_INIT_KEY
1025 #undef TREE_GIVE_INIT_DATA
1026 #undef TREE_GIVE_ALLOC
1027 #undef TREE_NOCASE
1028 #undef TREE_ATOMIC_TYPE
1029 #undef TREE_USE_POOL
1030 #undef TREE_STATIC
1031 #undef TREE_CONSERVE_SPACE
1032 #undef TREE_DUPLICATES
1033 #undef TREE_MAX_DEPTH
1034 #undef TREE_STORE_PARENT
1035 #undef TREE_KEY
1036 #undef TREE_EXTRA_SIZE
1037 #undef TREE_SAFE_FREE
1038 #undef TREE_TRACE
1039 #undef STATIC