lsearch.c revision 105250
1247738Sbapt/* 2247738Sbapt * Initial implementation: 3247738Sbapt * Copyright (c) 2002 Robert Drehmel 4247738Sbapt * All rights reserved. 5247738Sbapt * 6247738Sbapt * As long as the above copyright statement and this notice remain 7247738Sbapt * unchanged, you can do what ever you want with this file. 8247738Sbapt */ 9247738Sbapt#include <sys/types.h> 10247738Sbapt#include <sys/cdefs.h> 11247738Sbapt__FBSDID("$FreeBSD: head/lib/libc/stdlib/lsearch.c 105250 2002-10-16 14:29:23Z robert $"); 12247738Sbapt 13247738Sbapt#define _SEARCH_PRIVATE 14247738Sbapt#include <search.h> 15247738Sbapt#include <stdint.h> /* for uint8_t */ 16247738Sbapt#include <stdlib.h> /* for NULL */ 17247738Sbapt#include <string.h> /* for memcpy() prototype */ 18247738Sbapt 19247738Sbaptstatic void *lwork(const void *, const void *, size_t *, size_t, 20247738Sbapt int (*)(const void *, const void *), int); 21247738Sbapt 22247738Sbaptvoid *lsearch(const void *key, void *base, size_t *nelp, size_t width, 23247738Sbapt int (*compar)(const void *, const void *)) 24247738Sbapt{ 25247738Sbapt 26247738Sbapt return (lwork(key, base, nelp, width, compar, 1)); 27247738Sbapt} 28247738Sbapt 29247738Sbaptvoid *lfind(const void *key, const void *base, size_t *nelp, size_t width, 30247738Sbapt int (*compar)(const void *, const void *)) 31247738Sbapt{ 32247738Sbapt 33247738Sbapt return (lwork(key, base, nelp, width, compar, 0)); 34247738Sbapt} 35247738Sbapt 36247738Sbaptstatic void * 37247738Sbaptlwork(const void *key, const void *base, size_t *nelp, size_t width, 38247738Sbapt int (*compar)(const void *, const void *), int addelem) 39247738Sbapt{ 40247738Sbapt uint8_t *ep, *endp; 41247738Sbapt 42247738Sbapt /* 43247738Sbapt * Cast to an integer value first to avoid the warning for removing 44247738Sbapt * 'const' via a cast. 45247738Sbapt */ 46247738Sbapt ep = (uint8_t *)(uintptr_t)base; 47247738Sbapt for (endp = (uint8_t *)(ep + width * *nelp); ep < endp; ep += width) { 48247738Sbapt if (compar(key, ep) == 0) 49247738Sbapt return (ep); 50247738Sbapt } 51247738Sbapt 52247738Sbapt /* lfind() shall return when the key was not found. */ 53247738Sbapt if (!addelem) 54247738Sbapt return (NULL); 55247738Sbapt 56247738Sbapt /* 57247738Sbapt * lsearch() adds the key to the end of the table and increments 58247738Sbapt * the number of elements. 59247738Sbapt */ 60247738Sbapt memcpy(endp, key, width); 61247738Sbapt ++*nelp; 62247738Sbapt 63247738Sbapt return (endp); 64247738Sbapt} 65247738Sbapt