my-debug-cache_open.p
[cvsps/4msysgit.git] / tsearch / tsearch.c
blob4d03b63047103ef31186fe995520935959ac1141
1 /* $NetBSD: tsearch.c,v 1.4 1999/09/20 04:39:43 lukem Exp $ */
3 /*
4 * Tree search generalized from Knuth (6.2.2) Algorithm T just like
5 * the AT&T man page says.
7 * The node_t structure is for internal use only, lint doesn't grok it.
9 * Written by reading the System V Interface Definition, not the code.
11 * Totally public domain.
14 #include <assert.h>
15 #define _SEARCH_PRIVATE
16 #include <tsearch/search.h>
17 #include <stdlib.h>
20 /* find or insert datum into search tree */
21 void *
22 tsearch(const void * __restrict__ vkey, /* key to be located */
23 void ** __restrict__ vrootp, /* address of tree root */
24 int (*compar) (const void *, const void *))
26 node_t *q;
27 node_t **rootp = (node_t **)vrootp;
29 if (rootp == NULL)
30 return NULL;
32 while (*rootp != NULL) { /* Knuth's T1: */
33 int r;
35 if ((r = (*compar)(vkey, (*rootp)->key)) == 0) /* T2: */
36 return *rootp; /* we found it! */
38 rootp = (r < 0) ?
39 &(*rootp)->llink : /* T3: follow left branch */
40 &(*rootp)->rlink; /* T4: follow right branch */
43 q = malloc(sizeof(node_t)); /* T5: key not found */
44 if (q != 0) { /* make new node */
45 *rootp = q; /* link new node to old */
46 /* LINTED const castaway ok */
47 q->key = (void *)vkey; /* initialize new node */
48 q->llink = q->rlink = NULL;
50 return q;