xref: /freebsd/lib/libc/stdlib/lsearch.c (revision 734e82fe33aa764367791a7d603b383996c6b40b)
1 /*
2  * Initial implementation:
3  * Copyright (c) 2002 Robert Drehmel
4  * All rights reserved.
5  *
6  * As long as the above copyright statement and this notice remain
7  * unchanged, you can do what ever you want with this file.
8  */
9 #include <sys/types.h>
10 #include <sys/cdefs.h>
11 #define	_SEARCH_PRIVATE
12 #include <search.h>
13 #include <stdint.h>	/* for uint8_t */
14 #include <stdlib.h>	/* for NULL */
15 #include <string.h>	/* for memcpy() prototype */
16 
17 static void *lwork(const void *, const void *, size_t *, size_t,
18     int (*)(const void *, const void *), int);
19 
20 void *lsearch(const void *key, void *base, size_t *nelp, size_t width,
21     int (*compar)(const void *, const void *))
22 {
23 
24 	return (lwork(key, base, nelp, width, compar, 1));
25 }
26 
27 void *lfind(const void *key, const void *base, size_t *nelp, size_t width,
28     int (*compar)(const void *, const void *))
29 {
30 
31 	return (lwork(key, base, nelp, width, compar, 0));
32 }
33 
34 static void *
35 lwork(const void *key, const void *base, size_t *nelp, size_t width,
36     int (*compar)(const void *, const void *), int addelem)
37 {
38 	uint8_t *ep, *endp;
39 
40 	ep = __DECONST(uint8_t *, base);
41 	for (endp = (uint8_t *)(ep + width * *nelp); ep < endp; ep += width) {
42 		if (compar(key, ep) == 0)
43 			return (ep);
44 	}
45 
46 	/* lfind() shall return when the key was not found. */
47 	if (!addelem)
48 		return (NULL);
49 
50 	/*
51 	 * lsearch() adds the key to the end of the table and increments
52 	 * the number of elements.
53 	 */
54 	memcpy(endp, key, width);
55 	++*nelp;
56 
57 	return (endp);
58 }
59