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