File: tree.c

package info (click to toggle)
xymon 4.3.30-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 11,288 kB
  • sloc: ansic: 69,112; sh: 3,595; makefile: 857; javascript: 452; perl: 48
file content (551 lines) | stat: -rw-r--r-- 13,606 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
/*----------------------------------------------------------------------------*/
/* Xymon monitor library.                                                     */
/*                                                                            */
/* This is a library module, part of libxymon.                                */
/* It contains routines for tree-based record storage.                        */
/*                                                                            */
/* Copyright (C) 2011-2011 Henrik Storner <henrik@storner.dk>                 */
/*                                                                            */
/* This program is released under the GNU General Public License (GPL),       */
/* version 2. See the file "COPYING" for details.                             */
/*                                                                            */
/*----------------------------------------------------------------------------*/

static char rcsid[] = "$Id: files.c 6712 2011-07-31 21:01:52Z storner $";

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>

#include "config.h"
#include "tree.h"


#ifdef HAVE_BINARY_TREE
#include <search.h>

typedef struct treerec_t {
	char *key;
	void *userdata;
	int (*compare)(const char *a, const char *b);
	struct treerec_t *link;
} treerec_t;

typedef struct xtree_t {
	void *root;
	int (*compare)(const char *a, const char *b);
} xtree_t;
static treerec_t *i_curr = NULL;


static int xtree_i_compare(const void *pa, const void *pb)
{
	const treerec_t *reca = pa, *recb = pb;
	return (reca->compare)(reca->key, recb->key);
}


void *xtreeNew(int(*xtreeCompare)(const char *a, const char *b))
{
	xtree_t *newtree;

	newtree = (xtree_t *)calloc(1, sizeof(xtree_t));
	newtree->compare = xtreeCompare;
	newtree->root = NULL;

	return newtree;
}

void xtreeDestroy(void *treehandle)
{
	free(treehandle);
}

xtreeStatus_t xtreeAdd(void *treehandle, char *key, void *userdata)
{
	xtree_t *tree = treehandle;
	treerec_t *rec, **erec;

	if (!tree) return XTREE_STATUS_NOTREE;

	rec = (treerec_t *)calloc(1, sizeof(treerec_t));
	rec->key = key;
	rec->userdata = userdata;
	rec->compare = tree->compare;

	erec = tsearch(rec, &tree->root, xtree_i_compare);
	if (erec == NULL) {
		free(rec);
		return XTREE_STATUS_MEM_EXHAUSTED;
	}
	if (*erec != rec) {
		/* Was already there */
		free(rec);
		return XTREE_STATUS_DUPLICATE_KEY;
	}

	return XTREE_STATUS_OK;
}


void *xtreeDelete(void *treehandle, char *key)
{
	xtree_t *tree = treehandle;
	treerec_t **result, *zombie, rec;
	void *userdata;

	if (!tree) return NULL;

	rec.key = key;
	rec.userdata = NULL;
	rec.compare = tree->compare;
	result = tfind(&rec, &tree->root, xtree_i_compare);
	if (result == NULL) {
		/* Not found */
		return NULL;
	}

	userdata = (*result)->userdata;
	zombie = (*result);
	tdelete(&rec, &tree->root, xtree_i_compare);
	free(zombie);

	return userdata;
}


xtreePos_t xtreeFind(void *treehandle, char *key)
{
	xtree_t *tree = treehandle;
	treerec_t **result, rec;

	if (!tree) return NULL;

	rec.key = key;
	rec.userdata = NULL;
	rec.compare = tree->compare;
	result = tfind(&rec, &tree->root, xtree_i_compare);

	return (result ? *result : NULL);
}


