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
42273614Sbrooks	ep = __DECONST(uint8_t *, base);
43105250Srobert	for (endp = (uint8_t *)(ep + width * *nelp); ep < endp; ep += width) {
44105250Srobert		if (compar(key, ep) == 0)
45105250Srobert			return (ep);
46105250Srobert	}
47105250Srobert
48105250Srobert	/* lfind() shall return when the key was not found. */
49105250Srobert	if (!addelem)
50105250Srobert		return (NULL);
51105250Srobert
52105250Srobert	/*
53105250Srobert	 * lsearch() adds the key to the end of the table and increments
54105250Srobert	 * the number of elements.
55105250Srobert	 */
56105250Srobert	memcpy(endp, key, width);
57105250Srobert	++*nelp;
58105250Srobert
59105250Srobert	return (endp);
60105250Srobert}
61