Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

util_macros.h: add find_closest() macro

This series unduplicates the code used to find the member in an array
closest to 'x'.

The first patch adds a macro implementing the algorithm in two flavors -
for arrays sorted in ascending and descending order. The second updates
Documentation/CodingStyle on the naming convention for local variables in
macros resembling functions. Other three patches replace duplicated code
with calls to one of these macros in some hwmon drivers.

This patch (of 5):

Searching for the member of an array closest to 'x' is duplicated in
several places.

Add a new include - util_macros.h - and two macros that implement this
algorithm for arrays sorted both in ascending and descending order.

Uses linear search.

Signed-off-by: Bartosz Golaszewski <bgolaszewski@baylibre.com>
Cc: Guenter Roeck <linux@roeck-us.net>
Cc: Steven Rostedt <rostedt@goodmis.org>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>

authored by

Bartosz Golaszewski and committed by
Linus Torvalds
95d11952 a7a2c02a

+40
+40
include/linux/util_macros.h
··· 1 + #ifndef _LINUX_HELPER_MACROS_H_ 2 + #define _LINUX_HELPER_MACROS_H_ 3 + 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) *__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 + /** 18 + * find_closest - locate the closest element in a sorted array 19 + * @x: The reference value. 20 + * @a: The array in which to look for the closest element. Must be sorted 21 + * in ascending order. 22 + * @as: Size of 'a'. 23 + * 24 + * Returns the index of the element closest to 'x'. 25 + */ 26 + #define find_closest(x, a, as) __find_closest(x, a, as, <=) 27 + 28 + /** 29 + * find_closest_descending - locate the closest element in a sorted array 30 + * @x: The reference value. 31 + * @a: The array in which to look for the closest element. Must be sorted 32 + * in descending order. 33 + * @as: Size of 'a'. 34 + * 35 + * Similar to find_closest() but 'a' is expected to be sorted in descending 36 + * order. 37 + */ 38 + #define find_closest_descending(x, a, as) __find_closest(x, a, as, >=) 39 + 40 + #endif