xref: /original-bsd/lib/libcompat/4.3/lsearch.c (revision c3e32dec)
1 /*
2  * Copyright (c) 1989, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Roger L. Snyder.
7  *
8  * %sccs.include.redist.c%
9  */
10 
11 #if defined(LIBC_SCCS) && !defined(lint)
12 static char sccsid[] = "@(#)lsearch.c	8.1 (Berkeley) 06/04/93";
13 #endif /* LIBC_SCCS and not lint */
14 
15 #include <sys/types.h>
16 #include <unistd.h>
17 
18 static char *linear_base();
19 
20 char *
21 lsearch(key, base, nelp, width, compar)
22 	char *key, *base;
23 	u_int *nelp, width;
24 	int (*compar)();
25 {
26 	return(linear_base(key, base, nelp, width, compar, 1));
27 }
28 
29 char *
30 lfind(key, base, nelp, width, compar)
31 	char *key, *base;
32 	u_int *nelp, width;
33 	int (*compar)();
34 {
35 	return(linear_base(key, base, nelp, width, compar, 0));
36 }
37 
38 static char *
39 linear_base(key, base, nelp, width, compar, add_flag)
40 	char *key, *base;
41 	u_int *nelp, width;
42 	int (*compar)(), add_flag;
43 {
44 	register char *element, *end;
45 
46 	end = base + *nelp * width;
47 	for (element = base; element < end; element += width)
48 		if (!compar(element, key))		/* key found */
49 			return(element);
50 
51 	if (!add_flag)					/* key not found */
52 		return(NULL);
53 
54 	/*
55 	 * The UNIX System User's Manual, 1986 edition claims that
56 	 * a NULL pointer is returned by lsearch with errno set
57 	 * appropriately, if there is not enough room in the table
58 	 * to add a new item.  This can't be done as none of these
59 	 * routines have any method of determining the size of the
60 	 * table.  This comment was isn't in the 1986-87 System V
61 	 * manual.
62 	 */
63 	++*nelp;
64 	bcopy(key, end, (int)width);
65 	return(end);
66 }
67