xref: /freebsd/lib/libc/stdlib/lsearch.c (revision 5ca8e32633c4ffbbcd6762e5888b6a4ba0708c6c)
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 #define	_SEARCH_PRIVATE
11 #include <search.h>
12 #include <stdint.h>	/* for uint8_t */
13 #include <stdlib.h>	/* for NULL */
14 #include <string.h>	/* for memcpy() prototype */
15 
16 static void *lwork(const void *, const void *, size_t *, size_t,
17     int (*)(const void *, const void *), int);
18 
19 void *lsearch(const void *key, void *base, size_t *nelp, size_t width,
20     int (*compar)(const void *, const void *))
21 {
22 
23 	return (lwork(key, base, nelp, width, compar, 1));
24 }
25 
26 void *lfind(const void *key, const void *base, size_t *nelp, size_t width,
27     int (*compar)(const void *, const void *))
28 {
29 
30 	return (lwork(key, base, nelp, width, compar, 0));
31 }
32 
33 static void *
34 lwork(const void *key, const void *base, size_t *nelp, size_t width,
35     int (*compar)(const void *, const void *), int addelem)
36 {
37 	uint8_t *ep, *endp;
38 
39 	ep = __DECONST(uint8_t *, base);
40 	for (endp = (uint8_t *)(ep + width * *nelp); ep < endp; ep += width) {
41 		if (compar(key, ep) == 0)
42 			return (ep);
43 	}
44 
45 	/* lfind() shall return when the key was not found. */
46 	if (!addelem)
47 		return (NULL);
48 
49 	/*
50 	 * lsearch() adds the key to the end of the table and increments
51 	 * the number of elements.
52 	 */
53 	memcpy(endp, key, width);
54 	++*nelp;
55 
56 	return (endp);
57 }
58