diff mbox series

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

Message ID 20240415191454.3259243-2-denkenz@gmail.com (mailing list archive)
State New
Headers show
Series [1/4] util: Remove confusing static keyword use | expand

Checks

Context Check Description
tedd_an/pre-ci_am success Success

Commit Message

Denis Kenzior April 15, 2024, 7:14 p.m. UTC
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 mbox series

Patch

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.