Return-Path: Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1753260Ab3GIGqU (ORCPT ); Tue, 9 Jul 2013 02:46:20 -0400 Received: from mail-yh0-f49.google.com ([209.85.213.49]:51295 "EHLO mail-yh0-f49.google.com" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1752862Ab3GIGqT (ORCPT ); Tue, 9 Jul 2013 02:46:19 -0400 From: Wedson Almeida Filho To: Rusty Russell , Joe Perches Cc: Tim Abbott , linux-kernel@vger.kernel.org, Wedson Almeida Filho Subject: [PATCH v2] lib: One less subtraction in binary search iterations. Date: Mon, 8 Jul 2013 23:37:02 -0700 Message-Id: <1373351822-52050-1-git-send-email-wedsonaf@gmail.com> X-Mailer: git-send-email 1.7.9.5 In-Reply-To: References: Sender: linux-kernel-owner@vger.kernel.org List-ID: X-Mailing-List: linux-kernel@vger.kernel.org Content-Length: 1535 Lines: 42 The subtraction is removed at the expense of generality: when the element size is 1, the array length cannot exceed half the architecture's addressable memory. Signed-off-by: Wedson Almeida Filho --- lib/bsearch.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/lib/bsearch.c b/lib/bsearch.c index e33c179..668ae6c 100644 --- a/lib/bsearch.c +++ b/lib/bsearch.c @@ -24,6 +24,11 @@ * contents of the array should already be in ascending sorted order * under the provided comparison function. * + * There is a limitation when @size is 1: in this case @num must be at + * most SIZE_MAX / 2; that is, the number of elements in the sorted + * array must be at most half the maximum number expressible as a size_t + * to avoid overflows. + * * Note that the key need not have the same type as the elements in * the array, e.g. key could be a string and the comparison function * could compare the string with the struct's name field. However, if @@ -37,7 +42,7 @@ void *bsearch(const void *key, const void *base, size_t num, size_t size, int result; while (start < end) { - size_t mid = start + (end - start) / 2; + size_t mid = (start + end) / 2; result = cmp(key, base + mid * size); if (result < 0) -- 1.7.9.5 -- To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to majordomo@vger.kernel.org More majordomo info at http://vger.kernel.org/majordomo-info.html Please read the FAQ at http://www.tux.org/lkml/