Home | History | Annotate | Line # | Download | only in stdlib
tfind.c revision 1.5
      1  1.5    kleink /*	$NetBSD: tfind.c,v 1.5 2005/03/23 08:16:53 kleink Exp $	*/
      2  1.1  christos 
      3  1.1  christos /*
      4  1.1  christos  * Tree search generalized from Knuth (6.2.2) Algorithm T just like
      5  1.1  christos  * the AT&T man page says.
      6  1.1  christos  *
      7  1.1  christos  * The node_t structure is for internal use only, lint doesn't grok it.
      8  1.1  christos  *
      9  1.1  christos  * Written by reading the System V Interface Definition, not the code.
     10  1.1  christos  *
     11  1.1  christos  * Totally public domain.
     12  1.1  christos  */
     13  1.1  christos 
     14  1.1  christos #include <sys/cdefs.h>
     15  1.1  christos #if defined(LIBC_SCCS) && !defined(lint)
     16  1.5    kleink __RCSID("$NetBSD: tfind.c,v 1.5 2005/03/23 08:16:53 kleink Exp $");
     17  1.1  christos #endif /* LIBC_SCCS and not lint */
     18  1.1  christos 
     19  1.2     lukem #include <assert.h>
     20  1.1  christos #define _SEARCH_PRIVATE
     21  1.1  christos #include <stdlib.h>
     22  1.1  christos #include <search.h>
     23  1.1  christos 
     24  1.1  christos /* find a node, or return 0 */
     25  1.1  christos void *
     26  1.1  christos tfind(vkey, vrootp, compar)
     27  1.1  christos 	const void *vkey;		/* key to be found */
     28  1.4    kleink 	void * const *vrootp;		/* address of the tree root */
     29  1.1  christos 	int (*compar) __P((const void *, const void *));
     30  1.1  christos {
     31  1.5    kleink 	node_t * const *rootp = (node_t * const*)vrootp;
     32  1.2     lukem 
     33  1.2     lukem 	_DIAGASSERT(vkey != NULL);
     34  1.2     lukem 	_DIAGASSERT(compar != NULL);
     35  1.1  christos 
     36  1.1  christos 	if (rootp == NULL)
     37  1.1  christos 		return NULL;
     38  1.1  christos 
     39  1.1  christos 	while (*rootp != NULL) {		/* T1: */
     40  1.1  christos 		int r;
     41  1.1  christos 
     42  1.1  christos 		if ((r = (*compar)(vkey, (*rootp)->key)) == 0)	/* T2: */
     43  1.1  christos 			return *rootp;		/* key found */
     44  1.1  christos 		rootp = (r < 0) ?
     45  1.1  christos 		    &(*rootp)->llink :		/* T3: follow left branch */
     46  1.1  christos 		    &(*rootp)->rlink;		/* T4: follow right branch */
     47  1.1  christos 	}
     48  1.1  christos 	return NULL;
     49  1.1  christos }
     50