util_macros.h 1.2 KB

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