static void xtree_i_action(const void *nodep, const VISIT which, const int depth)
{
	treerec_t *rec = NULL;

	switch (which) {
	  case preorder:
		break;
	  case postorder:
		rec = *(treerec_t **) nodep;
		break;
	  case endorder:
		break;
	  case leaf:
		rec = *(treerec_t **) nodep;
		break;
	}

	if (rec) {
		/*
		 * Each time here, we have rec pointing to the next record in the tree, and i_curr is then
		 * pointing to the previous record. So build a linked list of the records going backwards
		 * as we move through the tree.
		 *
		 * R0 <- R1:link <- R2:link <- R3:link
		 *                              ^
		 *                              i_curr
		 *
		 * becomes
		 *
		 * R0 <- R1:link <- R2:link <- R3:link <- rec:link
		 *                                         ^
		 *                                         i_curr
		 */
		rec->link = i_curr;
		i_curr = rec;
	}
}

xtreePos_t xtreeFirst(void *treehandle)
{
	xtree_t *tree = treehandle;
	treerec_t *walk, *right, *left;

	if (!tree) return NULL;

	i_curr = NULL;
	twalk(tree->root, xtree_i_action);
	if (!i_curr) return NULL;

	/*
	 * We have walked the tree and created a reverse-linked list of the records.
	 * Now reverse the list so we get the records in the right sequence.
	 * i_curr points to the last entry.
	 *
	 * R1 <- R2 <- R3 <- R4
	 *                   ^
	 *                   i_curr
	 *
	 * must be reversed to
	 *
	 * R1 -> R2 -> R3 -> R4
	 */

	walk = i_curr;
	right = NULL;
	while (walk->link) {
		left = walk->link;
		walk->link = right;
		right = walk;
		walk = left;
	}
	walk->link = right;

	i_curr = NULL;
	return walk;
}

xtreePos_t xtreeNext(void *treehandle, xtreePos_t pos)
{
	return pos ? ((treerec_t *)pos)->link : NULL;
}


char *xtreeKey(void *treehandle, xtreePos_t pos)
{
	return pos ? ((treerec_t *)pos)->key : NULL;
}

void *xtreeData(void *treehandle, xtreePos_t pos)
{
	return pos ? ((treerec_t *)pos)->userdata : NULL;
}

#else

typedef struct treerec_t {
	char *key;
	void *userdata;
	int deleted;
} treerec_t;

typedef struct xtree_t {
	treerec_t *entries;
	xtreePos_t treesz;
	int (*compare)(const char *a, const char *b);
} xtree_t;

static xtreePos_t binsearch(xtree_t *mytree, char *key)
{
	xtreePos_t uplim, lowlim, n;

	if (!key) return -1;

	/* Do a binary search  */
	lowlim = 0; uplim = mytree->treesz-1;

	do {
		xtreePos_t res;

		n = (uplim + lowlim) / 2;
		res = mytree->compare(key, mytree->entries[n].key);

		if (res == 0) {
			/* Found it! */
			uplim = -1; /* To exit loop */
		}
		else if (res > 0) {
		  	/* Higher up */
			lowlim = n+1;
		}
		else {
			/* Further down */
			uplim = n-1;
		}

	} while ((uplim >= 0) && (lowlim <= uplim));

	return n;
}

void *xtreeNew(int(*xtreeCompare)(const char *a, const char *b))
{
	xtree_t *newtree = (xtree_t *)calloc(1, sizeof(xtree_t));
	newtree->compare = xtreeCompare;
	return newtree;
}

void xtreeDestroy(void *treehandle)
{
	xtree_t *mytree = (xtree_t *)treehandle;
	xtreePos_t i;

	if (treehandle == NULL) return;

	/* Must delete our privately held keys in the deleted records */
	for (i = 0; (i < mytree->treesz); i++) {
		if (mytree->entries[i].deleted) free(mytree->entries[i].key);
	}
	free(mytree->entries);
	free(mytree);
}

xtreePos_t xtreeFind(void *treehandle, char *key)
{
	xtree_t *mytree = (xtree_t *)treehandle;
	xtreePos_t n;

	/* Does tree exist ? Is it empty? */
	if ((treehandle == NULL) || (mytree->treesz == 0)) return -1;

	n = binsearch(mytree, key);
	if ((n >= 0) && (n < mytree->treesz) && (mytree->entries[n].deleted == 0) && (mytree->compare(key, mytree->entries[n].key) == 0)) 
		return n;

	return -1;
}

