1*f14fb602SLionel Sambuc /* $NetBSD: tfind.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: tfind.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 <stdlib.h>
222fe8fb19SBen Gras #include <search.h>
232fe8fb19SBen Gras
24*f14fb602SLionel Sambuc /* find a node by key "vkey" in tree "vrootp", or return 0 */
252fe8fb19SBen Gras void *
tfind(const void * vkey,void * const * vrootp,int (* compar)(const void *,const void *))26*f14fb602SLionel Sambuc tfind(const void *vkey, void * const *vrootp,
27*f14fb602SLionel Sambuc int (*compar)(const void *, const void *))
282fe8fb19SBen Gras {
292fe8fb19SBen Gras node_t * const *rootp = (node_t * const*)vrootp;
302fe8fb19SBen Gras
312fe8fb19SBen Gras _DIAGASSERT(vkey != NULL);
322fe8fb19SBen Gras _DIAGASSERT(compar != NULL);
332fe8fb19SBen Gras
342fe8fb19SBen Gras if (rootp == NULL)
352fe8fb19SBen Gras return NULL;
362fe8fb19SBen Gras
372fe8fb19SBen Gras while (*rootp != NULL) { /* T1: */
382fe8fb19SBen Gras int r;
392fe8fb19SBen Gras
402fe8fb19SBen Gras if ((r = (*compar)(vkey, (*rootp)->key)) == 0) /* T2: */
412fe8fb19SBen Gras return *rootp; /* key found */
422fe8fb19SBen Gras rootp = (r < 0) ?
432fe8fb19SBen Gras &(*rootp)->llink : /* T3: follow left branch */
442fe8fb19SBen Gras &(*rootp)->rlink; /* T4: follow right branch */
452fe8fb19SBen Gras }
462fe8fb19SBen Gras return NULL;
472fe8fb19SBen Gras }
48