1 /* Licensed under LGPLv2.1+ - see LICENSE file for details */
5 #include <ccan/typesafe_cb/typesafe_cb.h>
7 typedef int (*asearch_cmp)(const void *, const void *, void *);
10 * asearch - search an array of elements
11 * @key: pointer to item being searched for
12 * @base: pointer to data to sort
13 * @num: number of elements
14 * @cmp: pointer to comparison function
16 * This function does a binary search on the given array. The
17 * contents of the array should already be in ascending sorted order
18 * under the provided comparison function.
20 * Note that the key need not have the same type as the elements in
21 * the array, e.g. key could be a string and the comparison function
22 * could compare the string with the struct's name field. However, if
23 * the key and elements in the array are of the same type, you can use
24 * the same comparison function for both sort() and asearch().
27 #define asearch(key, base, num, cmp, ctx) \
28 ((__typeof__(*(base))*)(_asearch((key), (base), (num), sizeof(*(base)), \
29 typesafe_cb_cast(asearch_cmp, \
30 int (*)(const __typeof__(*(key)) *, \
31 const __typeof__(*(base)) *, \
32 __typeof__(*(ctx)) *), \
36 #define asearch(key, base, num, cmp, ctx) \
37 (_asearch((key), (base), (num), sizeof(*(base)), \
38 (int (*)(const void *, const void *, void *))(cmp), (ctx)))
41 void *_asearch(const void *key, const void *base,
42 size_t nmemb, size_t size,
43 asearch_cmp compar, void *ctx);
45 #endif /* CCAN_ASEARCH_H */