diff mbox series

[1/2] include: kernel.h: port find_closest() from Linux

Message ID 20230316221626.1043438-2-judge.packham@gmail.com
State Superseded
Delegated to: Tom Rini
Headers show
Series max313xx RTC driver | expand

Commit Message

Chris Packham March 16, 2023, 10:16 p.m. UTC
The find_closest() macro can be used to find an element in a sorted
array that is closest to an input value.

Signed-off-by: Chris Packham <judge.packham@gmail.com>
---

 include/linux/kernel.h | 24 ++++++++++++++++++++++++
 1 file changed, 24 insertions(+)

Comments

Simon Glass March 18, 2023, 8:20 p.m. UTC | #1
On Thu, 16 Mar 2023 at 16:17, Chris Packham <judge.packham@gmail.com> wrote:
>
> The find_closest() macro can be used to find an element in a sorted
> array that is closest to an input value.
>
> Signed-off-by: Chris Packham <judge.packham@gmail.com>
> ---
>
>  include/linux/kernel.h | 24 ++++++++++++++++++++++++
>  1 file changed, 24 insertions(+)
>

Reviewed-by: Simon Glass <sjg@chromium.org>

Good to mention the Linux version it was taken from
diff mbox series

Patch

diff --git a/include/linux/kernel.h b/include/linux/kernel.h
index 3e71d61074b6..5cd6c9dc8219 100644
--- a/include/linux/kernel.h
+++ b/include/linux/kernel.h
@@ -284,4 +284,28 @@ 
 	offsetof(struct structure, member) == (offset), \
 	"`struct " #structure "` offset for `" #member "` is not " #offset)
 
+#define __find_closest(x, a, as, op)					\
+({									\
+	typeof(as) __fc_i, __fc_as = (as) - 1;				\
+	typeof(x) __fc_x = (x);						\
+	typeof(*a) const *__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, <=)
+
 #endif