diff options
author | Denis Kenzior <denkenz@gmail.com> | 2024-04-12 14:39:01 -0500 |
---|---|---|
committer | Denis Kenzior <denkenz@gmail.com> | 2024-04-16 14:06:53 -0500 |
commit | f5456000a1e75d4fb566844cd997eef11da2516c (patch) | |
tree | 8324d88b0f84ae4469710ca1babad65fef3d1b3f | |
parent | b995e0f3b990e91b2ec57134d3ce66cf9511e9a0 (diff) |
util: Add L_BIT_{SET|CLEAR|TEST} macros
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);
-rw-r--r-- | ell/util.h | 30 |
1 files changed, 30 insertions, 0 deletions
@@ -366,6 +366,36 @@ 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__ ({ \ + typeof(*(bits)) _one = 1U; \ + const unsigned int _shift = (nr) % (sizeof(_one) * 8); \ + _one << _shift; \ +}) + +#define _L_BIT_TO_OFFSET(bits, nr) __extension__ ({ \ + __auto_type _bits = (bits); \ + const size_t _offset = (nr) / (sizeof(*_bits) * 8); \ + _bits + _offset; \ +}) + +#define L_BIT_SET(bits, nr) __extension__ ({ \ + size_t _nr = (nr); \ + __auto_type _offset = _L_BIT_TO_OFFSET(bits, _nr); \ + *_offset |= _L_BIT_TO_MASK(_offset, _nr); \ +}) + +#define L_BIT_CLEAR(bits, nr) __extension__ ({ \ + size_t _nr = (nr); \ + __auto_type _offset = _L_BIT_TO_OFFSET(bits, _nr); \ + *_offset &= ~_L_BIT_TO_MASK(_offset, _nr); \ +}) + +#define L_BIT_TEST(bits, nr) __extension__ ({ \ + size_t _nr = (nr); \ + __auto_type _offset = _L_BIT_TO_OFFSET(bits, _nr); \ + (*_offset & _L_BIT_TO_MASK(_offset, _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. |