From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S964929AbbCSR13 (ORCPT ); Thu, 19 Mar 2015 13:27:29 -0400 Received: from mail-wg0-f51.google.com ([74.125.82.51]:33381 "EHLO mail-wg0-f51.google.com" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1752007AbbCSR1Z (ORCPT ); Thu, 19 Mar 2015 13:27:25 -0400 From: Bartosz Golaszewski To: LKML Cc: Guenter Roeck , lm-sensors , Andrew Morton , Steven Rostedt , Bartosz Golaszewski Subject: [PATCH v4 1/5] util_macros.h: add find_closest() macro Date: Thu, 19 Mar 2015 18:27:41 +0100 Message-Id: <1426786065-9798-2-git-send-email-bgolaszewski@baylibre.com> X-Mailer: git-send-email 2.1.4 In-Reply-To: <1426786065-9798-1-git-send-email-bgolaszewski@baylibre.com> References: <1426786065-9798-1-git-send-email-bgolaszewski@baylibre.com> Sender: linux-kernel-owner@vger.kernel.org List-ID: X-Mailing-List: linux-kernel@vger.kernel.org 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. Signed-off-by: Bartosz Golaszewski --- include/linux/util_macros.h | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 include/linux/util_macros.h diff --git a/include/linux/util_macros.h b/include/linux/util_macros.h new file mode 100644 index 0000000..d5f4fb6 --- /dev/null +++ b/include/linux/util_macros.h @@ -0,0 +1,40 @@ +#ifndef _LINUX_HELPER_MACROS_H_ +#define _LINUX_HELPER_MACROS_H_ + +#define __find_closest(x, a, as, op) \ +({ \ + typeof(as) __fc_i, __fc_as = (as) - 1; \ + typeof(x) __fc_x = (x); \ + typeof(*a) *__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, <=) + +/** + * find_closest_descending - 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 descending order. + * @as: Size of 'a'. + * + * Similar to find_closest() but 'a' is expected to be sorted in descending + * order. + */ +#define find_closest_descending(x, a, as) __find_closest(x, a, as, >=) + +#endif -- 2.1.4