asearch.h 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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. * 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. typesafe_cb_cast(int (*)(const void *, const void *), \
  27. int (*)(const __typeof__(*(key)) *, \
  28. const __typeof__(*(base)) *), \
  29. (cmp)))))
  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. #endif /* CCAN_ASEARCH_H */