1*f14fb602SLionel Sambuc /* $NetBSD: tsearch.c,v 1.7 2012/06/25 22:32:45 abs Exp $ */
22fe8fb19SBen Gras
32fe8fb19SBen Gras /*
42fe8fb19SBen Gras * Tree search generalized from Knuth (6.2.2) Algorithm T just like
52fe8fb19SBen Gras * the AT&T man page says.
62fe8fb19SBen Gras *
72fe8fb19SBen Gras * The node_t structure is for internal use only, lint doesn't grok it.
82fe8fb19SBen Gras *
92fe8fb19SBen Gras * Written by reading the System V Interface Definition, not the code.
102fe8fb19SBen Gras *
112fe8fb19SBen Gras * Totally public domain.
122fe8fb19SBen Gras */
132fe8fb19SBen Gras
142fe8fb19SBen Gras #include <sys/cdefs.h>
152fe8fb19SBen Gras #if defined(LIBC_SCCS) && !defined(lint)
16*f14fb602SLionel Sambuc __RCSID("$NetBSD: tsearch.c,v 1.7 2012/06/25 22:32:45 abs Exp $");
172fe8fb19SBen Gras #endif /* LIBC_SCCS and not lint */
182fe8fb19SBen Gras
192fe8fb19SBen Gras #include <assert.h>
202fe8fb19SBen Gras #define _SEARCH_PRIVATE
212fe8fb19SBen Gras #include <search.h>
222fe8fb19SBen Gras #include <stdlib.h>
232fe8fb19SBen Gras
242fe8fb19SBen Gras /* find or insert datum into search tree */
252fe8fb19SBen Gras void *
tsearch(const void * vkey,void ** vrootp,int (* compar)(const void *,const void *))26*f14fb602SLionel Sambuc tsearch(const void *vkey, void **vrootp,
27*f14fb602SLionel Sambuc int (*compar)(const void *, const void *))
282fe8fb19SBen Gras {
292fe8fb19SBen Gras node_t *q;
302fe8fb19SBen Gras node_t **rootp = (node_t **)vrootp;
312fe8fb19SBen Gras
322fe8fb19SBen Gras _DIAGASSERT(vkey != NULL);
332fe8fb19SBen Gras _DIAGASSERT(compar != NULL);
342fe8fb19SBen Gras
352fe8fb19SBen Gras if (rootp == NULL)
362fe8fb19SBen Gras return NULL;
372fe8fb19SBen Gras
382fe8fb19SBen Gras while (*rootp != NULL) { /* Knuth's T1: */
392fe8fb19SBen Gras int r;
402fe8fb19SBen Gras
412fe8fb19SBen Gras if ((r = (*compar)(vkey, (*rootp)->key)) == 0) /* T2: */
422fe8fb19SBen Gras return *rootp; /* we found it! */
432fe8fb19SBen Gras
442fe8fb19SBen Gras rootp = (r < 0) ?
452fe8fb19SBen Gras &(*rootp)->llink : /* T3: follow left branch */
462fe8fb19SBen Gras &(*rootp)->rlink; /* T4: follow right branch */
472fe8fb19SBen Gras }
482fe8fb19SBen Gras
492fe8fb19SBen Gras q = malloc(sizeof(node_t)); /* T5: key not found */
502fe8fb19SBen Gras if (q != 0) { /* make new node */
512fe8fb19SBen Gras *rootp = q; /* link new node to old */
522fe8fb19SBen Gras q->key = __UNCONST(vkey); /* initialize new node */
532fe8fb19SBen Gras q->llink = q->rlink = NULL;
542fe8fb19SBen Gras }
552fe8fb19SBen Gras return q;
562fe8fb19SBen Gras }
57