xtreePos_t xtreeFirst(void *treehandle)
{
	xtree_t *mytree = (xtree_t *)treehandle;

	/* Does tree exist ? Is it empty? */
	if ((treehandle == NULL) || (mytree->treesz == 0)) return -1;

	return 0;
}

xtreePos_t xtreeNext(void *treehandle, xtreePos_t pos)
{
	xtree_t *mytree = (xtree_t *)treehandle;

	/* Does tree exist ? Is it empty? */
	if ((treehandle == NULL) || (mytree->treesz == 0) || (pos >= (mytree->treesz - 1)) || (pos < 0)) return -1;

	do {
		pos++;
	} while (mytree->entries[pos].deleted && (pos < mytree->treesz));

	return (pos < mytree->treesz) ? pos : -1;
}

char *xtreeKey(void *treehandle, xtreePos_t pos)
{
	xtree_t *mytree = (xtree_t *)treehandle;

	/* Does tree exist ? Is it empty? */
	if ((treehandle == NULL) || (mytree->treesz == 0) || (pos >= mytree->treesz) || (pos < 0)) return NULL;

	return mytree->entries[pos].key;
}

void *xtreeData(void *treehandle, xtreePos_t pos)
{
	xtree_t *mytree = (xtree_t *)treehandle;

	/* Does tree exist ? Is it empty? */
	if ((treehandle == NULL) || (mytree->treesz == 0) || (pos >= mytree->treesz) || (pos < 0)) return NULL;

	return mytree->entries[pos].userdata;
}


xtreeStatus_t xtreeAdd(void *treehandle, char *key, void *userdata)
{
	xtree_t *mytree = (xtree_t *)treehandle;
	xtreePos_t n;

	if (treehandle == NULL) return XTREE_STATUS_NOTREE;

	if (mytree->treesz == 0) {
		/* Empty tree, just add record */
		mytree->entries = (treerec_t *)calloc(1, sizeof(treerec_t));
		mytree->entries[0].key = key;
		mytree->entries[0].userdata = userdata;
		mytree->entries[0].deleted = 0;
	}
	else {
		n = binsearch(mytree, key);

		if ((n >= 0) && (n < mytree->treesz) && (mytree->compare(key, mytree->entries[n].key) == 0)) {
			/* Record already exists */

			if (mytree->entries[n].deleted != 0) {
				/* Revive the old record. Note that we can now discard our privately held key */
				free(mytree->entries[n].key);

				mytree->entries[n].key = key;
				mytree->entries[n].deleted = 0;
				mytree->entries[n].userdata = userdata;
				return XTREE_STATUS_OK;
			}
			else {
				/* Error */
				return XTREE_STATUS_DUPLICATE_KEY;
			}
		}

		/* Must create new record */
		if (mytree->compare(key, mytree->entries[mytree->treesz - 1].key) > 0) {
			/* Add after all the others */
			mytree->entries = (treerec_t *)realloc(mytree->entries, (1 + mytree->treesz)*sizeof(treerec_t));
			mytree->entries[mytree->treesz].key = key;
			mytree->entries[mytree->treesz].userdata = userdata;
			mytree->entries[mytree->treesz].deleted = 0;
		}
		else if (mytree->compare(key, mytree->entries[0].key) < 0) {
			/* Add before all the others */
			treerec_t *newents = (treerec_t *)malloc((1 + mytree->treesz)*sizeof(treerec_t));
			newents[0].key = key;
			newents[0].userdata = userdata;
			newents[0].deleted = 0;
			memcpy(&(newents[1]), &(mytree->entries[0]), (mytree->treesz * sizeof(treerec_t)));
			free(mytree->entries);
			mytree->entries = newents;
		}
		else {
			treerec_t *newents;

			n = binsearch(mytree, key);
			if (mytree->compare(mytree->entries[n].key, key) < 0) n++;

			/* 
			 * n now points to the record AFTER where we will insert data in the current list.
			 * So in the new list, the new record will be in position n.
			 * Check if this is a deleted record, if it is then we won't have to move anything.
			 */
			if (mytree->entries[n].deleted != 0) {
				/* Deleted record, let's re-use it. */
				free(mytree->entries[n].key);
				mytree->entries[n].key = key;
				mytree->entries[n].userdata = userdata;
				mytree->entries[n].deleted = 0;
				return XTREE_STATUS_OK;
			}

			/* Ok, must create a new list and copy entries there */
			newents = (treerec_t *)malloc((1 + mytree->treesz)*sizeof(treerec_t));

			/* Copy record 0..(n-1), i.e. n records */
			memcpy(&(newents[0]), &(mytree->entries[0]), n*sizeof(treerec_t));

			/* New record is the n'th record */
			newents[n].key = key;
			newents[n].userdata = userdata;
			newents[n].deleted = 0;

			/* Finally, copy records n..(treesz-1) from the old list to position (n+1) onwards in the new list */
			memcpy(&(newents[n+1]), &(mytree->entries[n]), (mytree->treesz - n)*sizeof(treerec_t));

			free(mytree->entries);
			mytree->entries = newents;
		}
	}

	mytree->treesz += 1;
	return XTREE_STATUS_OK;
}

