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 /* 43 * Cast to an integer value first to avoid the warning for removing 44 * 'const' via a cast. 45 */ 46 ep = (uint8_t *)(uintptr_t)base; 47 for (endp = (uint8_t *)(ep + width * *nelp); ep < endp; ep += width) { 48 if (compar(key, ep) == 0) 49 return (ep); 50 } 51 52 /* lfind() shall return when the key was not found. */ 53 if (!addelem) 54 return (NULL); 55 56 /* 57 * lsearch() adds the key to the end of the table and increments 58 * the number of elements. 59 */ 60 memcpy(endp, key, width); 61 ++*nelp; 62 63 return (endp); 64 } 65