]> git.ozlabs.org Git - ccan/blob - ccan/asearch/asearch.h
gitify the tree, especially the web makefile.
[ccan] / ccan / asearch / asearch.h
1 #ifndef CCAN_ASEARCH_H
2 #define CCAN_ASEARCH_H
3 #include <stdlib.h>
4 #include <ccan/typesafe_cb/typesafe_cb.h>
5
6 /**
7  * asearch - search an array of elements
8  * @key: pointer to item being searched for
9  * @base: pointer to data to sort
10  * @num: number of elements
11  * @cmp: pointer to comparison function
12  *
13  * This function does a binary search on the given array.  The
14  * contents of the array should already be in ascending sorted order
15  * under the provided comparison function.
16  *
17  * Note that the key need not have the same type as the elements in
18  * the array, e.g. key could be a string and the comparison function
19  * could compare the string with the struct's name field.  However, if
20  * the key and elements in the array are of the same type, you can use
21  * the same comparison function for both sort() and asearch().
22  */
23 #if HAVE_TYPEOF
24 #define asearch(key, base, num, cmp)                                    \
25         ((__typeof__(*(base))*)(bsearch((key), (base), (num), sizeof(*(base)), \
26                 cast_if_type(int (*)(const void *, const void *),       \
27                              (cmp), &*(cmp),                            \
28                              int (*)(const __typeof__(*(key)) *,        \
29                                      const __typeof__(*(base)) *)))))
30 #else
31 #define asearch(key, base, num, cmp)                            \
32         (bsearch((key), (base), (num), sizeof(*(base)),         \
33                  (int (*)(const void *, const void *))(cmp)))
34 #endif
35
36 #endif /* CCAN_ASEARCH_H */