]> git.ozlabs.org Git - ccan/blob - ccan/sparse_bsearch/sparse_bsearch.h
Add licences/ dir and symlinks for a bit more clarity.
[ccan] / ccan / sparse_bsearch / sparse_bsearch.h
1 #ifndef SPARSE_BSEARCH_H
2 #define SPARSE_BSEARCH_H
3 #include <stdbool.h>
4 #include <stdlib.h>
5 #include <ccan/typesafe_cb/typesafe_cb.h>
6 #include <ccan/check_type/check_type.h>
7
8 /**
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.
15  *
16  * Binary search of a sorted array, which may have some invalid entries.
17  *
18  * Example:
19  *      static bool val_valid(unsigned int *val)
20  *      {
21  *              return *val != 0;
22  *      }
23  *      static int val_cmp(const unsigned int *a, const unsigned int *b)
24  *      {
25  *              return (int)((*a) - (*b));
26  *      }
27  *      static unsigned int values[] = { 1, 7, 11, 1235, 99999 };
28  *
29  *      // Return true if this value is in set, and remove it.
30  *      bool remove_from_values(unsigned int val)
31  *      {
32  *              unsigned int *p;
33  *              p = sparse_bsearch(&val, values, 5, val_cmp, val_valid);
34  *              if (!p)
35  *                      return false;
36  *              *p = 0;
37  *              return true;
38  *      }
39  */
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)))
45
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 */