#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: tsearch.c,v 1.7 2012/06/25 22:32:45 abs Exp $");
#endif
#include <assert.h>
#define _SEARCH_PRIVATE
#include <search.h>
#include <stdlib.h>
void *
tsearch(const void *vkey, void **vrootp,
int (*compar)(const void *, const void *))
{
node_t *q;
node_t **rootp = (node_t **)vrootp;
_DIAGASSERT(vkey != NULL);
_DIAGASSERT(compar != NULL);
if (rootp == NULL)
return NULL;
while (*rootp != NULL) {
int r;
if ((r = (*compar)(vkey, (*rootp)->key)) == 0)
return *rootp;
rootp = (r < 0) ?
&(*rootp)->llink :
&(*rootp)->rlink;
}
q = malloc(sizeof(node_t));
if (q != 0) {
*rootp = q;
q->key = __UNCONST(vkey);
q->llink = q->rlink = NULL;
}
return q;
}