[PATCH 2/4] util: Add L_BIT_{SET|CLEAR|TEST} macros

Denis Kenzior <[email protected]> Mon, 15 Apr 2024 14:14:34 -0500
Newsgroups dev.linux.lists.ell
Message-ID <[email protected]>
These macros support arbitrarily sized bitmaps using any integer data
type.  It is thus possible to write code like this:

	uint64_t bitmap = 0;
	uint8_t array[4] = {};
	bool r;

	L_BIT_SET(&bitmap, 63);
	r = L_BIT_TEST(&bitmap, 0);

	L_BIT_SET(array, 25);
	r = L_BIT_TEST(array, 31);
---
 ell/util.h | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)

diff --git a/ell/util.h b/ell/util.h
index b5d96754e8ae..53a932c771e6 100644
--- a/ell/util.h
+++ b/ell/util.h
@@ -366,6 +366,24 @@ inline __attribute__((always_inline)) void _l_close_cleanup(void *p)
 				(__v && __elems[__i] &&			\
 				 !strcmp(__v, __elems[__i])), ##__VA_ARGS__)
 
+#define _L_BIT_TO_MASK(bits, nr) __extension__ ({			\
+	const unsigned int shift = (nr) % (sizeof(*(bits)) * 8);	\
+	const typeof(*(bits)) mask = (typeof(*(bits)))1 << shift;	\
+	mask;								\
+})
+
+#define _L_BIT_TO_OFFSET(bits, nr)					\
+	(*((bits) + ((nr) / (sizeof(*(bits)) * 8))))			\
+
+#define L_BIT_SET(bits, nr)						\
+	_L_BIT_TO_OFFSET(bits, nr) |= _L_BIT_TO_MASK(bits, nr)
+
+#define L_BIT_CLEAR(bits, nr)						\
+	_L_BIT_TO_OFFSET(bits, nr) &= ~_L_BIT_TO_MASK(bits, nr)
+
+#define L_BIT_TEST(bits, nr)						\
+	((~_L_BIT_TO_OFFSET(bits, nr) & _L_BIT_TO_MASK(bits, nr)) == 0)
+
 /*
  * Taken from https://github.com/chmike/cst_time_memcmp, adding a volatile to
  * ensure the compiler does not try to optimize the constant time behavior.
-- 
2.44.0