File: bostree.c

package info (click to toggle)
pqiv 2.11-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 700 kB
  • sloc: ansic: 9,781; sh: 360; makefile: 13
file content (610 lines) | stat: -rw-r--r-- 17,241 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
/*
	Self-Balancing order statistic tree

	Implements an AVL tree with two additional methods,
	Select(i), which finds the i'th smallest element, and
	Rank(x), which returns the rank of a given element,
	which both run in O(log n).

	The tree is implemented with map semantics, that is, there are separete key
	and value pointers.

	Copyright (c) 2017, Phillip Berndt

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "bostree.h"
#include <assert.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>

/* Tree structure */
struct _BOSTree {
	BOSNode *root_node;

	BOSTree_cmp_function cmp_function;
	BOSTree_free_function free_function;
};

/* Local helper functions */
static int _imax(const int i1, const int i2) {
	return i1 > i2 ? i1 : i2;
}

static int _bostree_balance(BOSNode *node) {
	const int left_depth = node->left_child_node ? node->left_child_node->depth + 1 : 0;
	const int right_depth = node->right_child_node ? node->right_child_node->depth + 1 : 0;
	return right_depth - left_depth;
}

static BOSNode *_bostree_rotate_right(BOSTree *tree, BOSNode *P) {
	// Rotate right:
	//
	//      P                     L
	//  L        R     -->    c1      P
	//c1 c2                        c2     R
	//
	BOSNode *L = P->left_child_node;

	if(P->parent_node) {
		if(P->parent_node->left_child_node == P) {
			P->parent_node->left_child_node = L;
		}
		else {
			P->parent_node->right_child_node = L;
		}
	}
	else {
		tree->root_node = L;
	}

	L->parent_node = P->parent_node;

	P->left_child_node = L->right_child_node;
	P->left_child_count = L->right_child_count;
	if(P->left_child_node) {
		P->left_child_node->parent_node = P;
	}
	P->depth = _imax(P->left_child_node ? 1 + P->left_child_node->depth : 0, P->right_child_node ? 1 + P->right_child_node->depth : 0);
	P->parent_node = L;

	L->right_child_node = P;
	P->parent_node = L;
	L->right_child_count = P->left_child_count + P->right_child_count + 1;
	L->depth = _imax(L->left_child_node ? 1 + L->left_child_node->depth : 0, L->right_child_node ? 1 + L->right_child_node->depth : 0);

	return L;
}

static BOSNode *_bostree_rotate_left(BOSTree *tree, BOSNode *P) {
	// Rotate left:
	//
	//      P                     R
	//  L        R     -->    P      c2
	//         c1 c2        L  c1
	//
	BOSNode *R = P->right_child_node;

	if(P->parent_node) {
		if(P->parent_node->left_child_node == P) {
			P->parent_node->left_child_node = R;
		}
		else {
			P->parent_node->right_child_node = R;
		}
	}
	else {
		tree->root_node = R;
	}

	R->parent_node = P->parent_node;

	P->right_child_node = R->left_child_node;
	P->right_child_count = R->left_child_count;
	if(P->right_child_node) {
		P->right_child_node->parent_node = P;
	}
	P->depth = _imax(P->left_child_node ? 1 + P->left_child_node->depth : 0, P->right_child_node ? 1 + P->right_child_node->depth : 0);
	P->parent_node = R;

	R->left_child_node = P;
	P->parent_node = R;
	R->left_child_count = P->left_child_count + P->right_child_count + 1;
	R->depth = _imax(R->left_child_node ? 1 + R->left_child_node->depth : 0, R->right_child_node ? 1 + R->right_child_node->depth : 0);

	return R;
}


/* API implementation */
BOSTree *bostree_new(BOSTree_cmp_function cmp_function, BOSTree_free_function free_function) {
	BOSTree *new_tree = malloc(sizeof(BOSTree));
	new_tree->root_node = NULL;
	new_tree->cmp_function = cmp_function;
	new_tree->free_function = free_function;
	return new_tree;
}

void bostree_destroy(BOSTree *tree) {
	// Walk the tree and unref all nodes
	BOSNode *node = tree->root_node;
	while(node) {
		// The order should not really matter, but use post-order traversal here.
		while(node->left_child_node) {
			node = node->left_child_node;
		}

		if(node->right_child_node) {
			node = node->right_child_node;
			continue;
		}

		// At this point, we can be sure that this node has no child nodes.
		// So it is safe to remove it.
		BOSNode *next = node->parent_node;
		if(next) {
			if(next->left_child_node == node) {
				next->left_child_node = NULL;
			}
			else {
				next->right_child_node = NULL;
			}
		}
		bostree_node_weak_unref(tree, node);
		node = next;
	}

	free(tree);
}

