]> git.ozlabs.org Git - ccan/blob - ccan/asearch/asearch.c
base64: fix for unsigned chars (e.g. ARM).
[ccan] / ccan / asearch / asearch.c
1 #include <ccan/asearch/asearch.h>
2
3 #include <stddef.h>
4
5 /* Steal glibc's code. */
6
7 /* Perform binary search - inline version.
8    Copyright (C) 1991-2015 Free Software Foundation, Inc.
9    This file is part of the GNU C Library.
10
11    The GNU C Library is free software; you can redistribute it and/or
12    modify it under the terms of the GNU Lesser General Public
13    License as published by the Free Software Foundation; either
14    version 2.1 of the License, or (at your option) any later version.
15
16    The GNU C Library is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19    Lesser General Public License for more details.
20
21    You should have received a copy of the GNU Lesser General Public
22    License along with the GNU C Library; if not, see
23    <http://www.gnu.org/licenses/>.  */
24
25 void *
26 _asearch (const void *__key, const void *__base, size_t __nmemb, size_t __size,
27           asearch_cmp __compar, void *ctx)
28 {
29   size_t __l, __u, __idx;
30   const void *__p;
31   int __comparison;
32
33   __l = 0;
34   __u = __nmemb;
35   while (__l < __u)
36     {
37       __idx = (__l + __u) / 2;
38       __p = (void *) (((const char *) __base) + (__idx * __size));
39       __comparison = (*__compar) (__key, __p, ctx);
40       if (__comparison < 0)
41         __u = __idx;
42       else if (__comparison > 0)
43         __l = __idx + 1;
44       else
45         return (void *) __p;
46     }
47
48   return NULL;
49 }