Back to home page

OSCL-LXR

 
 

    


0001 /* SPDX-License-Identifier: GPL-2.0 */
0002 #ifndef _LINUX_HELPER_MACROS_H_
0003 #define _LINUX_HELPER_MACROS_H_
0004 
0005 #define __find_closest(x, a, as, op)                    \
0006 ({                                  \
0007     typeof(as) __fc_i, __fc_as = (as) - 1;              \
0008     typeof(x) __fc_x = (x);                     \
0009     typeof(*a) const *__fc_a = (a);                 \
0010     for (__fc_i = 0; __fc_i < __fc_as; __fc_i++) {          \
0011         if (__fc_x op DIV_ROUND_CLOSEST(__fc_a[__fc_i] +    \
0012                         __fc_a[__fc_i + 1], 2)) \
0013             break;                      \
0014     }                               \
0015     (__fc_i);                           \
0016 })
0017 
0018 /**
0019  * find_closest - locate the closest element in a sorted array
0020  * @x: The reference value.
0021  * @a: The array in which to look for the closest element. Must be sorted
0022  *  in ascending order.
0023  * @as: Size of 'a'.
0024  *
0025  * Returns the index of the element closest to 'x'.
0026  */
0027 #define find_closest(x, a, as) __find_closest(x, a, as, <=)
0028 
0029 /**
0030  * find_closest_descending - locate the closest element in a sorted array
0031  * @x: The reference value.
0032  * @a: The array in which to look for the closest element. Must be sorted
0033  *  in descending order.
0034  * @as: Size of 'a'.
0035  *
0036  * Similar to find_closest() but 'a' is expected to be sorted in descending
0037  * order.
0038  */
0039 #define find_closest_descending(x, a, as) __find_closest(x, a, as, >=)
0040 
0041 #endif