]> git.ozlabs.org Git - ccan/blob - ccan/asearch/asearch.h
asearch: Add context pointer to asearch comparison callback
[ccan] / ccan / asearch / asearch.h
1 /* Licensed under LGPLv2.1+ - see LICENSE file for details */
2 #ifndef CCAN_ASEARCH_H
3 #define CCAN_ASEARCH_H
4 #include <stdlib.h>
5 #include <ccan/typesafe_cb/typesafe_cb.h>
6
7 typedef int (*asearch_cmp)(const void *, const void *, void *);
8
9 /**
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
15  *
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.
19  *
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().
25  */
26 #if HAVE_TYPEOF
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)) *),         \
33                                  (cmp)), (ctx))))
34
35 #else
36 #define asearch(key, base, num, cmp, ctx)                               \
37         (_asearch((key), (base), (num), sizeof(*(base)),                \
38                   (int (*)(const void *, const void *, void *))(cmp), (ctx)))
39 #endif
40
41 void *_asearch(const void *key, const void *base,
42                size_t nmemb, size_t size,
43                asearch_cmp compar, void *ctx);
44
45 #endif /* CCAN_ASEARCH_H */