OSDN Git Service

a348f0e35cabe124cde900e03d1f02b6df7c8313
[pf3gnuchains/pf3gnuchains3x.git] / winsup / cygwin / lsearch.cc
1 /* Initial implementation:
2    Copyright (c) 2002 Robert Drehmel
3    All rights reserved.
4
5    As long as the above copyright statement and this notice remain
6    unchanged, you can do what ever you want with this file.  */
7
8 #include <sys/types.h>
9 #include <sys/cdefs.h>
10 #include <search.h>
11 #include <stdint.h>     /* for uint8_t */
12 #include <stdlib.h>     /* for NULL */
13 #include <string.h>     /* for memcpy () prototype */
14
15 static void *lwork (const void *, const void *, size_t *, size_t,
16                     int (*) (const void *, const void *), int);
17
18 extern "C" void *
19 lsearch (const void *key, void *base, size_t *nelp, size_t width,
20                int (*compar) (const void *, const void *))
21 {
22   return lwork (key, base, nelp, width, compar, 1);
23 }
24
25 extern "C" void *
26 lfind (const void *key, const void *base, size_t *nelp, size_t width,
27              int (*compar) (const void *, const void *))
28 {
29   return lwork (key, base, nelp, width, compar, 0);
30 }
31
32 static void *
33 lwork (const void *key, const void *base, size_t *nelp, size_t width,
34        int (*compar) (const void *, const void *), int addelem)
35 {
36   uint8_t *ep, *endp;
37
38   /*  Cast to an integer value first to avoid the warning for removing
39      'const' via a cast.  */
40   ep = (uint8_t *) (uintptr_t)base;
41   for (endp = (uint8_t *) (ep + width * *nelp); ep < endp; ep += width)
42     if (compar (key, ep) == 0)
43       return ep;
44
45   /* lfind () shall return when the key was not found. */
46   if (!addelem)
47     return NULL;
48
49   /* lsearch () adds the key to the end of the table and increments
50      the number of elements.  */
51   memcpy (endp, key, width);
52   ++*nelp;
53
54   return endp;
55 }