unsigned int bostree_node_count(BOSTree *tree) {
	return tree->root_node ? tree->root_node->left_child_count + tree->root_node->right_child_count + 1 : 0;
}

BOSNode *bostree_insert(BOSTree *tree, void *key, void *data) {
	BOSNode **node = &tree->root_node;
	BOSNode *parent_node = NULL;

	// Find tree position to insert new node
	while(*node) {
		parent_node = *node;
		int cmp = tree->cmp_function(key, (*node)->key);
		if(cmp < 0) {
			(*node)->left_child_count++;
			node = &(*node)->left_child_node;
		}
		else {
			(*node)->right_child_count++;
			node = &(*node)->right_child_node;
		}
	}

	// Create new node
	BOSNode *new_node = malloc(sizeof(BOSNode));
	memset(new_node, 0, sizeof(BOSNode));
	new_node->key = key;
	new_node->data = data;
	new_node->weak_ref_count = 1;
	new_node->weak_ref_node_valid = 1;
	new_node->parent_node = parent_node;

	*node = new_node;

	if(!parent_node) {
		// Simple case, this is the first node.
		tree->root_node = new_node;
		return new_node;
	}

	// Check if the depth changed with the new node:
	// It does only change if this is the first child of the parent
	if(!!parent_node->left_child_node ^ !!parent_node->right_child_node) {
		// Bubble the information up the tree
		parent_node->depth++;
		while(parent_node->parent_node) {
			// Assign new depth
			parent_node = parent_node->parent_node;

			unsigned int new_left_depth  = parent_node->left_child_node ? parent_node->left_child_node->depth + 1 : 0;
			unsigned int new_right_depth = parent_node->right_child_node ? parent_node->right_child_node->depth + 1 : 0;

			unsigned int max_depth = _imax(new_left_depth, new_right_depth);

			if(parent_node->depth != max_depth) {
				parent_node->depth = max_depth;
			}
			else {
				// We can break here, because if the depth did not change
				// at this level, it won't have further up either.
				break;
			}

			// Check if this node violates the AVL property, that is, that the
			// depths differ by no more than 1.
			if(new_left_depth - 2 == new_right_depth) {
				// Handle left-right case
				if(_bostree_balance(parent_node->left_child_node) > 0) {
					_bostree_rotate_left(tree, parent_node->left_child_node);
				}

				// Left is two levels deeper than right. Rotate right.
				parent_node = _bostree_rotate_right(tree, parent_node);
			}
			else if(new_left_depth + 2 == new_right_depth) {
				// Handle right-left case
				if(_bostree_balance(parent_node->right_child_node) < 0) {
					_bostree_rotate_right(tree, parent_node->right_child_node);
				}

				// Right is two levels deeper than left. Rotate left.
				parent_node = _bostree_rotate_left(tree, parent_node);
			}
		}
	}

	return new_node;
}