void *xtreeDelete(void *treehandle, char *key)
{
	xtree_t *mytree = (xtree_t *)treehandle;
	xtreePos_t n;

	if (treehandle == NULL) return NULL;
	if (mytree->treesz == 0) return NULL;	/* Empty tree */

	n = binsearch(mytree, key);

	if ((n >= 0) && (n < mytree->treesz) && (mytree->entries[n].deleted == 0) && (mytree->compare(key, mytree->entries[n].key) == 0)) {
		mytree->entries[n].key = strdup(mytree->entries[n].key); /* Must dup the key, since user may discard it */
		mytree->entries[n].deleted = 1;
		return mytree->entries[n].userdata;
	}

	return NULL;
}
#endif


#ifdef STANDALONE
#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-result"
#endif  // __GNUC__

int main(int argc, char **argv)
{
	char buf[1024], key[1024], data[1024];
	void *th = NULL;
	xtreePos_t n;
	xtreeStatus_t stat;
	char *rec, *p;

	do {
		printf("New, Add, Find, Delete, dUmp, deStroy : "); fflush(stdout);
		if (fgets(buf, sizeof(buf), stdin) == NULL) return 0;

		switch (*buf) {
		  case 'N': case 'n':
			th = xtreeNew(strcasecmp);
			break;

		  case 'A': case 'a':
			printf("Key:");fflush(stdout); fgets(key, sizeof(key), stdin);
			p = strchr(key, '\n'); if (p) *p = '\0';
			printf("Data:");fflush(stdout); fgets(data, sizeof(data), stdin);
			p = strchr(data, '\n'); if (p) *p = '\0';
			stat = xtreeAdd(th, strdup(key), strdup(data));
			printf("Result: %d\n", stat);
			break;

		  case 'D': case 'd':
			printf("Key:");fflush(stdout); fgets(key, sizeof(key), stdin);
			p = strchr(key, '\n'); if (p) *p = '\0';
			rec = xtreeDelete(th, key);
			if (rec) {
				printf("Existing record deleted: Data was '%s'\n", rec);
			}
			else {
				printf("No record\n");
			}
			break;

		  case 'F': case 'f':
			printf("Key:");fflush(stdout); fgets(key, sizeof(key), stdin);
			p = strchr(key, '\n'); if (p) *p = '\0';
			n = xtreeFind(th, key);
			if (n != xtreeEnd(th)) {
				printf("Found record: Data was '%s'\n", (char *)xtreeData(th, n));
			}
			else {
				printf("No record\n");
			}
			break;

		  case 'U': case 'u':
			n = xtreeFirst(th);
			while (n != xtreeEnd(th)) {
				printf("Key '%s', data '%s'\n", (char *)xtreeKey(th, n), (char *)xtreeData(th, n));
				n = xtreeNext(th, n);
			}
			break;

		  case 'S': case 's':
			xtreeDestroy(th);
			th = NULL;
			break;
		}
	} while (1);

	return 0;
}
#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
#pragma GCC diagnostic pop
#endif  // __GNUC__
#endif