1105250Srobert/* 2105250Srobert * Initial implementation: 3105250Srobert * Copyright (c) 2002 Robert Drehmel 4105250Srobert * All rights reserved. 5105250Srobert * 6105250Srobert * As long as the above copyright statement and this notice remain 7105250Srobert * unchanged, you can do what ever you want with this file. 8105250Srobert */ 9105250Srobert#include <sys/types.h> 10105250Srobert#include <sys/cdefs.h> 11105250Srobert__FBSDID("$FreeBSD$"); 12105250Srobert 13105250Srobert#define _SEARCH_PRIVATE 14105250Srobert#include <search.h> 15105250Srobert#include <stdint.h> /* for uint8_t */ 16105250Srobert#include <stdlib.h> /* for NULL */ 17105250Srobert#include <string.h> /* for memcpy() prototype */ 18105250Srobert 19105250Srobertstatic void *lwork(const void *, const void *, size_t *, size_t, 20105250Srobert int (*)(const void *, const void *), int); 21105250Srobert 22105250Srobertvoid *lsearch(const void *key, void *base, size_t *nelp, size_t width, 23105250Srobert int (*compar)(const void *, const void *)) 24105250Srobert{ 25105250Srobert 26105250Srobert return (lwork(key, base, nelp, width, compar, 1)); 27105250Srobert} 28105250Srobert 29105250Srobertvoid *lfind(const void *key, const void *base, size_t *nelp, size_t width, 30105250Srobert int (*compar)(const void *, const void *)) 31105250Srobert{ 32105250Srobert 33105250Srobert return (lwork(key, base, nelp, width, compar, 0)); 34105250Srobert} 35105250Srobert 36105250Srobertstatic void * 37105250Srobertlwork(const void *key, const void *base, size_t *nelp, size_t width, 38105250Srobert int (*compar)(const void *, const void *), int addelem) 39105250Srobert{ 40105250Srobert uint8_t *ep, *endp; 41105250Srobert 42105250Srobert /* 43105250Srobert * Cast to an integer value first to avoid the warning for removing 44105250Srobert * 'const' via a cast. 45105250Srobert */ 46105250Srobert ep = (uint8_t *)(uintptr_t)base; 47105250Srobert for (endp = (uint8_t *)(ep + width * *nelp); ep < endp; ep += width) { 48105250Srobert if (compar(key, ep) == 0) 49105250Srobert return (ep); 50105250Srobert } 51105250Srobert 52105250Srobert /* lfind() shall return when the key was not found. */ 53105250Srobert if (!addelem) 54105250Srobert return (NULL); 55105250Srobert 56105250Srobert /* 57105250Srobert * lsearch() adds the key to the end of the table and increments 58105250Srobert * the number of elements. 59105250Srobert */ 60105250Srobert memcpy(endp, key, width); 61105250Srobert ++*nelp; 62105250Srobert 63105250Srobert return (endp); 64105250Srobert} 65