void bostree_remove(BOSTree *tree, BOSNode *node) {
	BOSNode *bubble_up = NULL;

	// If this node has children on both sides, bubble one of it upwards
	// and rotate within the subtrees.
	if(node->left_child_node && node->right_child_node) {
		BOSNode *candidate = NULL;
		BOSNode *lost_child = NULL;
		if(node->left_child_node->depth >= node->right_child_node->depth) {
			// Left branch is deeper than right branch, might be a good idea to
			// bubble from this side to maintain the AVL property with increased
			// likelihood.
			node->left_child_count--;
			candidate = node->left_child_node;
			while(candidate->right_child_node) {
				candidate->right_child_count--;
				candidate = candidate->right_child_node;
			}
			lost_child = candidate->left_child_node;
		}
		else {
			node->right_child_count--;
			candidate = node->right_child_node;
			while(candidate->left_child_node) {
				candidate->left_child_count--;
				candidate = candidate->left_child_node;
			}
			lost_child = candidate->right_child_node;
		}

		BOSNode *bubble_start = candidate->parent_node;
		if(bubble_start->left_child_node == candidate) {
			bubble_start->left_child_node = lost_child;
		}
		else {
			bubble_start->right_child_node = lost_child;
		}
		if(lost_child) {
			lost_child->parent_node = bubble_start;
		}

		// We will later rebalance upwards from bubble_start up to candidate.
		// But first, anchor candidate into the place where "node" used to be.

		if(node->parent_node) {
			if(node->parent_node->left_child_node == node) {
				node->parent_node->left_child_node = candidate;
			}
			else {
				node->parent_node->right_child_node = candidate;
			}
		}
		else {
			tree->root_node = candidate;
		}
		candidate->parent_node = node->parent_node;

		candidate->left_child_node = node->left_child_node;
		candidate->left_child_count = node->left_child_count;
		candidate->right_child_node = node->right_child_node;
		candidate->right_child_count = node->right_child_count;

		if(candidate->left_child_node) {
			candidate->left_child_node->parent_node = candidate;
		}

		if(candidate->right_child_node) {
			candidate->right_child_node->parent_node = candidate;
		}

		// From here on, node is out of the game.
		// Rebalance up to candidate.

		if(bubble_start != node) {
			while(bubble_start != candidate) {
				bubble_start->depth = _imax((bubble_start->left_child_node ? bubble_start->left_child_node->depth + 1 : 0),
					(bubble_start->right_child_node ? bubble_start->right_child_node->depth + 1 : 0));
				int balance = _bostree_balance(bubble_start);
				if(balance > 1) {
					// Rotate left. Check for right-left case before.
					if(_bostree_balance(bubble_start->right_child_node) < 0) {
						_bostree_rotate_right(tree, bubble_start->right_child_node);
					}
					bubble_start = _bostree_rotate_left(tree, bubble_start);
				}
				else if(balance < -1) {
					// Rotate right. Check for left-right case before.
					if(_bostree_balance(bubble_start->left_child_node) > 0) {
						_bostree_rotate_left(tree, bubble_start->left_child_node);
					}
					bubble_start = _bostree_rotate_right(tree, bubble_start);
				}
				bubble_start = bubble_start->parent_node;
			}
		}

		// Fixup candidate's depth
		candidate->depth = _imax((candidate->left_child_node ? candidate->left_child_node->depth + 1 : 0),
			(candidate->right_child_node ? candidate->right_child_node->depth + 1 : 0));

		// We'll have to fixup child counts and depths up to the root, do that
		// later.
		bubble_up = candidate->parent_node;

		// Fix immediate parent node child count here.
		if(bubble_up) {
			if(bubble_up->left_child_node == candidate) {
				bubble_up->left_child_count--;
			}
			else {
				bubble_up->right_child_count--;
			}
		}
	}
	else {
		// If this node has children on one side only, removing it is much simpler.
		if(!node->parent_node) {
			// Simple case: Node _was_ the old root.
			if(node->left_child_node) {
				tree->root_node = node->left_child_node;
				if(node->left_child_node) {
					node->left_child_node->parent_node = NULL;
				}
			}
			else {
				tree->root_node = node->right_child_node;
				if(node->right_child_node) {
					node->right_child_node->parent_node = NULL;
				}
			}

			// No rebalancing to do
			bubble_up = NULL;
		}
		else {
			BOSNode *candidate = node->left_child_node;
			int candidate_count = node->left_child_count;
			if(node->right_child_node) {
				candidate = node->right_child_node;
				candidate_count = node->right_child_count;
			}

			if(node->parent_node->left_child_node == node) {
				node->parent_node->left_child_node = candidate;
				node->parent_node->left_child_count = candidate_count;
			}
			else {
				node->parent_node->right_child_node = candidate;
				node->parent_node->right_child_count = candidate_count;
			}

			if(candidate) {
				candidate->parent_node = node->parent_node;
			}

			// Again, from here on, the original node is out of the game.
			// Rebalance up to the root.
			bubble_up = node->parent_node;
		}
	}

	// At this point, everything below and including bubble_start is
	// balanced, and we have to look further up.

	char bubbling_finished = 0;
	while(bubble_up) {
		if(!bubbling_finished) {
			// Calculate updated depth for bubble_up
			unsigned int left_depth = bubble_up->left_child_node ? bubble_up->left_child_node->depth + 1 : 0;
			unsigned int right_depth = bubble_up->right_child_node ? bubble_up->right_child_node->depth + 1 : 0;
			unsigned int new_depth = _imax(left_depth, right_depth);
			char depth_changed = (new_depth != bubble_up->depth);
			bubble_up->depth = new_depth;

			// Rebalance bubble_up
			// Not necessary for the first node, but calling _bostree_balance once
			// isn't that much overhead.
			int balance = _bostree_balance(bubble_up);
			if(balance < -1) {
				if(_bostree_balance(bubble_up->left_child_node) > 0) {
					_bostree_rotate_left(tree, bubble_up->left_child_node);
				}
				bubble_up = _bostree_rotate_right(tree, bubble_up);
			}
			else if(balance > 1) {
				if(_bostree_balance(bubble_up->right_child_node) < 0) {
					_bostree_rotate_right(tree, bubble_up->right_child_node);
				}
				bubble_up = _bostree_rotate_left(tree, bubble_up);
			}
			else {
				if(!depth_changed) {
					// If we neither had to rotate nor to change the depth,
					// then we are obviously finished.  Only update child
					// counts from here on.
					bubbling_finished = 1;
				}
			}
		}

		if(bubble_up->parent_node) {
			if(bubble_up->parent_node->left_child_node == bubble_up) {
				bubble_up->parent_node->left_child_count--;
			}
			else {
				bubble_up->parent_node->right_child_count--;
			}
		}
		bubble_up = bubble_up->parent_node;
	}

	node->weak_ref_node_valid = 0;
	bostree_node_weak_unref(tree, node);
}

