xref: /netbsd-src/lib/libc/stdlib/tsearch.c (revision 9e66e6d75e9910b3de5f4ef031995955f69a7dd1)
1*9e66e6d7Sabs /*	$NetBSD: tsearch.c,v 1.7 2012/06/25 22:32:45 abs Exp $	*/
27975455dSchristos 
37975455dSchristos /*
47975455dSchristos  * Tree search generalized from Knuth (6.2.2) Algorithm T just like
57975455dSchristos  * the AT&T man page says.
67975455dSchristos  *
77975455dSchristos  * The node_t structure is for internal use only, lint doesn't grok it.
87975455dSchristos  *
97975455dSchristos  * Written by reading the System V Interface Definition, not the code.
107975455dSchristos  *
117975455dSchristos  * Totally public domain.
127975455dSchristos  */
137975455dSchristos 
147975455dSchristos #include <sys/cdefs.h>
157975455dSchristos #if defined(LIBC_SCCS) && !defined(lint)
16*9e66e6d7Sabs __RCSID("$NetBSD: tsearch.c,v 1.7 2012/06/25 22:32:45 abs Exp $");
177975455dSchristos #endif /* LIBC_SCCS and not lint */
187975455dSchristos 
19b48252f3Slukem #include <assert.h>
207975455dSchristos #define _SEARCH_PRIVATE
217975455dSchristos #include <search.h>
227975455dSchristos #include <stdlib.h>
237975455dSchristos 
247975455dSchristos /* find or insert datum into search tree */
257975455dSchristos void *
tsearch(const void * vkey,void ** vrootp,int (* compar)(const void *,const void *))26*9e66e6d7Sabs tsearch(const void *vkey, void **vrootp,
27*9e66e6d7Sabs     int (*compar)(const void *, const void *))
287975455dSchristos {
297975455dSchristos 	node_t *q;
307975455dSchristos 	node_t **rootp = (node_t **)vrootp;
317975455dSchristos 
32b48252f3Slukem 	_DIAGASSERT(vkey != NULL);
33b48252f3Slukem 	_DIAGASSERT(compar != NULL);
34b48252f3Slukem 
357975455dSchristos 	if (rootp == NULL)
367975455dSchristos 		return NULL;
377975455dSchristos 
387975455dSchristos 	while (*rootp != NULL) {	/* Knuth's T1: */
397975455dSchristos 		int r;
407975455dSchristos 
417975455dSchristos 		if ((r = (*compar)(vkey, (*rootp)->key)) == 0)	/* T2: */
427975455dSchristos 			return *rootp;		/* we found it! */
437975455dSchristos 
447975455dSchristos 		rootp = (r < 0) ?
457975455dSchristos 		    &(*rootp)->llink :		/* T3: follow left branch */
467975455dSchristos 		    &(*rootp)->rlink;		/* T4: follow right branch */
477975455dSchristos 	}
487975455dSchristos 
497975455dSchristos 	q = malloc(sizeof(node_t));		/* T5: key not found */
507975455dSchristos 	if (q != 0) {				/* make new node */
517975455dSchristos 		*rootp = q;			/* link new node to old */
5203256c6eSchristos 		q->key = __UNCONST(vkey);	/* initialize new node */
537975455dSchristos 		q->llink = q->rlink = NULL;
547975455dSchristos 	}
557975455dSchristos 	return q;
567975455dSchristos }
57