Skip to content

Commit

Permalink
include: kernel.h: port find_closest() from Linux
Browse files Browse the repository at this point in the history
The find_closest() macro can be used to find an element in a sorted
array that is closest to an input value. Bring in this macro from
Linux v6.3-rc1-2-g8ca09d5fa354.

Signed-off-by: Chris Packham <[email protected]>
Reviewed-by: Simon Glass <[email protected]>
  • Loading branch information
cpackham authored and trini committed Mar 30, 2023
1 parent d87bdb8 commit b5f045e
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions include/linux/kernel.h
Original file line number Diff line number Diff line change
Expand Up @@ -284,4 +284,28 @@
offsetof(struct structure, member) == (offset), \
"`struct " #structure "` offset for `" #member "` is not " #offset)

#define __find_closest(x, a, as, op) \
({ \
typeof(as) __fc_i, __fc_as = (as) - 1; \
typeof(x) __fc_x = (x); \
typeof(*a) const *__fc_a = (a); \
for (__fc_i = 0; __fc_i < __fc_as; __fc_i++) { \
if (__fc_x op DIV_ROUND_CLOSEST(__fc_a[__fc_i] + \
__fc_a[__fc_i + 1], 2)) \
break; \
} \
(__fc_i); \
})

/**
* find_closest - locate the closest element in a sorted array
* @x: The reference value.
* @a: The array in which to look for the closest element. Must be sorted
* in ascending order.
* @as: Size of 'a'.
*
* Returns the index of the element closest to 'x'.
*/
#define find_closest(x, a, as) __find_closest(x, a, as, <=)

#endif

0 comments on commit b5f045e

Please sign in to comment.