BOSNode *bostree_node_weak_ref(BOSNode *node) {
	assert(node->weak_ref_count < 127);
	assert(node->weak_ref_count > 0);
	node->weak_ref_count++;
	return node;
}

BOSNode *bostree_node_weak_unref(BOSTree *tree, BOSNode *node) {
	node->weak_ref_count--;
	if(node->weak_ref_count == 0) {
		if(tree->free_function) {
			tree->free_function(node);
		}
		free(node);
	}
	else if(node->weak_ref_node_valid) {
		return node;
	}
	return NULL;
}

BOSNode *bostree_lookup(BOSTree *tree, const void *key) {
	BOSNode *node = tree->root_node;
	while(node) {
		int cmp = tree->cmp_function(key, node->key);
		if(cmp == 0) {
			break;
		}
		else if(cmp < 0) {
			node = node->left_child_node;
		}
		else {
			node = node->right_child_node;
		}
	}
	return node;
}

BOSNode *bostree_select(BOSTree *tree, unsigned int index) {
	BOSNode *node = tree->root_node;
	while(node) {
		if(node->left_child_count <= index) {
			index -= node->left_child_count;
			if(index == 0) {
				return node;
			}
			index--;
			node = node->right_child_node;
		}
		else {
			node = node->left_child_node;
		}
	}
	return node;
}

BOSNode *bostree_next_node(BOSNode *node) {
	if(node->right_child_node) {
		node = node->right_child_node;
		while(node->left_child_node) {
			node = node->left_child_node;
		}
		return node;
	}
	else if(node->parent_node) {
		while(node->parent_node && node->parent_node->right_child_node == node) {
			node = node->parent_node;
		}
		return node->parent_node;
	}
	return NULL;
}

BOSNode *bostree_previous_node(BOSNode *node) {
	if(node->left_child_node) {
		node = node->left_child_node;
		while(node->right_child_node) {
			node = node->right_child_node;
		}
		return node;
	}
	else if(node->parent_node) {
		while(node->parent_node && node->parent_node->left_child_node == node) {
			node = node->parent_node;
		}
		return node->parent_node;
	}
	return NULL;
}

unsigned int bostree_rank(BOSNode *node) {
	unsigned int counter = node->left_child_count;
	while(node) {
		if(node->parent_node && node->parent_node->right_child_node == node) counter += 1 + node->parent_node->left_child_count;
		node = node->parent_node;
	}
	return counter;
}

#if !defined(NDEBUG)
#include <stdio.h>
#include <unistd.h>

/* Debug helpers:

	Print the tree to stdout in dot format.
*/

static void _bostree_print_helper(BOSNode *node) {
	printf("  %s [label=\"\\N (%d,%d,%d)\"];\n", (char *)node->key, node->left_child_count, node->right_child_count, node->depth);
	if(node->parent_node) {
		printf("  %s -> %s [color=green];\n", (char *)node->key, (char *)node->parent_node->key);
	}

	if(node->left_child_node != NULL) {
		printf("  %s -> %s\n", (char *)node->key, (char *)node->left_child_node->key);
		_bostree_print_helper(node->left_child_node);
	}
	if(node->right_child_node != NULL) {
		printf("  %s -> %s\n", (char *)node->key, (char *)node->right_child_node->key);
		_bostree_print_helper(node->right_child_node);
	}
}

void bostree_print(BOSTree *tree) {
	if(tree->root_node == NULL) {
		return;
	}

	printf("digraph {\n  ordering = out;\n");
	_bostree_print_helper(tree->root_node);
	printf("}\n");
	fsync(0);
}
#endif