blob: 72299f261b253392ead9e08977d033f43bf6b77c [file] [log] [blame]
Greg Kroah-Hartmanb2441312017-11-01 15:07:57 +01001/* SPDX-License-Identifier: GPL-2.0 */
Bartosz Golaszewski95d11952015-04-16 12:43:28 -07002#ifndef _LINUX_HELPER_MACROS_H_
3#define _LINUX_HELPER_MACROS_H_
4
5#define __find_closest(x, a, as, op) \
6({ \
7 typeof(as) __fc_i, __fc_as = (as) - 1; \
8 typeof(x) __fc_x = (x); \
Guenter Roeck05836c32015-05-05 16:23:57 -07009 typeof(*a) const *__fc_a = (a); \
Bartosz Golaszewski95d11952015-04-16 12:43:28 -070010 for (__fc_i = 0; __fc_i < __fc_as; __fc_i++) { \
11 if (__fc_x op DIV_ROUND_CLOSEST(__fc_a[__fc_i] + \
12 __fc_a[__fc_i + 1], 2)) \
13 break; \
14 } \
15 (__fc_i); \
16})
17
18/**
19 * find_closest - locate the closest element in a sorted array
20 * @x: The reference value.
21 * @a: The array in which to look for the closest element. Must be sorted
22 * in ascending order.
23 * @as: Size of 'a'.
24 *
25 * Returns the index of the element closest to 'x'.
26 */
27#define find_closest(x, a, as) __find_closest(x, a, as, <=)
28
29/**
30 * find_closest_descending - locate the closest element in a sorted array
31 * @x: The reference value.
32 * @a: The array in which to look for the closest element. Must be sorted
33 * in descending order.
34 * @as: Size of 'a'.
35 *
36 * Similar to find_closest() but 'a' is expected to be sorted in descending
37 * order.
38 */
39#define find_closest_descending(x, a, as) __find_closest(x, a, as, >=)
40
41#endif