lkml.org 
[lkml]   [2022]   [Aug]   [8]   [last100]   RSS Feed
Views: [wrap][no wrap]   [headers]  [forward] 
 
Messages in this thread
Patch in this message
/
From
Subject[PATCH 7/8] util_macros.h: Add macro to find closest smaller value in array
Date
From: Yassine Oudjana <y.oudjana@protonmail.com>

Add a macro to find the value closest to but smaller than a given
value in an array.

Signed-off-by: Yassine Oudjana <y.oudjana@protonmail.com>
---
include/linux/util_macros.h | 22 ++++++++++++++++++++++
1 file changed, 22 insertions(+)

diff --git a/include/linux/util_macros.h b/include/linux/util_macros.h
index 72299f261b25..ad0020e7932b 100644
--- a/include/linux/util_macros.h
+++ b/include/linux/util_macros.h
@@ -38,4 +38,26 @@
*/
#define find_closest_descending(x, a, as) __find_closest(x, a, as, >=)

+/**
+ * find_closest_smaller - locate the closest smaller element in a sorted array
+ * @x: The reference value.
+ * @a: The array in which to look for the closest smaller element. Must be
+ * sorted in ascending order.
+ * @as: Size of 'a'.
+ *
+ * Returns the index of the element closest to and smaller than 'x', or -1
+ * if no element smaller than 'x' exists in the array.
+ */
+#define find_closest_smaller(x, a, as) \
+({ \
+ typeof(as) __fcs_i; \
+ typeof(x) __fcs_x = (x); \
+ typeof(*a) const *__fcs_a = (a); \
+ for (__fcs_i = 0; __fcs_i < (as); __fcs_i++) { \
+ if (__fcs_x < __fcs_a[__fcs_i]) \
+ break; \
+ } \
+ (__fcs_i - 1); \
+})
+
#endif
--
2.37.1
\
 
 \ /
  Last update: 2022-08-08 09:38    [W:0.218 / U:0.364 seconds]
©2003-2020 Jasper Spaans|hosted at Digital Ocean and TransIP|Read the blog|Advertise on this site