xref: /dragonfly/lib/libc/stdlib/lsearch.c (revision a361ab31)
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  * $FreeBSD: src/lib/libc/stdlib/lsearch.c,v 1.1 2002/10/16 14:29:22 robert Exp $
10  * $DragonFly: src/lib/libc/stdlib/lsearch.c,v 1.1 2008/05/19 10:06:34 corecode Exp $
11  */
12 #include <sys/types.h>
13 
14 #define	_SEARCH_PRIVATE
15 #include <search.h>
16 #include <stdint.h>	/* for uint8_t */
17 #include <stdlib.h>	/* for NULL */
18 #include <string.h>	/* for memcpy() prototype */
19 
20 static void *lwork(const void *, const void *, size_t *, size_t,
21     int (*)(const void *, const void *), int);
22 
23 void *lsearch(const void *key, void *base, size_t *nelp, size_t width,
24     int (*compar)(const void *, const void *))
25 {
26 
27 	return (lwork(key, base, nelp, width, compar, 1));
28 }
29 
30 void *lfind(const void *key, const void *base, size_t *nelp, size_t width,
31     int (*compar)(const void *, const void *))
32 {
33 
34 	return (lwork(key, base, nelp, width, compar, 0));
35 }
36 
37 static void *
38 lwork(const void *key, const void *base, size_t *nelp, size_t width,
39     int (*compar)(const void *, const void *), int addelem)
40 {
41 	uint8_t *ep, *endp;
42 
43 	/*
44 	 * Cast to an integer value first to avoid the warning for removing
45 	 * 'const' via a cast.
46 	 */
47 	ep = (uint8_t *)(uintptr_t)base;
48 	for (endp = (uint8_t *)(ep + width * *nelp); ep < endp; ep += width) {
49 		if (compar(key, ep) == 0)
50 			return (ep);
51 	}
52 
53 	/* lfind() shall return when the key was not found. */
54 	if (!addelem)
55 		return (NULL);
56 
57 	/*
58 	 * lsearch() adds the key to the end of the table and increments
59 	 * the number of elements.
60 	 */
61 	memcpy(endp, key, width);
62 	++*nelp;
63 
64 	return (endp);
65 }
66