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