util_macros.h 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #ifndef _LINUX_HELPER_MACROS_H_
  2. #define _LINUX_HELPER_MACROS_H_
  3. #define __find_closest(x, a, as, op) \
  4. ({ \
  5. typeof(as) __fc_i, __fc_as = (as) - 1; \
  6. typeof(x) __fc_x = (x); \
  7. typeof(*a) const *__fc_a = (a); \
  8. for (__fc_i = 0; __fc_i < __fc_as; __fc_i++) { \
  9. if (__fc_x op DIV_ROUND_CLOSEST(__fc_a[__fc_i] + \
  10. __fc_a[__fc_i + 1], 2)) \
  11. break; \
  12. } \
  13. (__fc_i); \
  14. })
  15. /**
  16. * find_closest - locate the closest element in a sorted array
  17. * @x: The reference value.
  18. * @a: The array in which to look for the closest element. Must be sorted
  19. * in ascending order.
  20. * @as: Size of 'a'.
  21. *
  22. * Returns the index of the element closest to 'x'.
  23. */
  24. #define find_closest(x, a, as) __find_closest(x, a, as, <=)
  25. /**
  26. * find_closest_descending - locate the closest element in a sorted array
  27. * @x: The reference value.
  28. * @a: The array in which to look for the closest element. Must be sorted
  29. * in descending order.
  30. * @as: Size of 'a'.
  31. *
  32. * Similar to find_closest() but 'a' is expected to be sorted in descending
  33. * order.
  34. */
  35. #define find_closest_descending(x, a, as) __find_closest(x, a, as, >=)
  36. #endif