diff mbox series

[7/8] util_macros.h: Add macro to find closest smaller value in array

Message ID 20220808073459.396278-8-y.oudjana@protonmail.com
State New
Headers show
Series power: supply: Add driver for Qualcomm SMBCHG | expand

Commit Message

Yassine Oudjana Aug. 8, 2022, 7:34 a.m. UTC
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 mbox series

Patch

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