util: add util_is_field_bit_set
PATCH 1/2 util: add util_is_field_bit_set
This lets you easily check if a bit is set in a field of bytes. This was added as a new API rather than modifiying util_is_bit_set since its still useful to check if a bit is set in a single byte.
The drive here is that we have many places doing e.g.
if (util_bit_is_set(data[3], 4))
...
To check the 28th bit in a field (in this example). This makes the code hard to read since you have to do math (3 * 8 + 4) to figure out what bit is actually being checked in the overall field.
--- src/util.h | 7 +++++++ 1 file changed, 7 insertions(+)
src/util.h +7 -0
@@ -54,6 +54,13 @@ static inline bool util_is_bit_set(const uint8_t oct, int bit)return oct & mask ? true : false; } +static inline bool util_is_field_bit_set (const uint8_t *field,int bit) +{ +uint8_t oct = field[bit /8 ]; + +return util_is_bit_set (oct, bit %8 ); +} +static inline bool util_mem_is_zero (const uint8_t *field,size_t size) {size_t i;
Signature · 1 line
2.17.1
PATCH 2/2 unit: add test for util_is_field_bit_set
--- unit/test-util.c | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+)
unit/test-util.c +24 -0
@@ -115,6 +115,29 @@ static void get_username_test(const void *data)assert (strcmp (test,"username" ) ==0 ); } +static void test_is_bit_field_set (const void *data) +{ +uint8_t field[8 ] = {0 }; + + field[4 ] = (1 <<7 ) | (1 <<3 ); + field[0 ] = (1 <<0 ); + field[7 ] = (1 <<7 ); + +/* test first and last bit */ +assert (util_is_field_bit_set (field,0 )); +assert (util_is_field_bit_set (field,63 )); + +/* 4th byte 7th bit = 39th bit */ +assert (!util_is_field_bit_set (field,38 )); +assert (util_is_field_bit_set (field,39 )); +assert (!util_is_field_bit_set (field,40 )); + +/* 4th byte 3rd bit = 35th bit */ +assert (!util_is_field_bit_set (field,34 )); +assert (util_is_field_bit_set (field,35 )); +assert (!util_is_field_bit_set (field,46 )); +} +int main (int argc,char *argv[]) {l_test_init (&argc, &argv);
@@ -122,6 +145,7 @@ int main(int argc, char *argv[])l_test_add ("/util/ssid_to_utf8/" , ssid_to_utf8, ssid_samples);l_test_add ("/util/get_domain/" , get_domain_test,NULL );l_test_add ("/util/get_username/" , get_username_test,NULL ); +l_test_add ("/util/is_field_bit_set/" , test_is_bit_field_set,NULL );return l_test_run (); }
Signature · 1 line
2.17.1