Debian Codegraph @

Docs/src/bin/halibut/tree234.c

raw
1 /*
2 * tree234.c: reasonably generic counted 2-3-4 tree routines.
3 *
4 * This file is copyright 1999-2001 Simon Tatham.
5 *
6 * Permission is hereby granted, free of charge, to any person
7 * obtaining a copy of this software and associated documentation
8 * files (the "Software"), to deal in the Software without
9 * restriction, including without limitation the rights to use,
10 * copy, modify, merge, publish, distribute, sublicense, and/or
11 * sell copies of the Software, and to permit persons to whom the
12 * Software is furnished to do so, subject to the following
13 * conditions:
14 *
15 * The above copyright notice and this permission notice shall be
16 * included in all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 * NONINFRINGEMENT. IN NO EVENT SHALL SIMON TATHAM BE LIABLE FOR
22 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
23 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
24 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25 * SOFTWARE.
26 */
27
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <assert.h>
31
32 #include "tree234.h"
33
34 #define smalloc malloc
35 #define sfree free
36
37 #define mknew(typ) ( (typ *) smalloc (sizeof (typ)) )
38
39 #ifdef TEST
40 #define LOG(x) (printf x)
41 #else
42 #define LOG(x)
43 #endif
44
45 typedef struct node234_Tag node234;
46
47 struct tree234_Tag {
48 node234 *root;
49 cmpfn234 cmp;
50 };
51
52 struct node234_Tag {
53 node234 *parent;
54 node234 *kids[4];
55 int counts[4];
56 void *elems[3];
57 };
58
59 /*
60 * Create a 2-3-4 tree.
61 */
62 tree234 *newtree234(cmpfn234 cmp)
63 {
64 tree234 *ret = mknew(tree234);
65 LOG(("created tree %p\n", ret));
66 ret->root = NULL;
67 ret->cmp = cmp;
68 return ret;
69 }
70
71 /*
72 * Free a 2-3-4 tree (not including freeing the elements).
73 */
74 static void freenode234(node234 * n)
75 {
76 if (!n)
77 return;
78 freenode234(n->kids[0]);
79 freenode234(n->kids[1]);
80 freenode234(n->kids[2]);
81 freenode234(n->kids[3]);
82 sfree(n);
83 }
84
85 void freetree234(tree234 * t)
86 {
87 freenode234(t->root);
88 sfree(t);
89 }
90
91 /*
92 * Internal function to count a node.
93 */
94 static int countnode234(node234 * n)
95 {
96 int count = 0;
97 int i;
98 if (!n)
99 return 0;
100 for (i = 0; i < 4; i++)
101 count += n->counts[i];
102 for (i = 0; i < 3; i++)
103 if (n->elems[i])
104 count++;
105 return count;
106 }
107
108 /*
109 * Count the elements in a tree.
110 */
111 int count234(tree234 * t)
112 {
113 if (t->root)
114 return countnode234(t->root);
115 else
116 return 0;
117 }
118
119 /*
120 * Propagate a node overflow up a tree until it stops. Returns 0 or
121 * 1, depending on whether the root had to be split or not.
122 */
123 static int
124 add234_insert(node234 * left, void *e, node234 * right,
125 node234 ** root, node234 * n, int ki)
126 {
127 int lcount, rcount;
128 /*
129 * We need to insert the new left/element/right set in n at
130 * child position ki.
131 */
132 lcount = countnode234(left);
133 rcount = countnode234(right);
134 while (n)
135 {
136 LOG((" at %p: %p/%d \"%s\" %p/%d \"%s\" %p/%d \"%s\" %p/%d\n",
137 n,
138 n->kids[0], n->counts[0], n->elems[0],
139 n->kids[1], n->counts[1], n->elems[1],
140 n->kids[2], n->counts[2], n->elems[2], n->kids[3], n->counts[3]));
141 LOG((" need to insert %p/%d \"%s\" %p/%d at position %d\n", left,
142 lcount, e, right, rcount, ki));
143 if (n->elems[1] == NULL)
144 {
145 /*
146 * Insert in a 2-node; simple.
147 */
148 if (ki == 0)
149 {
150 LOG((" inserting on left of 2-node\n"));
151 n->kids[2] = n->kids[1];
152 n->counts[2] = n->counts[1];
153 n->elems[1] = n->elems[0];
154 n->kids[1] = right;
155 n->counts[1] = rcount;
156 n->elems[0] = e;
157 n->kids[0] = left;
158 n->counts[0] = lcount;
159 } else
160 { /* ki == 1 */
161 LOG((" inserting on right of 2-node\n"));
162 n->kids[2] = right;
163 n->counts[2] = rcount;
164 n->elems[1] = e;
165 n->kids[1] = left;
166 n->counts[1] = lcount;
167 }
168 if (n->kids[0])
169 n->kids[0]->parent = n;
170 if (n->kids[1])
171 n->kids[1]->parent = n;
172 if (n->kids[2])
173 n->kids[2]->parent = n;
174 LOG((" done\n"));
175 break;
176 } else if (n->elems[2] == NULL)
177 {
178 /*
179 * Insert in a 3-node; simple.
180 */
181 if (ki == 0)
182 {
183 LOG((" inserting on left of 3-node\n"));
184 n->kids[3] = n->kids[2];
185 n->counts[3] = n->counts[2];
186 n->elems[2] = n->elems[1];
187 n->kids[2] = n->kids[1];
188 n->counts[2] = n->counts[1];
189 n->elems[1] = n->elems[0];
190 n->kids[1] = right;
191 n->counts[1] = rcount;
192 n->elems[0] = e;
193 n->kids[0] = left;
194 n->counts[0] = lcount;
195 } else if (ki == 1)
196 {
197 LOG((" inserting in middle of 3-node\n"));
198 n->kids[3] = n->kids[2];
199 n->counts[3] = n->counts[2];
200 n->elems[2] = n->elems[1];
201 n->kids[2] = right;
202 n->counts[2] = rcount;
203 n->elems[1] = e;
204 n->kids[1] = left;
205 n->counts[1] = lcount;
206 } else
207 { /* ki == 2 */
208 LOG((" inserting on right of 3-node\n"));
209 n->kids[3] = right;
210 n->counts[3] = rcount;
211 n->elems[2] = e;
212 n->kids[2] = left;
213 n->counts[2] = lcount;
214 }
215 if (n->kids[0])
216 n->kids[0]->parent = n;
217 if (n->kids[1])
218 n->kids[1]->parent = n;
219 if (n->kids[2])
220 n->kids[2]->parent = n;
221 if (n->kids[3])
222 n->kids[3]->parent = n;
223 LOG((" done\n"));
224 break;
225 } else
226 {
227 node234 *m = mknew(node234);
228 m->parent = n->parent;
229 LOG((" splitting a 4-node; created new node %p\n", m));
230 /*
231 * Insert in a 4-node; split into a 2-node and a
232 * 3-node, and move focus up a level.
233 *
234 * I don't think it matters which way round we put the
235 * 2 and the 3. For simplicity, we'll put the 3 first
236 * always.
237 */
238 if (ki == 0)
239 {
240 m->kids[0] = left;
241 m->counts[0] = lcount;
242 m->elems[0] = e;
243 m->kids[1] = right;
244 m->counts[1] = rcount;
245 m->elems[1] = n->elems[0];
246 m->kids[2] = n->kids[1];
247 m->counts[2] = n->counts[1];
248 e = n->elems[1];
249 n->kids[0] = n->kids[2];
250 n->counts[0] = n->counts[2];
251 n->elems[0] = n->elems[2];
252 n->kids[1] = n->kids[3];
253 n->counts[1] = n->counts[3];
254 } else if (ki == 1)
255 {
256 m->kids[0] = n->kids[0];
257 m->counts[0] = n->counts[0];
258 m->elems[0] = n->elems[0];
259 m->kids[1] = left;
260 m->counts[1] = lcount;
261 m->elems[1] = e;
262 m->kids[2] = right;
263 m->counts[2] = rcount;
264 e = n->elems[1];
265 n->kids[0] = n->kids[2];
266 n->counts[0] = n->counts[2];
267 n->elems[0] = n->elems[2];
268 n->kids[1] = n->kids[3];
269 n->counts[1] = n->counts[3];
270 } else if (ki == 2)
271 {
272 m->kids[0] = n->kids[0];
273 m->counts[0] = n->counts[0];
274 m->elems[0] = n->elems[0];
275 m->kids[1] = n->kids[1];
276 m->counts[1] = n->counts[1];
277 m->elems[1] = n->elems[1];
278 m->kids[2] = left;
279 m->counts[2] = lcount;
280 /* e = e; */
281 n->kids[0] = right;
282 n->counts[0] = rcount;
283 n->elems[0] = n->elems[2];
284 n->kids[1] = n->kids[3];
285 n->counts[1] = n->counts[3];
286 } else
287 { /* ki == 3 */
288 m->kids[0] = n->kids[0];
289 m->counts[0] = n->counts[0];
290 m->elems[0] = n->elems[0];
291 m->kids[1] = n->kids[1];
292 m->counts[1] = n->counts[1];
293 m->elems[1] = n->elems[1];
294 m->kids[2] = n->kids[2];
295 m->counts[2] = n->counts[2];
296 n->kids[0] = left;
297 n->counts[0] = lcount;
298 n->elems[0] = e;
299 n->kids[1] = right;
300 n->counts[1] = rcount;
301 e = n->elems[2];
302 }
303 m->kids[3] = n->kids[3] = n->kids[2] = NULL;
304 m->counts[3] = n->counts[3] = n->counts[2] = 0;
305 m->elems[2] = n->elems[2] = n->elems[1] = NULL;
306 if (m->kids[0])
307 m->kids[0]->parent = m;
308 if (m->kids[1])
309 m->kids[1]->parent = m;
310 if (m->kids[2])
311 m->kids[2]->parent = m;
312 if (n->kids[0])
313 n->kids[0]->parent = n;
314 if (n->kids[1])
315 n->kids[1]->parent = n;
316 LOG((" left (%p): %p/%d \"%s\" %p/%d \"%s\" %p/%d\n", m,
317 m->kids[0], m->counts[0], m->elems[0],
318 m->kids[1], m->counts[1], m->elems[1],
319 m->kids[2], m->counts[2]));
320 LOG((" right (%p): %p/%d \"%s\" %p/%d\n", n,
321 n->kids[0], n->counts[0], n->elems[0],
322 n->kids[1], n->counts[1]));
323 left = m;
324 lcount = countnode234(left);
325 right = n;
326 rcount = countnode234(right);
327 }
328 if (n->parent)
329 ki = (n->parent->kids[0] == n ? 0 :
330 n->parent->kids[1] == n ? 1 : n->parent->kids[2] == n ? 2 : 3);
331 n = n->parent;
332 }
333
334 /*
335 * If we've come out of here by `break', n will still be
336 * non-NULL and all we need to do is go back up the tree
337 * updating counts. If we've come here because n is NULL, we
338 * need to create a new root for the tree because the old one
339 * has just split into two. */
340 if (n)
341 {
342 while (n->parent)
343 {
344 int count = countnode234(n);
345 int childnum;
346 childnum = (n->parent->kids[0] == n ? 0 :
347 n->parent->kids[1] == n ? 1 :
348 n->parent->kids[2] == n ? 2 : 3);
349 n->parent->counts[childnum] = count;
350 n = n->parent;
351 }
352 return 0; /* root unchanged */
353 } else
354 {
355 LOG((" root is overloaded, split into two\n"));
356 (*root) = mknew(node234);
357 (*root)->kids[0] = left;
358 (*root)->counts[0] = lcount;
359 (*root)->elems[0] = e;
360 (*root)->kids[1] = right;
361 (*root)->counts[1] = rcount;
362 (*root)->elems[1] = NULL;
363 (*root)->kids[2] = NULL;
364 (*root)->counts[2] = 0;
365 (*root)->elems[2] = NULL;
366 (*root)->kids[3] = NULL;
367 (*root)->counts[3] = 0;
368 (*root)->parent = NULL;
369 if ((*root)->kids[0])
370 (*root)->kids[0]->parent = (*root);
371 if ((*root)->kids[1])
372 (*root)->kids[1]->parent = (*root);
373 LOG((" new root is %p/%d \"%s\" %p/%d\n",
374 (*root)->kids[0], (*root)->counts[0],
375 (*root)->elems[0], (*root)->kids[1], (*root)->counts[1]));
376 return 1; /* root moved */
377 }
378 }
379
380 /*
381 * Add an element e to a 2-3-4 tree t. Returns e on success, or if
382 * an existing element compares equal, returns that.
383 */
384 static void *add234_internal(tree234 * t, void *e, int index)
385 {
386 node234 *n;
387 int ki;
388 void *orig_e = e;
389 int c;
390
391 LOG(("adding element \"%s\" to tree %p\n", e, t));
392 if (t->root == NULL)
393 {
394 t->root = mknew(node234);
395 t->root->elems[1] = t->root->elems[2] = NULL;
396 t->root->kids[0] = t->root->kids[1] = NULL;
397 t->root->kids[2] = t->root->kids[3] = NULL;
398 t->root->counts[0] = t->root->counts[1] = 0;
399 t->root->counts[2] = t->root->counts[3] = 0;
400 t->root->parent = NULL;
401 t->root->elems[0] = e;
402 LOG((" created root %p\n", t->root));
403 return orig_e;
404 }
405
406 n = t->root;
407 while (n)
408 {
409 LOG((" node %p: %p/%d \"%s\" %p/%d \"%s\" %p/%d \"%s\" %p/%d\n",
410 n,
411 n->kids[0], n->counts[0], n->elems[0],
412 n->kids[1], n->counts[1], n->elems[1],
413 n->kids[2], n->counts[2], n->elems[2], n->kids[3], n->counts[3]));
414 if (index >= 0)
415 {
416 if (!n->kids[0])
417 {
418 /*
419 * Leaf node. We want to insert at kid position
420 * equal to the index:
421 *
422 * 0 A 1 B 2 C 3
423 */
424 ki = index;
425 } else
426 {
427 /*
428 * Internal node. We always descend through it (add
429 * always starts at the bottom, never in the
430 * middle).
431 */
432 if (index <= n->counts[0])
433 {
434 ki = 0;
435 } else if (index -= n->counts[0] + 1, index <= n->counts[1])
436 {
437 ki = 1;
438 } else if (index -= n->counts[1] + 1, index <= n->counts[2])
439 {
440 ki = 2;
441 } else if (index -= n->counts[2] + 1, index <= n->counts[3])
442 {
443 ki = 3;
444 } else
445 return NULL; /* error: index out of range */
446 }
447 } else
448 {
449 if ((c = t->cmp(e, n->elems[0])) < 0)
450 ki = 0;
451 else if (c == 0)
452 return n->elems[0]; /* already exists */
453 else if (n->elems[1] == NULL || (c = t->cmp(e, n->elems[1])) < 0)
454 ki = 1;
455 else if (c == 0)
456 return n->elems[1]; /* already exists */
457 else if (n->elems[2] == NULL || (c = t->cmp(e, n->elems[2])) < 0)
458 ki = 2;
459 else if (c == 0)
460 return n->elems[2]; /* already exists */
461 else
462 ki = 3;
463 }
464 LOG((" moving to child %d (%p)\n", ki, n->kids[ki]));
465 if (!n->kids[ki])
466 break;
467 n = n->kids[ki];
468 }
469
470 add234_insert(NULL, e, NULL, &t->root, n, ki);
471
472 return orig_e;
473 }
474
475 void *add234(tree234 * t, void *e)
476 {
477 if (!t->cmp) /* tree is unsorted */
478 return NULL;
479
480 return add234_internal(t, e, -1);
481 }
482
483 void *addpos234(tree234 * t, void *e, int index)
484 {
485 if (index < 0 || /* index out of range */
486 t->cmp) /* tree is sorted */
487 return NULL; /* return failure */
488
489 return add234_internal(t, e, index); /* this checks the upper bound */
490 }
491
492 /*
493 * Look up the element at a given numeric index in a 2-3-4 tree.
494 * Returns NULL if the index is out of range.
495 */
496 void *index234(tree234 * t, int index)
497 {
498 node234 *n;
499
500 if (!t->root)
501 return NULL; /* tree is empty */
502
503 if (index < 0 || index >= countnode234(t->root))
504 return NULL; /* out of range */
505
506 n = t->root;
507
508 while (n)
509 {
510 if (index < n->counts[0])
511 n = n->kids[0];
512 else if (index -= n->counts[0] + 1, index < 0)
513 return n->elems[0];
514 else if (index < n->counts[1])
515 n = n->kids[1];
516 else if (index -= n->counts[1] + 1, index < 0)
517 return n->elems[1];
518 else if (index < n->counts[2])
519 n = n->kids[2];
520 else if (index -= n->counts[2] + 1, index < 0)
521 return n->elems[2];
522 else
523 n = n->kids[3];
524 }
525
526 /* We shouldn't ever get here. I wonder how we did. */
527 return NULL;
528 }
529
530 /*
531 * Find an element e in a sorted 2-3-4 tree t. Returns NULL if not
532 * found. e is always passed as the first argument to cmp, so cmp
533 * can be an asymmetric function if desired. cmp can also be passed
534 * as NULL, in which case the compare function from the tree proper
535 * will be used.
536 */
537 void *findrelpos234(tree234 * t, void *e, cmpfn234 cmp, int relation,
538 int *index)
539 {
540 node234 *n;
541 void *ret;
542 int c;
543 int idx, ecount, kcount, cmpret;
544
545 if (t->root == NULL)
546 return NULL;
547
548 if (cmp == NULL)
549 cmp = t->cmp;
550
551 n = t->root;
552 /*
553 * Attempt to find the element itself.
554 */
555 idx = 0;
556 ecount = -1;
557 /*
558 * Prepare a fake `cmp' result if e is NULL.
559 */
560 cmpret = 0;
561 if (e == NULL)
562 {
563 assert(relation == REL234_LT || relation == REL234_GT);
564 if (relation == REL234_LT)
565 cmpret = +1; /* e is a max: always greater */
566 else if (relation == REL234_GT)
567 cmpret = -1; /* e is a min: always smaller */
568 }
569 while (1)
570 {
571 for (kcount = 0; kcount < 4; kcount++)
572 {
573 if (kcount >= 3 || n->elems[kcount] == NULL ||
574 (c = cmpret ? cmpret : cmp(e, n->elems[kcount])) < 0)
575 {
576 break;
577 }
578 if (n->kids[kcount])
579 idx += n->counts[kcount];
580 if (c == 0)
581 {
582 ecount = kcount;
583 break;
584 }
585 idx++;
586 }
587 if (ecount >= 0)
588 break;
589 if (n->kids[kcount])
590 n = n->kids[kcount];
591 else
592 break;
593 }
594
595 if (ecount >= 0)
596 {
597 /*
598 * We have found the element we're looking for. It's
599 * n->elems[ecount], at tree index idx. If our search
600 * relation is EQ, LE or GE we can now go home.
601 */
602 if (relation != REL234_LT && relation != REL234_GT)
603 {
604 if (index)
605 *index = idx;
606 return n->elems[ecount];
607 }
608
609 /*
610 * Otherwise, we'll do an indexed lookup for the previous
611 * or next element. (It would be perfectly possible to
612 * implement these search types in a non-counted tree by
613 * going back up from where we are, but far more fiddly.)
614 */
615 if (relation == REL234_LT)
616 idx--;
617 else
618 idx++;
619 } else
620 {
621 /*
622 * We've found our way to the bottom of the tree and we
623 * know where we would insert this node if we wanted to:
624 * we'd put it in in place of the (empty) subtree
625 * n->kids[kcount], and it would have index idx
626 *
627 * But the actual element isn't there. So if our search
628 * relation is EQ, we're doomed.
629 */
630 if (relation == REL234_EQ)
631 return NULL;
632
633 /*
634 * Otherwise, we must do an index lookup for index idx-1
635 * (if we're going left - LE or LT) or index idx (if we're
636 * going right - GE or GT).
637 */
638 if (relation == REL234_LT || relation == REL234_LE)
639 {
640 idx--;
641 }
642 }
643
644 /*
645 * We know the index of the element we want; just call index234
646 * to do the rest. This will return NULL if the index is out of
647 * bounds, which is exactly what we want.
648 */
649 ret = index234(t, idx);
650 if (ret && index)
651 *index = idx;
652 return ret;
653 }
654
655 void *find234(tree234 * t, void *e, cmpfn234 cmp)
656 {
657 return findrelpos234(t, e, cmp, REL234_EQ, NULL);
658 }
659
660 void *findrel234(tree234 * t, void *e, cmpfn234 cmp, int relation)
661 {
662 return findrelpos234(t, e, cmp, relation, NULL);
663 }
664
665 void *findpos234(tree234 * t, void *e, cmpfn234 cmp, int *index)
666 {
667 return findrelpos234(t, e, cmp, REL234_EQ, index);
668 }
669
670 /*
671 * Tree transformation used in delete and split: move a subtree
672 * right, from child ki of a node to the next child. Update k and
673 * index so that they still point to the same place in the
674 * transformed tree. Assumes the destination child is not full, and
675 * that the source child does have a subtree to spare. Can cope if
676 * the destination child is undersized.
677 *
678 * . C . . B .
679 * / \ -> / \
680 * [more] a A b B c d D e [more] a A b c C d D e
681 *
682 * . C . . B .
683 * / \ -> / \
684 * [more] a A b B c d [more] a A b c C d
685 */
686 static void trans234_subtree_right(node234 * n, int ki, int *k, int *index)
687 {
688 node234 *src, *dest;
689 int i, srclen, adjust;
690
691 src = n->kids[ki];
692 dest = n->kids[ki + 1];
693
694 LOG((" trans234_subtree_right(%p, %d):\n", n, ki));
695 LOG((" parent %p: %p/%d \"%s\" %p/%d \"%s\" %p/%d \"%s\" %p/%d\n",
696 n,
697 n->kids[0], n->counts[0], n->elems[0],
698 n->kids[1], n->counts[1], n->elems[1],
699 n->kids[2], n->counts[2], n->elems[2], n->kids[3], n->counts[3]));
700 LOG((" src %p: %p/%d \"%s\" %p/%d \"%s\" %p/%d \"%s\" %p/%d\n",
701 src,
702 src->kids[0], src->counts[0], src->elems[0],
703 src->kids[1], src->counts[1], src->elems[1],
704 src->kids[2], src->counts[2], src->elems[2],
705 src->kids[3], src->counts[3]));
706 LOG((" dest %p: %p/%d \"%s\" %p/%d \"%s\" %p/%d \"%s\" %p/%d\n",
707 dest,
708 dest->kids[0], dest->counts[0], dest->elems[0],
709 dest->kids[1], dest->counts[1], dest->elems[1],
710 dest->kids[2], dest->counts[2], dest->elems[2],
711 dest->kids[3], dest->counts[3]));
712 /*
713 * Move over the rest of the destination node to make space.
714 */
715 dest->kids[3] = dest->kids[2];
716 dest->counts[3] = dest->counts[2];
717 dest->elems[2] = dest->elems[1];
718 dest->kids[2] = dest->kids[1];
719 dest->counts[2] = dest->counts[1];
720 dest->elems[1] = dest->elems[0];
721 dest->kids[1] = dest->kids[0];
722 dest->counts[1] = dest->counts[0];
723
724 /* which element to move over */
725 i = (src->elems[2] ? 2 : src->elems[1] ? 1 : 0);
726
727 dest->elems[0] = n->elems[ki];
728 n->elems[ki] = src->elems[i];
729 src->elems[i] = NULL;
730
731 dest->kids[0] = src->kids[i + 1];
732 dest->counts[0] = src->counts[i + 1];
733 src->kids[i + 1] = NULL;
734 src->counts[i + 1] = 0;
735
736 if (dest->kids[0])
737 dest->kids[0]->parent = dest;
738
739 adjust = dest->counts[0] + 1;
740
741 n->counts[ki] -= adjust;
742 n->counts[ki + 1] += adjust;
743
744 srclen = n->counts[ki];
745
746 if (k)
747 {
748 LOG((" before: k,index = %d,%d\n", (*k), (*index)));
749 if ((*k) == ki && (*index) > srclen)
750 {
751 (*index) -= srclen + 1;
752 (*k)++;
753 } else if ((*k) == ki + 1)
754 {
755 (*index) += adjust;
756 }
757 LOG((" after: k,index = %d,%d\n", (*k), (*index)));
758 }
759
760 LOG((" parent %p: %p/%d \"%s\" %p/%d \"%s\" %p/%d \"%s\" %p/%d\n",
761 n,
762 n->kids[0], n->counts[0], n->elems[0],
763 n->kids[1], n->counts[1], n->elems[1],
764 n->kids[2], n->counts[2], n->elems[2], n->kids[3], n->counts[3]));
765 LOG((" src %p: %p/%d \"%s\" %p/%d \"%s\" %p/%d \"%s\" %p/%d\n",
766 src,
767 src->kids[0], src->counts[0], src->elems[0],
768 src->kids[1], src->counts[1], src->elems[1],
769 src->kids[2], src->counts[2], src->elems[2],
770 src->kids[3], src->counts[3]));
771 LOG((" dest %p: %p/%d \"%s\" %p/%d \"%s\" %p/%d \"%s\" %p/%d\n",
772 dest,
773 dest->kids[0], dest->counts[0], dest->elems[0],
774 dest->kids[1], dest->counts[1], dest->elems[1],
775 dest->kids[2], dest->counts[2], dest->elems[2],
776 dest->kids[3], dest->counts[3]));
777 }
778
779 /*
780 * Tree transformation used in delete and split: move a subtree
781 * left, from child ki of a node to the previous child. Update k
782 * and index so that they still point to the same place in the
783 * transformed tree. Assumes the destination child is not full, and
784 * that the source child does have a subtree to spare. Can cope if
785 * the destination child is undersized.
786 *
787 * . B . . C .
788 * / \ -> / \
789 * a A b c C d D e [more] a A b B c d D e [more]
790 *
791 * . A . . B .
792 * / \ -> / \
793 * a b B c C d [more] a A b c C d [more]
794 */
795 static void trans234_subtree_left(node234 * n, int ki, int *k, int *index)
796 {
797 node234 *src, *dest;
798 int i, adjust;
799
800 src = n->kids[ki];
801 dest = n->kids[ki - 1];
802
803 LOG((" trans234_subtree_left(%p, %d):\n", n, ki));
804 LOG((" parent %p: %p/%d \"%s\" %p/%d \"%s\" %p/%d \"%s\" %p/%d\n",
805 n,
806 n->kids[0], n->counts[0], n->elems[0],
807 n->kids[1], n->counts[1], n->elems[1],
808 n->kids[2], n->counts[2], n->elems[2], n->kids[3], n->counts[3]));
809 LOG((" dest %p: %p/%d \"%s\" %p/%d \"%s\" %p/%d \"%s\" %p/%d\n",
810 dest,
811 dest->kids[0], dest->counts[0], dest->elems[0],
812 dest->kids[1], dest->counts[1], dest->elems[1],
813 dest->kids[2], dest->counts[2], dest->elems[2],
814 dest->kids[3], dest->counts[3]));
815 LOG((" src %p: %p/%d \"%s\" %p/%d \"%s\" %p/%d \"%s\" %p/%d\n",
816 src,
817 src->kids[0], src->counts[0], src->elems[0],
818 src->kids[1], src->counts[1], src->elems[1],
819 src->kids[2], src->counts[2], src->elems[2],
820 src->kids[3], src->counts[3]));
821
822 /* where in dest to put it */
823 i = (dest->elems[1] ? 2 : dest->elems[0] ? 1 : 0);
824 dest->elems[i] = n->elems[ki - 1];
825 n->elems[ki - 1] = src->elems[0];
826
827 dest->kids[i + 1] = src->kids[0];
828 dest->counts[i + 1] = src->counts[0];
829
830 if (dest->kids[i + 1])
831 dest->kids[i + 1]->parent = dest;
832
833 /*
834 * Move over the rest of the source node.
835 */
836 src->kids[0] = src->kids[1];
837 src->counts[0] = src->counts[1];
838 src->elems[0] = src->elems[1];
839 src->kids[1] = src->kids[2];
840 src->counts[1] = src->counts[2];
841 src->elems[1] = src->elems[2];
842 src->kids[2] = src->kids[3];
843 src->counts[2] = src->counts[3];
844 src->elems[2] = NULL;
845 src->kids[3] = NULL;
846 src->counts[3] = 0;
847
848 adjust = dest->counts[i + 1] + 1;
849
850 n->counts[ki] -= adjust;
851 n->counts[ki - 1] += adjust;
852
853 if (k)
854 {
855 LOG((" before: k,index = %d,%d\n", (*k), (*index)));
856 if ((*k) == ki)
857 {
858 (*index) -= adjust;
859 if ((*index) < 0)
860 {
861 (*index) += n->counts[ki - 1] + 1;
862 (*k)--;
863 }
864 }
865 LOG((" after: k,index = %d,%d\n", (*k), (*index)));
866 }
867
868 LOG((" parent %p: %p/%d \"%s\" %p/%d \"%s\" %p/%d \"%s\" %p/%d\n",
869 n,
870 n->kids[0], n->counts[0], n->elems[0],
871 n->kids[1], n->counts[1], n->elems[1],
872 n->kids[2], n->counts[2], n->elems[2], n->kids[3], n->counts[3]));
873 LOG((" dest %p: %p/%d \"%s\" %p/%d \"%s\" %p/%d \"%s\" %p/%d\n",
874 dest,
875 dest->kids[0], dest->counts[0], dest->elems[0],
876 dest->kids[1], dest->counts[1], dest->elems[1],
877 dest->kids[2], dest->counts[2], dest->elems[2],
878 dest->kids[3], dest->counts[3]));
879 LOG((" src %p: %p/%d \"%s\" %p/%d \"%s\" %p/%d \"%s\" %p/%d\n",
880 src,
881 src->kids[0], src->counts[0], src->elems[0],
882 src->kids[1], src->counts[1], src->elems[1],
883 src->kids[2], src->counts[2], src->elems[2],
884 src->kids[3], src->counts[3]));
885 }
886
887 /*
888 * Tree transformation used in delete and split: merge child nodes
889 * ki and ki+1 of a node. Update k and index so that they still
890 * point to the same place in the transformed tree. Assumes both
891 * children _are_ sufficiently small.
892 *
893 * . B . .
894 * / \ -> |
895 * a A b c C d a A b B c C d
896 *
897 * This routine can also cope with either child being undersized:
898 *
899 * . A . .
900 * / \ -> |
901 * a b B c a A b B c
902 *
903 * . A . .
904 * / \ -> |
905 * a b B c C d a A b B c C d
906 */
907 static void trans234_subtree_merge(node234 * n, int ki, int *k, int *index)
908 {
909 node234 *left, *right;
910 int i, leftlen, rightlen, lsize, rsize;
911
912 left = n->kids[ki];
913 leftlen = n->counts[ki];
914 right = n->kids[ki + 1];
915 rightlen = n->counts[ki + 1];
916
917 LOG((" trans234_subtree_merge(%p, %d):\n", n, ki));
918 LOG((" parent %p: %p/%d \"%s\" %p/%d \"%s\" %p/%d \"%s\" %p/%d\n",
919 n,
920 n->kids[0], n->counts[0], n->elems[0],
921 n->kids[1], n->counts[1], n->elems[1],
922 n->kids[2], n->counts[2], n->elems[2], n->kids[3], n->counts[3]));
923 LOG((" left %p: %p/%d \"%s\" %p/%d \"%s\" %p/%d \"%s\" %p/%d\n",
924 left,
925 left->kids[0], left->counts[0], left->elems[0],
926 left->kids[1], left->counts[1], left->elems[1],
927 left->kids[2], left->counts[2], left->elems[2],
928 left->kids[3], left->counts[3]));
929 LOG((" right %p: %p/%d \"%s\" %p/%d \"%s\" %p/%d \"%s\" %p/%d\n",
930 right,
931 right->kids[0], right->counts[0], right->elems[0],
932 right->kids[1], right->counts[1], right->elems[1],
933 right->kids[2], right->counts[2], right->elems[2],
934 right->kids[3], right->counts[3]));
935
936 assert(!left->elems[2] && !right->elems[2]); /* neither is large! */
937 lsize = (left->elems[1] ? 2 : left->elems[0] ? 1 : 0);
938 rsize = (right->elems[1] ? 2 : right->elems[0] ? 1 : 0);
939
940 left->elems[lsize] = n->elems[ki];
941
942 for (i = 0; i < rsize + 1; i++)
943 {
944 left->kids[lsize + 1 + i] = right->kids[i];
945 left->counts[lsize + 1 + i] = right->counts[i];
946 if (left->kids[lsize + 1 + i])
947 left->kids[lsize + 1 + i]->parent = left;
948 if (i < rsize)
949 left->elems[lsize + 1 + i] = right->elems[i];
950 }
951
952 n->counts[ki] += rightlen + 1;
953
954 sfree(right);
955
956 /*
957 * Move the rest of n up by one.
958 */
959 for (i = ki + 1; i < 3; i++)
960 {
961 n->kids[i] = n->kids[i + 1];
962 n->counts[i] = n->counts[i + 1];
963 }
964 for (i = ki; i < 2; i++)
965 {
966 n->elems[i] = n->elems[i + 1];
967 }
968 n->kids[3] = NULL;
969 n->counts[3] = 0;
970 n->elems[2] = NULL;
971
972 if (k)
973 {
974 LOG((" before: k,index = %d,%d\n", (*k), (*index)));
975 if ((*k) == ki + 1)
976 {
977 (*k)--;
978 (*index) += leftlen + 1;
979 } else if ((*k) > ki + 1)
980 {
981 (*k)--;
982 }
983 LOG((" after: k,index = %d,%d\n", (*k), (*index)));
984 }
985
986 LOG((" parent %p: %p/%d \"%s\" %p/%d \"%s\" %p/%d \"%s\" %p/%d\n",
987 n,
988 n->kids[0], n->counts[0], n->elems[0],
989 n->kids[1], n->counts[1], n->elems[1],
990 n->kids[2], n->counts[2], n->elems[2], n->kids[3], n->counts[3]));
991 LOG((" merged %p: %p/%d \"%s\" %p/%d \"%s\" %p/%d \"%s\" %p/%d\n",
992 left,
993 left->kids[0], left->counts[0], left->elems[0],
994 left->kids[1], left->counts[1], left->elems[1],
995 left->kids[2], left->counts[2], left->elems[2],
996 left->kids[3], left->counts[3]));
997
998 }
999
1000 /*
1001 * Delete an element e in a 2-3-4 tree. Does not free the element,
1002 * merely removes all links to it from the tree nodes.
1003 */
1004 static void *delpos234_internal(tree234 * t, int index)
1005 {
1006 node234 *n;
1007 void *retval;
1008 int ki, i;
1009
1010 retval = NULL;
1011
1012 n = t->root; /* by assumption this is non-NULL */
1013 LOG(("deleting item %d from tree %p\n", index, t));
1014 while (1)
1015 {
1016 node234 *sub;
1017
1018 LOG((" node %p: %p/%d \"%s\" %p/%d \"%s\" %p/%d \"%s\" %p/%d index=%d\n", n, n->kids[0], n->counts[0], n->elems[0], n->kids[1], n->counts[1], n->elems[1], n->kids[2], n->counts[2], n->elems[2], n->kids[3], n->counts[3], index));
1019 if (index <= n->counts[0])
1020 {
1021 ki = 0;
1022 } else if (index -= n->counts[0] + 1, index <= n->counts[1])
1023 {
1024 ki = 1;
1025 } else if (index -= n->counts[1] + 1, index <= n->counts[2])
1026 {
1027 ki = 2;
1028 } else if (index -= n->counts[2] + 1, index <= n->counts[3])
1029 {
1030 ki = 3;
1031 } else
1032 {
1033 assert(0); /* can't happen */
1034 }
1035
1036 if (!n->kids[0])
1037 break; /* n is a leaf node; we're here! */
1038
1039 /*
1040 * Check to see if we've found our target element. If so,
1041 * we must choose a new target (we'll use the old target's
1042 * successor, which will be in a leaf), move it into the
1043 * place of the old one, continue down to the leaf and
1044 * delete the old copy of the new target.
1045 */
1046 if (index == n->counts[ki])
1047 {
1048 node234 *m;
1049 LOG((" found element in internal node, index %d\n", ki));
1050 assert(n->elems[ki]); /* must be a kid _before_ an element */
1051 ki++;
1052 index = 0;
1053 for (m = n->kids[ki]; m->kids[0]; m = m->kids[0])
1054 continue;
1055 LOG((" replacing with element \"%s\" from leaf node %p\n",
1056 m->elems[0], m));
1057 retval = n->elems[ki - 1];
1058 n->elems[ki - 1] = m->elems[0];
1059 }
1060
1061 /*
1062 * Recurse down to subtree ki. If it has only one element,
1063 * we have to do some transformation to start with.
1064 */
1065 LOG((" moving to subtree %d\n", ki));
1066 sub = n->kids[ki];
1067 if (!sub->elems[1])
1068 {
1069 LOG((" subtree has only one element!\n"));
1070 if (ki > 0 && n->kids[ki - 1]->elems[1])
1071 {
1072 /*
1073 * Child ki has only one element, but child
1074 * ki-1 has two or more. So we need to move a
1075 * subtree from ki-1 to ki.
1076 */
1077 trans234_subtree_right(n, ki - 1, &ki, &index);
1078 } else if (ki < 3 && n->kids[ki + 1] && n->kids[ki + 1]->elems[1])
1079 {
1080 /*
1081 * Child ki has only one element, but ki+1 has
1082 * two or more. Move a subtree from ki+1 to ki.
1083 */
1084 trans234_subtree_left(n, ki + 1, &ki, &index);
1085 } else
1086 {
1087 /*
1088 * ki is small with only small neighbours. Pick a
1089 * neighbour and merge with it.
1090 */
1091 trans234_subtree_merge(n, ki > 0 ? ki - 1 : ki, &ki, &index);
1092 sub = n->kids[ki];
1093
1094 if (!n->elems[0])
1095 {
1096 /*
1097 * The root is empty and needs to be
1098 * removed.
1099 */
1100 LOG((" shifting root!\n"));
1101 t->root = sub;
1102 sub->parent = NULL;
1103 sfree(n);
1104 n = NULL;
1105 }
1106 }
1107 }
1108
1109 if (n)
1110 n->counts[ki]--;
1111 n = sub;
1112 }
1113
1114 /*
1115 * Now n is a leaf node, and ki marks the element number we
1116 * want to delete. We've already arranged for the leaf to be
1117 * bigger than minimum size, so let's just go to it.
1118 */
1119 assert(!n->kids[0]);
1120 if (!retval)
1121 retval = n->elems[ki];
1122
1123 for (i = ki; i < 2 && n->elems[i + 1]; i++)
1124 n->elems[i] = n->elems[i + 1];
1125 n->elems[i] = NULL;
1126
1127 /*
1128 * It's just possible that we have reduced the leaf to zero
1129 * size. This can only happen if it was the root - so destroy
1130 * it and make the tree empty.
1131 */
1132 if (!n->elems[0])
1133 {
1134 LOG((" removed last element in tree, destroying empty root\n"));
1135 assert(n == t->root);
1136 sfree(n);
1137 t->root = NULL;
1138 }
1139
1140 return retval; /* finished! */
1141 }
1142
1143 void *delpos234(tree234 * t, int index)
1144 {
1145 if (index < 0 || index >= countnode234(t->root))
1146 return NULL;
1147 return delpos234_internal(t, index);
1148 }
1149
1150 void *del234(tree234 * t, void *e)
1151 {
1152 int index;
1153 if (!findrelpos234(t, e, NULL, REL234_EQ, &index))
1154 return NULL; /* it wasn't in there anyway */
1155 return delpos234_internal(t, index); /* it's there; delete it. */
1156 }
1157
1158 /*
1159 * Join two subtrees together with a separator element between
1160 * them, given their relative height.
1161 *
1162 * (Height<0 means the left tree is shorter, >0 means the right
1163 * tree is shorter, =0 means (duh) they're equal.)
1164 *
1165 * It is assumed that any checks needed on the ordering criterion
1166 * have _already_ been done.
1167 *
1168 * The value returned in `height' is 0 or 1 depending on whether the
1169 * resulting tree is the same height as the original larger one, or
1170 * one higher.
1171 */
1172 static node234 *join234_internal(node234 * left, void *sep,
1173 node234 * right, int *height)
1174 {
1175 node234 *root, *node;
1176 int relht = *height;
1177 int ki;
1178
1179 LOG((" join: joining %p \"%s\" %p, relative height is %d\n",
1180 left, sep, right, relht));
1181 if (relht == 0)
1182 {
1183 /*
1184 * The trees are the same height. Create a new one-element
1185 * root containing the separator and pointers to the two
1186 * nodes.
1187 */
1188 node234 *newroot;
1189 newroot = mknew(node234);
1190 newroot->kids[0] = left;
1191 newroot->counts[0] = countnode234(left);
1192 newroot->elems[0] = sep;
1193 newroot->kids[1] = right;
1194 newroot->counts[1] = countnode234(right);
1195 newroot->elems[1] = NULL;
1196 newroot->kids[2] = NULL;
1197 newroot->counts[2] = 0;
1198 newroot->elems[2] = NULL;
1199 newroot->kids[3] = NULL;
1200 newroot->counts[3] = 0;
1201 newroot->parent = NULL;
1202 if (left)
1203 left->parent = newroot;
1204 if (right)
1205 right->parent = newroot;
1206 *height = 1;
1207 LOG((" join: same height, brand new root\n"));
1208 return newroot;
1209 }
1210
1211 /*
1212 * This now works like the addition algorithm on the larger
1213 * tree. We're replacing a single kid pointer with two kid
1214 * pointers separated by an element; if that causes the node to
1215 * overload, we split it in two, move a separator element up to
1216 * the next node, and repeat.
1217 */
1218 if (relht < 0)
1219 {
1220 /*
1221 * Left tree is shorter. Search down the right tree to find
1222 * the pointer we're inserting at.
1223 */
1224 node = root = right;
1225 while (++relht < 0)
1226 {
1227 node = node->kids[0];
1228 }
1229 ki = 0;
1230 right = node->kids[ki];
1231 } else
1232 {
1233 /*
1234 * Right tree is shorter; search down the left to find the
1235 * pointer we're inserting at.
1236 */
1237 node = root = left;
1238 while (--relht > 0)
1239 {
1240 if (node->elems[2])
1241 node = node->kids[3];
1242 else if (node->elems[1])
1243 node = node->kids[2];
1244 else
1245 node = node->kids[1];
1246 }
1247 if (node->elems[2])
1248 ki = 3;
1249 else if (node->elems[1])
1250 ki = 2;
1251 else
1252 ki = 1;
1253 left = node->kids[ki];
1254 }
1255
1256 /*
1257 * Now proceed as for addition.
1258 */
1259 *height = add234_insert(left, sep, right, &root, node, ki);
1260
1261 return root;
1262 }
1263 static int height234(tree234 * t)
1264 {
1265 int level = 0;
1266 node234 *n = t->root;
1267 while (n)
1268 {
1269 level++;
1270 n = n->kids[0];
1271 }
1272 return level;
1273 }
1274
1275 tree234 *join234(tree234 * t1, tree234 * t2)
1276 {
1277 int size2 = countnode234(t2->root);
1278 if (size2 > 0)
1279 {
1280 void *element;
1281 int relht;
1282
1283 if (t1->cmp)
1284 {
1285 element = index234(t2, 0);
1286 element = findrelpos234(t1, element, NULL, REL234_GE, NULL);
1287 if (element)
1288 return NULL;
1289 }
1290
1291 element = delpos234(t2, 0);
1292 relht = height234(t1) - height234(t2);
1293 t1->root = join234_internal(t1->root, element, t2->root, &relht);
1294 t2->root = NULL;
1295 }
1296 return t1;
1297 }
1298
1299 tree234 *join234r(tree234 * t1, tree234 * t2)
1300 {
1301 int size1 = countnode234(t1->root);
1302 if (size1 > 0)
1303 {
1304 void *element;
1305 int relht;
1306
1307 if (t2->cmp)
1308 {
1309 element = index234(t1, size1 - 1);
1310 element = findrelpos234(t2, element, NULL, REL234_LE, NULL);
1311 if (element)
1312 return NULL;
1313 }
1314
1315 element = delpos234(t1, size1 - 1);
1316 relht = height234(t1) - height234(t2);
1317 t2->root = join234_internal(t1->root, element, t2->root, &relht);
1318 t1->root = NULL;
1319 }
1320 return t2;
1321 }
1322
1323 /*
1324 * Split out the first <index> elements in a tree and return a
1325 * pointer to the root node. Leave the root node of the remainder
1326 * in t.
1327 */
1328 static node234 *split234_internal(tree234 * t, int index)
1329 {
1330 node234 *halves[2], *n, *sib, *sub;
1331 node234 *lparent, *rparent;
1332 int ki, pki=0, i, half, lcount, rcount;
1333
1334 n = t->root;
1335 LOG(("splitting tree %p at point %d\n", t, index));
1336
1337 /*
1338 * Easy special cases. After this we have also dealt completely
1339 * with the empty-tree case and we can assume the root exists.
1340 */
1341 if (index == 0) /* return nothing */
1342 return NULL;
1343 if (index == countnode234(t->root))
1344 { /* return the whole tree */
1345 node234 *ret = t->root;
1346 t->root = NULL;
1347 return ret;
1348 }
1349
1350 /*
1351 * Search down the tree to find the split point.
1352 */
1353 lparent = rparent = NULL;
1354 while (n)
1355 {
1356 LOG((" node %p: %p/%d \"%s\" %p/%d \"%s\" %p/%d \"%s\" %p/%d index=%d\n", n, n->kids[0], n->counts[0], n->elems[0], n->kids[1], n->counts[1], n->elems[1], n->kids[2], n->counts[2], n->elems[2], n->kids[3], n->counts[3], index));
1357 lcount = index;
1358 rcount = countnode234(n) - lcount;
1359 if (index <= n->counts[0])
1360 {
1361 ki = 0;
1362 } else if (index -= n->counts[0] + 1, index <= n->counts[1])
1363 {
1364 ki = 1;
1365 } else if (index -= n->counts[1] + 1, index <= n->counts[2])
1366 {
1367 ki = 2;
1368 } else
1369 {
1370 index -= n->counts[2] + 1;
1371 ki = 3;
1372 }
1373
1374 LOG((" splitting at subtree %d\n", ki));
1375 sub = n->kids[ki];
1376
1377 LOG((" splitting at child index %d\n", ki));
1378
1379 /*
1380 * Split the node, put halves[0] on the right of the left
1381 * one and halves[1] on the left of the right one, put the
1382 * new node pointers in halves[0] and halves[1], and go up
1383 * a level.
1384 */
1385 sib = mknew(node234);
1386 for (i = 0; i < 3; i++)
1387 {
1388 if (i + ki < 3 && n->elems[i + ki])
1389 {
1390 sib->elems[i] = n->elems[i + ki];
1391 sib->kids[i + 1] = n->kids[i + ki + 1];
1392 if (sib->kids[i + 1])
1393 sib->kids[i + 1]->parent = sib;
1394 sib->counts[i + 1] = n->counts[i + ki + 1];
1395 n->elems[i + ki] = NULL;
1396 n->kids[i + ki + 1] = NULL;
1397 n->counts[i + ki + 1] = 0;
1398 } else
1399 {
1400 sib->elems[i] = NULL;
1401 sib->kids[i + 1] = NULL;
1402 sib->counts[i + 1] = 0;
1403 }
1404 }
1405 if (lparent)
1406 {
1407 lparent->kids[pki] = n;
1408 lparent->counts[pki] = lcount;
1409 n->parent = lparent;
1410 rparent->kids[0] = sib;
1411 rparent->counts[0] = rcount;
1412 sib->parent = rparent;
1413 } else
1414 {
1415 halves[0] = n;
1416 n->parent = NULL;
1417 halves[1] = sib;
1418 sib->parent = NULL;
1419 }
1420 lparent = n;
1421 rparent = sib;
1422 pki = ki;
1423 LOG((" left node %p: %p/%d \"%s\" %p/%d \"%s\" %p/%d \"%s\" %p/%d\n",
1424 n, n->kids[0], n->counts[0], n->elems[0], n->kids[1],
1425 n->counts[1], n->elems[1], n->kids[2], n->counts[2], n->elems[2],
1426 n->kids[3], n->counts[3]));
1427 LOG((" right node %p: %p/%d \"%s\" %p/%d \"%s\" %p/%d \"%s\" %p/%d\n",
1428 sib, sib->kids[0], sib->counts[0], sib->elems[0], sib->kids[1],
1429 sib->counts[1], sib->elems[1], sib->kids[2], sib->counts[2],
1430 sib->elems[2], sib->kids[3], sib->counts[3]));
1431
1432 n = sub;
1433 }
1434
1435 /*
1436 * We've come off the bottom here, so we've successfully split
1437 * the tree into two equally high subtrees. The only problem is
1438 * that some of the nodes down the fault line will be smaller
1439 * than the minimum permitted size. (Since this is a 2-3-4
1440 * tree, that means they'll be zero-element one-child nodes.)
1441 */
1442 LOG((" fell off bottom, lroot is %p, rroot is %p\n",
1443 halves[0], halves[1]));
1444 lparent->counts[pki] = rparent->counts[0] = 0;
1445 lparent->kids[pki] = rparent->kids[0] = NULL;
1446
1447 /*
1448 * So now we go back down the tree from each of the two roots,
1449 * fixing up undersize nodes.
1450 */
1451 for (half = 0; half < 2; half++)
1452 {
1453 /*
1454 * Remove the root if it's undersize (it will contain only
1455 * one child pointer, so just throw it away and replace it
1456 * with its child). This might happen several times.
1457 */
1458 while (halves[half] && !halves[half]->elems[0])
1459 {
1460 LOG((" root %p is undersize, throwing away\n", halves[half]));
1461 halves[half] = halves[half]->kids[0];
1462 sfree(halves[half]->parent);
1463 halves[half]->parent = NULL;
1464 LOG((" new root is %p\n", halves[half]));
1465 }
1466
1467 n = halves[half];
1468 while (n)
1469 {
1470 void (*toward) (node234 * n, int ki, int *k, int *index);
1471 int ni, merge;
1472
1473 /*
1474 * Now we have a potentially undersize node on the
1475 * right (if half==0) or left (if half==1). Sort it
1476 * out, by merging with a neighbour or by transferring
1477 * subtrees over. At this time we must also ensure that
1478 * nodes are bigger than minimum, in case we need an
1479 * element to merge two nodes below.
1480 */
1481 LOG((" node %p: %p/%d \"%s\" %p/%d \"%s\" %p/%d \"%s\" %p/%d\n", n,
1482 n->kids[0], n->counts[0], n->elems[0], n->kids[1], n->counts[1],
1483 n->elems[1], n->kids[2], n->counts[2], n->elems[2], n->kids[3],
1484 n->counts[3]));
1485 if (half == 1)
1486 {
1487 ki = 0; /* the kid we're interested in */
1488 ni = 1; /* the neighbour */
1489 merge = 0; /* for merge: leftmost of the two */
1490 toward = trans234_subtree_left;
1491 } else
1492 {
1493 ki = (n->kids[3] ? 3 : n->kids[2] ? 2 : 1);
1494 ni = ki - 1;
1495 merge = ni;
1496 toward = trans234_subtree_right;
1497 }
1498
1499 sub = n->kids[ki];
1500 if (sub && !sub->elems[1])
1501 {
1502 /*
1503 * This node is undersized or minimum-size. If we
1504 * can merge it with its neighbour, we do so;
1505 * otherwise we must be able to transfer subtrees
1506 * over to it until it is greater than minimum
1507 * size.
1508 */
1509 int undersized = (!sub->elems[0]);
1510 LOG((" child %d is %ssize\n", ki,
1511 undersized ? "under" : "minimum-"));
1512 LOG((" neighbour is %s\n",
1513 n->kids[ni]->elems[2] ? "large" :
1514 n->kids[ni]->elems[1] ? "medium" : "small"));
1515 if (!n->kids[ni]->elems[1] ||
1516 (undersized && !n->kids[ni]->elems[2]))
1517 {
1518 /*
1519 * Neighbour is small, or possibly neighbour is
1520 * medium and we are undersize.
1521 */
1522 trans234_subtree_merge(n, merge, NULL, NULL);
1523 sub = n->kids[merge];
1524 if (!n->elems[0])
1525 {
1526 /*
1527 * n is empty, and hence must have been the
1528 * root and needs to be removed.
1529 */
1530 assert(!n->parent);
1531 LOG((" shifting root!\n"));
1532 halves[half] = sub;
1533 halves[half]->parent = NULL;
1534 sfree(n);
1535 }
1536 } else
1537 {
1538 /* Neighbour is big enough to move trees over. */
1539 toward(n, ni, NULL, NULL);
1540 if (undersized)
1541 toward(n, ni, NULL, NULL);
1542 }
1543 }
1544 n = sub;
1545 }
1546 }
1547
1548 t->root = halves[1];
1549 return halves[0];
1550 }
1551
1552 tree234 *splitpos234(tree234 * t, int index, int before)
1553 {
1554 tree234 *ret;
1555 node234 *n;
1556 int count;
1557
1558 count = countnode234(t->root);
1559 if (index < 0 || index > count)
1560 return NULL; /* error */
1561 ret = newtree234(t->cmp);
1562 n = split234_internal(t, index);
1563 if (before)
1564 {
1565 /* We want to return the ones before the index. */
1566 ret->root = n;
1567 } else
1568 {
1569 /*
1570 * We want to keep the ones before the index and return the
1571 * ones after.
1572 */
1573 ret->root = t->root;
1574 t->root = n;
1575 }
1576 return ret;
1577 }
1578
1579 tree234 *split234(tree234 * t, void *e, cmpfn234 cmp, int rel)
1580 {
1581 int before;
1582 int index;
1583
1584 assert(rel != REL234_EQ);
1585
1586 if (rel == REL234_GT || rel == REL234_GE)
1587 {
1588 before = 1;
1589 rel = (rel == REL234_GT ? REL234_LE : REL234_LT);
1590 } else
1591 {
1592 before = 0;
1593 }
1594 if (!findrelpos234(t, e, cmp, rel, &index))
1595 index = 0;
1596
1597 return splitpos234(t, index + 1, before);
1598 }
1599
1600 static node234 *copynode234(node234 * n, copyfn234 copyfn,
1601 void *copyfnstate)
1602 {
1603 int i;
1604 node234 *n2 = mknew(node234);
1605
1606 for (i = 0; i < 3; i++)
1607 {
1608 if (n->elems[i] && copyfn)
1609 n2->elems[i] = copyfn(copyfnstate, n->elems[i]);
1610 else
1611 n2->elems[i] = n->elems[i];
1612 }
1613
1614 for (i = 0; i < 4; i++)
1615 {
1616 if (n->kids[i])
1617 {
1618 n2->kids[i] = copynode234(n->kids[i], copyfn, copyfnstate);
1619 n2->kids[i]->parent = n2;
1620 } else
1621 {
1622 n2->kids[i] = NULL;
1623 }
1624 n2->counts[i] = n->counts[i];
1625 }
1626
1627 return n2;
1628 }
1629
1630 tree234 *copytree234(tree234 * t, copyfn234 copyfn, void *copyfnstate)
1631 {
1632 tree234 *t2;
1633
1634 t2 = newtree234(t->cmp);
1635 t2->root = copynode234(t->root, copyfn, copyfnstate);
1636 t2->root->parent = NULL;
1637
1638 return t2;
1639 }
1640
1641 #ifdef TEST
1642
1643 /*
1644 * Test code for the 2-3-4 tree. This code maintains an alternative
1645 * representation of the data in the tree, in an array (using the
1646 * obvious and slow insert and delete functions). After each tree
1647 * operation, the verify() function is called, which ensures all
1648 * the tree properties are preserved:
1649 * - node->child->parent always equals node
1650 * - tree->root->parent always equals NULL
1651 * - number of kids == 0 or number of elements + 1;
1652 * - tree has the same depth everywhere
1653 * - every node has at least one element
1654 * - subtree element counts are accurate
1655 * - any NULL kid pointer is accompanied by a zero count
1656 * - in a sorted tree: ordering property between elements of a
1657 * node and elements of its children is preserved
1658 * and also ensures the list represented by the tree is the same
1659 * list it should be. (This last check also doubly verifies the
1660 * ordering properties, because the `same list it should be' is by
1661 * definition correctly ordered. It also ensures all nodes are
1662 * distinct, because the enum functions would get caught in a loop
1663 * if not.)
1664 */
1665
1666 #include <stdarg.h>
1667
1668 #define srealloc realloc
1669
1670 /*
1671 * Error reporting function.
1672 */
1673 void error(char *fmt, ...)
1674 {
1675 va_list ap;
1676 printf("ERROR: ");
1677 va_start(ap, fmt);
1678 vfprintf(stdout, fmt, ap);
1679 va_end(ap);
1680 printf("\n");
1681 }
1682
1683 /* The array representation of the data. */
1684 void **array;
1685 int arraylen, arraysize;
1686 cmpfn234 cmp;
1687
1688 /* The tree representation of the same data. */
1689 tree234 *tree;
1690
1691 /*
1692 * Routines to provide a diagnostic printout of a tree. Currently
1693 * relies on every element in the tree being a one-character string
1694 * :-)
1695 */
1696 typedef struct {
1697 char **levels;
1698 } dispctx;
1699
1700 int dispnode(node234 * n, int level, dispctx * ctx)
1701 {
1702 if (level == 0)
1703 {
1704 int xpos = strlen(ctx->levels[0]);
1705 int len;
1706
1707 if (n->elems[2])
1708 len = sprintf(ctx->levels[0] + xpos, " %s%s%s",
1709 n->elems[0], n->elems[1], n->elems[2]);
1710 else if (n->elems[1])
1711 len = sprintf(ctx->levels[0] + xpos, " %s%s",
1712 n->elems[0], n->elems[1]);
1713 else
1714 len = sprintf(ctx->levels[0] + xpos, " %s", n->elems[0]);
1715 return xpos + 1 + (len - 1) / 2;
1716 } else
1717 {
1718 int xpos[4], nkids;
1719 int nodelen, mypos, myleft, x, i;
1720
1721 xpos[0] = dispnode(n->kids[0], level - 3, ctx);
1722 xpos[1] = dispnode(n->kids[1], level - 3, ctx);
1723 nkids = 2;
1724 if (n->kids[2])
1725 {
1726 xpos[2] = dispnode(n->kids[2], level - 3, ctx);
1727 nkids = 3;
1728 }
1729 if (n->kids[3])
1730 {
1731 xpos[3] = dispnode(n->kids[3], level - 3, ctx);
1732 nkids = 4;
1733 }
1734
1735 if (nkids == 4)
1736 mypos = (xpos[1] + xpos[2]) / 2;
1737 else if (nkids == 3)
1738 mypos = xpos[1];
1739 else
1740 mypos = (xpos[0] + xpos[1]) / 2;
1741 nodelen = nkids * 2 - 1;
1742 myleft = mypos - ((nodelen - 1) / 2);
1743 assert(myleft >= xpos[0]);
1744 assert(myleft + nodelen - 1 <= xpos[nkids - 1]);
1745
1746 x = strlen(ctx->levels[level]);
1747 while (x <= xpos[0] && x < myleft)
1748 ctx->levels[level][x++] = ' ';
1749 while (x < myleft)
1750 ctx->levels[level][x++] = '_';
1751 if (nkids == 4)
1752 x += sprintf(ctx->levels[level] + x, ".%s.%s.%s.",
1753 n->elems[0], n->elems[1], n->elems[2]);
1754 else if (nkids == 3)
1755 x += sprintf(ctx->levels[level] + x, ".%s.%s.",
1756 n->elems[0], n->elems[1]);
1757 else
1758 x += sprintf(ctx->levels[level] + x, ".%s.", n->elems[0]);
1759 while (x < xpos[nkids - 1])
1760 ctx->levels[level][x++] = '_';
1761 ctx->levels[level][x] = '\0';
1762
1763 x = strlen(ctx->levels[level - 1]);
1764 for (i = 0; i < nkids; i++)
1765 {
1766 int rpos, pos;
1767 rpos = xpos[i];
1768 if (i > 0 && i < nkids - 1)
1769 pos = myleft + 2 * i;
1770 else
1771 pos = rpos;
1772 if (rpos < pos)
1773 rpos++;
1774 while (x < pos && x < rpos)
1775 ctx->levels[level - 1][x++] = ' ';
1776 if (x == pos)
1777 ctx->levels[level - 1][x++] = '|';
1778 while (x < pos || x < rpos)
1779 ctx->levels[level - 1][x++] = '_';
1780 if (x == pos)
1781 ctx->levels[level - 1][x++] = '|';
1782 }
1783 ctx->levels[level - 1][x] = '\0';
1784
1785 x = strlen(ctx->levels[level - 2]);
1786 for (i = 0; i < nkids; i++)
1787 {
1788 int rpos = xpos[i];
1789
1790 while (x < rpos)
1791 ctx->levels[level - 2][x++] = ' ';
1792 ctx->levels[level - 2][x++] = '|';
1793 }
1794 ctx->levels[level - 2][x] = '\0';
1795
1796 return mypos;
1797 }
1798 }
1799
1800 void disptree(tree234 * t)
1801 {
1802 dispctx ctx;
1803 char *leveldata;
1804 int width = count234(t);
1805 int ht = height234(t) * 3 - 2;
1806 int i;
1807
1808 if (!t->root)
1809 {
1810 printf("[empty tree]\n");
1811 }
1812
1813 leveldata = smalloc(ht * (width + 2));
1814 ctx.levels = smalloc(ht * sizeof(char *));
1815 for (i = 0; i < ht; i++)
1816 {
1817 ctx.levels[i] = leveldata + i * (width + 2);
1818 ctx.levels[i][0] = '\0';
1819 }
1820
1821 (void) dispnode(t->root, ht - 1, &ctx);
1822
1823 for (i = ht; i--;)
1824 printf("%s\n", ctx.levels[i]);
1825
1826 sfree(ctx.levels);
1827 sfree(leveldata);
1828 }
1829
1830 typedef struct {
1831 int treedepth;
1832 int elemcount;
1833 } chkctx;
1834
1835 int
1836 chknode(chkctx * ctx, int level, node234 * node,
1837 void *lowbound, void *highbound)
1838 {
1839 int nkids, nelems;
1840 int i;
1841 int count;
1842
1843 /* Count the non-NULL kids. */
1844 for (nkids = 0; nkids < 4 && node->kids[nkids]; nkids++);
1845 /* Ensure no kids beyond the first NULL are non-NULL. */
1846 for (i = nkids; i < 4; i++)
1847 if (node->kids[i])
1848 {
1849 error("node %p: nkids=%d but kids[%d] non-NULL", node, nkids, i);
1850 } else if (node->counts[i])
1851 {
1852 error("node %p: kids[%d] NULL but count[%d]=%d nonzero",
1853 node, i, i, node->counts[i]);
1854 }
1855
1856 /* Count the non-NULL elements. */
1857 for (nelems = 0; nelems < 3 && node->elems[nelems]; nelems++);
1858 /* Ensure no elements beyond the first NULL are non-NULL. */
1859 for (i = nelems; i < 3; i++)
1860 if (node->elems[i])
1861 {
1862 error("node %p: nelems=%d but elems[%d] non-NULL", node, nelems, i);
1863 }
1864
1865 if (nkids == 0)
1866 {
1867 /*
1868 * If nkids==0, this is a leaf node; verify that the tree
1869 * depth is the same everywhere.
1870 */
1871 if (ctx->treedepth < 0)
1872 ctx->treedepth = level; /* we didn't know the depth yet */
1873 else if (ctx->treedepth != level)
1874 error("node %p: leaf at depth %d, previously seen depth %d",
1875 node, level, ctx->treedepth);
1876 } else
1877 {
1878 /*
1879 * If nkids != 0, then it should be nelems+1, unless nelems
1880 * is 0 in which case nkids should also be 0 (and so we
1881 * shouldn't be in this condition at all).
1882 */
1883 int shouldkids = (nelems ? nelems + 1 : 0);
1884 if (nkids != shouldkids)
1885 {
1886 error("node %p: %d elems should mean %d kids but has %d",
1887 node, nelems, shouldkids, nkids);
1888 }
1889 }
1890
1891 /*
1892 * nelems should be at least 1.
1893 */
1894 if (nelems == 0)
1895 {
1896 error("node %p: no elems", node, nkids);
1897 }
1898
1899 /*
1900 * Add nelems to the running element count of the whole tree.
1901 */
1902 ctx->elemcount += nelems;
1903
1904 /*
1905 * Check ordering property: all elements should be strictly >
1906 * lowbound, strictly < highbound, and strictly < each other in
1907 * sequence. (lowbound and highbound are NULL at edges of tree
1908 * - both NULL at root node - and NULL is considered to be <
1909 * everything and > everything. IYSWIM.)
1910 */
1911 if (cmp)
1912 {
1913 for (i = -1; i < nelems; i++)
1914 {
1915 void *lower = (i == -1 ? lowbound : node->elems[i]);
1916 void *higher = (i + 1 == nelems ? highbound : node->elems[i + 1]);
1917 if (lower && higher && cmp(lower, higher) >= 0)
1918 {
1919 error("node %p: kid comparison [%d=%s,%d=%s] failed",
1920 node, i, lower, i + 1, higher);
1921 }
1922 }
1923 }
1924
1925 /*
1926 * Check parent pointers: all non-NULL kids should have a
1927 * parent pointer coming back to this node.
1928 */
1929 for (i = 0; i < nkids; i++)
1930 if (node->kids[i]->parent != node)
1931 {
1932 error("node %p kid %d: parent ptr is %p not %p",
1933 node, i, node->kids[i]->parent, node);
1934 }
1935
1936
1937 /*
1938 * Now (finally!) recurse into subtrees.
1939 */
1940 count = nelems;
1941
1942 for (i = 0; i < nkids; i++)
1943 {
1944 void *lower = (i == 0 ? lowbound : node->elems[i - 1]);
1945 void *higher = (i >= nelems ? highbound : node->elems[i]);
1946 int subcount = chknode(ctx, level + 1, node->kids[i], lower, higher);
1947 if (node->counts[i] != subcount)
1948 {
1949 error("node %p kid %d: count says %d, subtree really has %d",
1950 node, i, node->counts[i], subcount);
1951 }
1952 count += subcount;
1953 }
1954
1955 return count;
1956 }
1957
1958 void verifytree(tree234 * tree, void **array, int arraylen)
1959 {
1960 chkctx ctx;
1961 int i;
1962 void *p;
1963
1964 ctx.treedepth = -1; /* depth unknown yet */
1965 ctx.elemcount = 0; /* no elements seen yet */
1966 /*
1967 * Verify validity of tree properties.
1968 */
1969 if (tree->root)
1970 {
1971 if (tree->root->parent != NULL)
1972 error("root->parent is %p should be null", tree->root->parent);
1973 chknode(&ctx, 0, tree->root, NULL, NULL);
1974 }
1975 printf("tree depth: %d\n", ctx.treedepth);
1976 /*
1977 * Enumerate the tree and ensure it matches up to the array.
1978 */
1979 for (i = 0; NULL != (p = index234(tree, i)); i++)
1980 {
1981 if (i >= arraylen)
1982 error("tree contains more than %d elements", arraylen);
1983 if (array[i] != p)
1984 error("enum at position %d: array says %s, tree says %s",
1985 i, array[i], p);
1986 }
1987 if (ctx.elemcount != i)
1988 {
1989 error("tree really contains %d elements, enum gave %d",
1990 ctx.elemcount, i);
1991 }
1992 if (i < arraylen)
1993 {
1994 error("enum gave only %d elements, array has %d", i, arraylen);
1995 }
1996 i = count234(tree);
1997 if (ctx.elemcount != i)
1998 {
1999 error("tree really contains %d elements, count234 gave %d",
2000 ctx.elemcount, i);
2001 }
2002 }
2003 void verify(void)
2004 {
2005 verifytree(tree, array, arraylen);
2006 }
2007
2008 void internal_addtest(void *elem, int index, void *realret)
2009 {
2010 int i, j;
2011 void *retval;
2012
2013 if (arraysize < arraylen + 1)
2014 {
2015 arraysize = arraylen + 1 + 256;
2016 array = (array == NULL ? smalloc(arraysize * sizeof(*array)) :
2017 srealloc(array, arraysize * sizeof(*array)));
2018 }
2019
2020 i = index;
2021 /* now i points to the first element >= elem */
2022 retval = elem; /* expect elem returned (success) */
2023 for (j = arraylen; j > i; j--)
2024 array[j] = array[j - 1];
2025 array[i] = elem; /* add elem to array */
2026 arraylen++;
2027
2028 if (realret != retval)
2029 {
2030 error("add: retval was %p expected %p", realret, retval);
2031 }
2032
2033 verify();
2034 }
2035
2036 void addtest(void *elem)
2037 {
2038 int i;
2039 void *realret;
2040
2041 realret = add234(tree, elem);
2042
2043 i = 0;
2044 while (i < arraylen && cmp(elem, array[i]) > 0)
2045 i++;
2046 if (i < arraylen && !cmp(elem, array[i]))
2047 {
2048 void *retval = array[i]; /* expect that returned not elem */
2049 if (realret != retval)
2050 {
2051 error("add: retval was %p expected %p", realret, retval);
2052 }
2053 } else
2054 internal_addtest(elem, i, realret);
2055 }
2056
2057 void addpostest(void *elem, int i)
2058 {
2059 void *realret;
2060
2061 realret = addpos234(tree, elem, i);
2062
2063 internal_addtest(elem, i, realret);
2064 }
2065
2066 void delpostest(int i)
2067 {
2068 int index = i;
2069 void *elem = array[i], *ret;
2070
2071 /* i points to the right element */
2072 while (i < arraylen - 1)
2073 {
2074 array[i] = array[i + 1];
2075 i++;
2076 }
2077 arraylen--; /* delete elem from array */
2078
2079 if (tree->cmp)
2080 ret = del234(tree, elem);
2081 else
2082 ret = delpos234(tree, index);
2083
2084 if (ret != elem)
2085 {
2086 error("del returned %p, expected %p", ret, elem);
2087 }
2088
2089 verify();
2090 }
2091
2092 void deltest(void *elem)
2093 {
2094 int i;
2095
2096 i = 0;
2097 while (i < arraylen && cmp(elem, array[i]) > 0)
2098 i++;
2099 if (i >= arraylen || cmp(elem, array[i]) != 0)
2100 return; /* don't do it! */
2101 delpostest(i);
2102 }
2103
2104 /* A sample data set and test utility. Designed for pseudo-randomness,
2105 * and yet repeatability. */
2106
2107 /*
2108 * This random number generator uses the `portable implementation'
2109 * given in ANSI C99 draft N869. It assumes `unsigned' is 32 bits;
2110 * change it if not.
2111 */
2112 int randomnumber(unsigned *seed)
2113 {
2114 *seed *= 1103515245;
2115 *seed += 12345;
2116 return ((*seed) / 65536) % 32768;
2117 }
2118
2119 int mycmp(void *av, void *bv)
2120 {
2121 char const *a = (char const *) av;
2122 char const *b = (char const *) bv;
2123 return strcmp(a, b);
2124 }
2125
2126 #define lenof(x) ( sizeof((x)) / sizeof(*(x)) )
2127
2128 char *strings[] = {
2129 "0", "2", "3", "I", "K", "d", "H", "J", "Q", "N", "n", "q", "j", "i",
2130 "7", "G", "F", "D", "b", "x", "g", "B", "e", "v", "V", "T", "f", "E",
2131 "S", "8", "A", "k", "X", "p", "C", "R", "a", "o", "r", "O", "Z", "u",
2132 "6", "1", "w", "L", "P", "M", "c", "U", "h", "9", "t", "5", "W", "Y",
2133 "m", "s", "l", "4",
2134 #if 0
2135 "a", "ab", "absque", "coram", "de",
2136 "palam", "clam", "cum", "ex", "e",
2137 "sine", "tenus", "pro", "prae",
2138 "banana", "carrot", "cabbage", "broccoli", "onion", "zebra",
2139 "penguin", "blancmange", "pangolin", "whale", "hedgehog",
2140 "giraffe", "peanut", "bungee", "foo", "bar", "baz", "quux",
2141 "murfl", "spoo", "breen", "flarn", "octothorpe",
2142 "snail", "tiger", "elephant", "octopus", "warthog", "armadillo",
2143 "aardvark", "wyvern", "dragon", "elf", "dwarf", "orc", "goblin",
2144 "pixie", "basilisk", "warg", "ape", "lizard", "newt", "shopkeeper",
2145 "wand", "ring", "amulet"
2146 #endif
2147 };
2148
2149 #define NSTR lenof(strings)
2150
2151 void findtest(void)
2152 {
2153 static const int rels[] = {
2154 REL234_EQ, REL234_GE, REL234_LE, REL234_LT, REL234_GT
2155 };
2156 static const char *const relnames[] = {
2157 "EQ", "GE", "LE", "LT", "GT"
2158 };
2159 int i, j, rel, index;
2160 char *p, *ret, *realret, *realret2;
2161 int lo, hi, mid, c;
2162
2163 for (i = 0; i < (int) NSTR; i++)
2164 {
2165 p = strings[i];
2166 for (j = 0; j < (int) (sizeof(rels) / sizeof(*rels)); j++)
2167 {
2168 rel = rels[j];
2169
2170 lo = 0;
2171 hi = arraylen - 1;
2172 while (lo <= hi)
2173 {
2174 mid = (lo + hi) / 2;
2175 c = strcmp(p, array[mid]);
2176 if (c < 0)
2177 hi = mid - 1;
2178 else if (c > 0)
2179 lo = mid + 1;
2180 else
2181 break;
2182 }
2183
2184 if (c == 0)
2185 {
2186 if (rel == REL234_LT)
2187 ret = (mid > 0 ? array[--mid] : NULL);
2188 else if (rel == REL234_GT)
2189 ret = (mid < arraylen - 1 ? array[++mid] : NULL);
2190 else
2191 ret = array[mid];
2192 } else
2193 {
2194 assert(lo == hi + 1);
2195 if (rel == REL234_LT || rel == REL234_LE)
2196 {
2197 mid = hi;
2198 ret = (hi >= 0 ? array[hi] : NULL);
2199 } else if (rel == REL234_GT || rel == REL234_GE)
2200 {
2201 mid = lo;
2202 ret = (lo < arraylen ? array[lo] : NULL);
2203 } else
2204 ret = NULL;
2205 }
2206
2207 realret = findrelpos234(tree, p, NULL, rel, &index);
2208 if (realret != ret)
2209 {
2210 error("find(\"%s\",%s) gave %s should be %s",
2211 p, relnames[j], realret, ret);
2212 }
2213 if (realret && index != mid)
2214 {
2215 error("find(\"%s\",%s) gave %d should be %d",
2216 p, relnames[j], index, mid);
2217 }
2218 if (realret && rel == REL234_EQ)
2219 {
2220 realret2 = index234(tree, index);
2221 if (realret2 != realret)
2222 {
2223 error("find(\"%s\",%s) gave %s(%d) but %d -> %s",
2224 p, relnames[j], realret, index, index, realret2);
2225 }
2226 }
2227 #if 0
2228 printf("find(\"%s\",%s) gave %s(%d)\n", p, relnames[j],
2229 realret, index);
2230 #endif
2231 }
2232 }
2233
2234 realret = findrelpos234(tree, NULL, NULL, REL234_GT, &index);
2235 if (arraylen && (realret != array[0] || index != 0))
2236 {
2237 error("find(NULL,GT) gave %s(%d) should be %s(0)",
2238 realret, index, array[0]);
2239 } else if (!arraylen && (realret != NULL))
2240 {
2241 error("find(NULL,GT) gave %s(%d) should be NULL", realret, index);
2242 }
2243
2244 realret = findrelpos234(tree, NULL, NULL, REL234_LT, &index);
2245 if (arraylen
2246 && (realret != array[arraylen - 1] || index != arraylen - 1))
2247 {
2248 error("find(NULL,LT) gave %s(%d) should be %s(0)", realret, index,
2249 array[arraylen - 1]);
2250 } else if (!arraylen && (realret != NULL))
2251 {
2252 error("find(NULL,LT) gave %s(%d) should be NULL", realret, index);
2253 }
2254 }
2255
2256 void splittest(tree234 * tree, void **array, int arraylen)
2257 {
2258 int i;
2259 tree234 *tree3, *tree4;
2260 for (i = 0; i <= arraylen; i++)
2261 {
2262 tree3 = copytree234(tree, NULL, NULL);
2263 tree4 = splitpos234(tree3, i, 0);
2264 verifytree(tree3, array, i);
2265 verifytree(tree4, array + i, arraylen - i);
2266 join234(tree3, tree4);
2267 freetree234(tree4); /* left empty by join */
2268 verifytree(tree3, array, arraylen);
2269 freetree234(tree3);
2270 }
2271 }
2272
2273 int main(void)
2274 {
2275 int in[NSTR];
2276 int i, j, k;
2277 int tworoot, tmplen;
2278 unsigned seed = 0;
2279 tree234 *tree2, *tree3, *tree4;
2280 int c;
2281
2282 setvbuf(stdout, NULL, _IOLBF, 0);
2283
2284 for (i = 0; i < (int) NSTR; i++)
2285 in[i] = 0;
2286 array = NULL;
2287 arraylen = arraysize = 0;
2288 tree = newtree234(mycmp);
2289 cmp = mycmp;
2290
2291 verify();
2292 for (i = 0; i < 10000; i++)
2293 {
2294 j = randomnumber(&seed);
2295 j %= NSTR;
2296 printf("trial: %d\n", i);
2297 if (in[j])
2298 {
2299 printf("deleting %s (%d)\n", strings[j], j);
2300 deltest(strings[j]);
2301 in[j] = 0;
2302 } else
2303 {
2304 printf("adding %s (%d)\n", strings[j], j);
2305 addtest(strings[j]);
2306 in[j] = 1;
2307 }
2308 disptree(tree);
2309 findtest();
2310 }
2311
2312 while (arraylen > 0)
2313 {
2314 j = randomnumber(&seed);
2315 j %= arraylen;
2316 deltest(array[j]);
2317 }
2318
2319 freetree234(tree);
2320
2321 /*
2322 * Now try an unsorted tree. We don't really need to test
2323 * delpos234 because we know del234 is based on it, so it's
2324 * already been tested in the above sorted-tree code; but for
2325 * completeness we'll use it to tear down our unsorted tree
2326 * once we've built it.
2327 */
2328 tree = newtree234(NULL);
2329 cmp = NULL;
2330 verify();
2331 for (i = 0; i < 1000; i++)
2332 {
2333 printf("trial: %d\n", i);
2334 j = randomnumber(&seed);
2335 j %= NSTR;
2336 k = randomnumber(&seed);
2337 k %= count234(tree) + 1;
2338 printf("adding string %s at index %d\n", strings[j], k);
2339 addpostest(strings[j], k);
2340 }
2341
2342 /*
2343 * While we have this tree in its full form, we'll take a copy
2344 * of it to use in split and join testing.
2345 */
2346 tree2 = copytree234(tree, NULL, NULL);
2347 verifytree(tree2, array, arraylen); /* check the copy is accurate */
2348 /*
2349 * Split tests. Split the tree at every possible point and
2350 * check the resulting subtrees.
2351 */
2352 tworoot = (!tree2->root->elems[1]); /* see if it has a 2-root */
2353 splittest(tree2, array, arraylen);
2354 /*
2355 * Now do the split test again, but on a tree that has a 2-root
2356 * (if the previous one didn't) or doesn't (if the previous one
2357 * did).
2358 */
2359 tmplen = arraylen;
2360 while ((!tree2->root->elems[1]) == tworoot)
2361 {
2362 delpos234(tree2, --tmplen);
2363 }
2364 printf("now trying splits on second tree\n");
2365 splittest(tree2, array, tmplen);
2366 freetree234(tree2);
2367
2368 /*
2369 * Back to the main testing of uncounted trees.
2370 */
2371 while (count234(tree) > 0)
2372 {
2373 printf("cleanup: tree size %d\n", count234(tree));
2374 j = randomnumber(&seed);
2375 j %= count234(tree);
2376 printf("deleting string %s from index %d\n", (char *) array[j], j);
2377 delpostest(j);
2378 }
2379 freetree234(tree);
2380
2381 /*
2382 * Finally, do some testing on split/join on _sorted_ trees. At
2383 * the same time, we'll be testing split on very small trees.
2384 */
2385 tree = newtree234(mycmp);
2386 cmp = mycmp;
2387 arraylen = 0;
2388 for (i = 0; i < 16; i++)
2389 {
2390 addtest(strings[i]);
2391 tree2 = copytree234(tree, NULL, NULL);
2392 splittest(tree2, array, arraylen);
2393 freetree234(tree2);
2394 }
2395 freetree234(tree);
2396
2397 /*
2398 * Test silly cases of join: join(emptytree, emptytree), and
2399 * also ensure join correctly spots when sorted trees fail the
2400 * ordering constraint.
2401 */
2402 tree = newtree234(mycmp);
2403 tree2 = newtree234(mycmp);
2404 tree3 = newtree234(mycmp);
2405 tree4 = newtree234(mycmp);
2406 assert(mycmp(strings[0], strings[1]) < 0); /* just in case :-) */
2407 add234(tree2, strings[1]);
2408 add234(tree4, strings[0]);
2409 array[0] = strings[0];
2410 array[1] = strings[1];
2411 verifytree(tree, array, 0);
2412 verifytree(tree2, array + 1, 1);
2413 verifytree(tree3, array, 0);
2414 verifytree(tree4, array, 1);
2415
2416 /*
2417 * So:
2418 * - join(tree,tree3) should leave both tree and tree3 unchanged.
2419 * - joinr(tree,tree2) should leave both tree and tree2 unchanged.
2420 * - join(tree4,tree3) should leave both tree3 and tree4 unchanged.
2421 * - join(tree, tree2) should move the element from tree2 to tree.
2422 * - joinr(tree4, tree3) should move the element from tree4 to tree3.
2423 * - join(tree,tree3) should return NULL and leave both unchanged.
2424 * - join(tree3,tree) should work and create a bigger tree in tree3.
2425 */
2426 assert(tree == join234(tree, tree3));
2427 verifytree(tree, array, 0);
2428 verifytree(tree3, array, 0);
2429 assert(tree2 == join234r(tree, tree2));
2430 verifytree(tree, array, 0);
2431 verifytree(tree2, array + 1, 1);
2432 assert(tree4 == join234(tree4, tree3));
2433 verifytree(tree3, array, 0);
2434 verifytree(tree4, array, 1);
2435 assert(tree == join234(tree, tree2));
2436 verifytree(tree, array + 1, 1);
2437 verifytree(tree2, array, 0);
2438 assert(tree3 == join234r(tree4, tree3));
2439 verifytree(tree3, array, 1);
2440 verifytree(tree4, array, 0);
2441 assert(NULL == join234(tree, tree3));
2442 verifytree(tree, array + 1, 1);
2443 verifytree(tree3, array, 1);
2444 assert(tree3 == join234(tree3, tree));
2445 verifytree(tree3, array, 2);
2446 verifytree(tree, array, 0);
2447
2448 return 0;
2449 }
2450
2451 #endif
2452
2453 #if 0 /* sorted list of strings might be useful */
2454 {
2455 "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D",
2456 "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
2457 "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b",
2458 "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
2459 "o", "p", "q", "r", "s", "t", "u", "v", "w", "x",}
2460 #endif