File: lsearch.cc

package info (click to toggle)
libnewlib-nano 2.11.2-1
  • links: PTS
  • area: main
  • in suites: buster
  • size: 114,156 kB
  • sloc: ansic: 631,393; cpp: 129,053; makefile: 62,427; asm: 49,042; sh: 15,817; xml: 15,337; perl: 4,340; lisp: 720; python: 557; exp: 470; yacc: 315; awk: 25; tcl: 4
file content (51 lines) | stat: -rw-r--r-- 1,496 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/* Initial implementation:
   Copyright (c) 2002 Robert Drehmel
   All rights reserved.

   As long as the above copyright statement and this notice remain
   unchanged, you can do what ever you want with this file.  */

#include <stdint.h>	/* for uint8_t */
#include <string.h>	/* for memcpy () prototype */

static void *lwork (const void *, const void *, size_t *, size_t,
		    int (*) (const void *, const void *), int);

extern "C" void *
lsearch (const void *key, void *base, size_t *nelp, size_t width,
	       int (*compar) (const void *, const void *))
{
  return lwork (key, base, nelp, width, compar, 1);
}

extern "C" void *
lfind (const void *key, const void *base, size_t *nelp, size_t width,
	     int (*compar) (const void *, const void *))
{
  return lwork (key, base, nelp, width, compar, 0);
}

static void *
lwork (const void *key, const void *base, size_t *nelp, size_t width,
       int (*compar) (const void *, const void *), int addelem)
{
  uint8_t *ep, *endp;

  /*  Cast to an integer value first to avoid the warning for removing
     'const' via a cast.  */
  ep = (uint8_t *) (uintptr_t)base;
  for (endp = (uint8_t *) (ep + width * *nelp); ep < endp; ep += width)
    if (compar (key, ep) == 0)
      return ep;

  /* lfind () shall return when the key was not found. */
  if (!addelem)
    return NULL;

  /* lsearch () adds the key to the end of the table and increments
     the number of elements.  */
  memcpy (endp, key, width);
  ++*nelp;

  return endp;
}