1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "sort-util.h"
4 #include "alloc-util.h"
5
6 /* hey glibc, APIs with callbacks without a user pointer are so useless */
xbsearch_r(const void * key,const void * base,size_t nmemb,size_t size,comparison_userdata_fn_t compar,void * arg)7 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
8 comparison_userdata_fn_t compar, void *arg) {
9 size_t l, u, idx;
10 const void *p;
11 int comparison;
12
13 assert(!size_multiply_overflow(nmemb, size));
14
15 l = 0;
16 u = nmemb;
17 while (l < u) {
18 idx = (l + u) / 2;
19 p = (const uint8_t*) base + idx * size;
20 comparison = compar(key, p, arg);
21 if (comparison < 0)
22 u = idx;
23 else if (comparison > 0)
24 l = idx + 1;
25 else
26 return (void *)p;
27 }
28 return NULL;
29 }
30
cmp_int(const int * a,const int * b)31 int cmp_int(const int *a, const int *b) {
32 return CMP(*a, *b);
33 }
34