diff --git a/src/lib/bit/bit.h b/src/lib/bit/bit.h index 370a0cc5d5f4cca38f1eff9bee2cb2c4eeca67c9..b11034cb97c00e52795c6eb15655cb3fe69e6db9 100644 --- a/src/lib/bit/bit.h +++ b/src/lib/bit/bit.h @@ -175,6 +175,21 @@ store_bool(void *p, bool b) ((struct unaligned_mem *)p)->b = b; } +/** + * @brief Returns the size of memory needed to store a bitmap + * of \a bit_count bits. + * The function rounds the size up to a multiple of the word + * size, which is required by bit_set() and bit_clear(). + * @param bit_count number of bits in the bitmap + * @retval bitmap size, in bytes + */ +static inline size_t +bitmap_size(size_t bit_count) +{ + size_t word_count = DIV_ROUND_UP(bit_count, CHAR_BIT * sizeof(long)); + return word_count * sizeof(long); +} + /** * @brief Test bit \a pos in memory chunk \a data * data is considered as a sequence of chars, diff --git a/test/unit/bit.c b/test/unit/bit.c index beb89a7e4e9aac1871fd2bfa04797ce15a4691e0..da514484d2103feb532ff5acb85b43e4a825a962 100644 --- a/test/unit/bit.c +++ b/test/unit/bit.c @@ -206,6 +206,20 @@ test_bit_iter_empty(void) footer(); } +static void +test_bitmap_size(void) +{ + header(); + fail_unless(bitmap_size(1) == sizeof(long)); + fail_unless(bitmap_size(10) == sizeof(long)); + fail_unless(bitmap_size(sizeof(long) * CHAR_BIT) == sizeof(long)); + fail_unless(bitmap_size(sizeof(long) * CHAR_BIT + 1) == sizeof(long) * 2); + fail_unless(bitmap_size(sizeof(long) * CHAR_BIT * 4) == sizeof(long) * 4); + fail_unless(bitmap_size(sizeof(long) * CHAR_BIT * 4 - 1) == sizeof(long) * 4); + fail_unless(bitmap_size(sizeof(long) * CHAR_BIT * 9 / 2) == sizeof(long) * 5); + footer(); +} + int main(void) { @@ -216,4 +230,5 @@ main(void) test_index(); test_bit_iter(); test_bit_iter_empty(); + test_bitmap_size(); } diff --git a/test/unit/bit.result b/test/unit/bit.result index e2c5601f342cabf12810413e5bd1d0b81af0bf0c..2d4ccc6f474a8fb50d2733145f7d29b5b88bc0a3 100644 --- a/test/unit/bit.result +++ b/test/unit/bit.result @@ -891,3 +891,5 @@ Clear: 0, 1, 2, 4, 5, 6, 7, 8, 10, 12, 13, 14, 15, 19, 20, 21, 23, 26, 28, 30, 3 *** test_bit_iter: done *** *** test_bit_iter_empty *** *** test_bit_iter_empty: done *** + *** test_bitmap_size *** + *** test_bitmap_size: done ***