1 #ifndef SPARSE_BSEARCH_H
2 #define SPARSE_BSEARCH_H
5 #include <ccan/typesafe_cb/typesafe_cb.h>
6 #include <ccan/check_type/check_type.h>
9 * sparse_bsearch - binary search of a sorted array with gaps.
10 * @key: the key to search for
11 * @base: the head of the array
12 * @nmemb: the number of elements in the array
13 * @cmpfn: the compare function (qsort/bsearch style)
14 * @validfn: whether this element is valid.
16 * Binary search of a sorted array, which may have some invalid entries.
19 * static bool val_valid(unsigned int *val)
23 * static int val_cmp(const unsigned int *a, const unsigned int *b)
25 * return (int)((*a) - (*b));
27 * static unsigned int values[] = { 1, 7, 11, 1235, 99999 };
29 * // Return true if this value is in set, and remove it.
30 * static bool remove_from_values(unsigned int val)
33 * p = sparse_bsearch(&val, values, 5, val_cmp, val_valid);
40 #define sparse_bsearch(key, base, nmemb, cmpfn, validfn) \
41 _sparse_bsearch((key)+check_types_match((key), &(base)[0]), \
42 (base), (nmemb), sizeof((base)[0]), \
43 typesafe_cb_cmp(int, (cmpfn), (base)), \
44 typesafe_cb_const(bool, (validfn), (base)))
46 void *_sparse_bsearch(const void *key, const void *base,
47 size_t nmemb, size_t size,
48 int (*cmpfn)(const void *, const void *),
49 bool (*validfn)(const void *));
50 #endif /* SPARSE_BSEARCH_H */