From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1753920AbbCJR2g (ORCPT ); Tue, 10 Mar 2015 13:28:36 -0400 Received: from mail-wg0-f44.google.com ([74.125.82.44]:41227 "EHLO mail-wg0-f44.google.com" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1752629AbbCJR1u (ORCPT ); Tue, 10 Mar 2015 13:27:50 -0400 From: Bartosz Golaszewski To: LKML Cc: Guenter Roeck , lm-sensors , Andrew Morton , Steven Rostedt , Bartosz Golaszewski Subject: [PATCH v2 1/4] kernel.h: add find_closest() macro Date: Tue, 10 Mar 2015 18:27:19 +0100 Message-Id: <1426008442-26236-2-git-send-email-bgolaszewski@baylibre.com> X-Mailer: git-send-email 2.1.4 In-Reply-To: <1426008442-26236-1-git-send-email-bgolaszewski@baylibre.com> References: <1426008442-26236-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 two macros that implement this algorithm for arrays sorted both in ascending and descending order. Signed-off-by: Bartosz Golaszewski --- include/linux/kernel.h | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/include/linux/kernel.h b/include/linux/kernel.h index d6d630d..f4294da 100644 --- a/include/linux/kernel.h +++ b/include/linux/kernel.h @@ -116,6 +116,29 @@ } \ ) +#define __find_closest(x, a, as, op)( \ +{ \ + typeof(as) _i, _as = (as) - 1; \ + typeof(x) _x = (x); \ + typeof(*a) *_a = (a); \ + for (_i = 0; _i < _as; _i++) { \ + if (_x op DIV_ROUND_CLOSEST(_a[_i] + _a[_i + 1], 2)) \ + break; \ + } \ + (_i); \ +} \ +) + +/* + * Given an array 'a' (sorted in ascending order) of size 'as' return + * the index of the element in that array closest to 'x'. + */ +#define find_closest(x, a, as) __find_closest(x, a, as, <=) +/* + * Similar to find_closest(), but 'a' is expected to be sorted + * in descending order. + */ +#define find_closest_desc(x, a, as) __find_closest(x, a, as, >) #define _RET_IP_ (unsigned long)__builtin_return_address(0) #define _THIS_IP_ ({ __label__ __here; __here: (unsigned long)&&__here; }) -- 2.1.4