From b905d4b79f1165d4c9bf24aea76e80470f3297b9 Mon Sep 17 00:00:00 2001
From: Kirill Shcherbatov <kshcherbatov@tarantool.org>
Date: Thu, 27 Dec 2018 13:06:26 +0300
Subject: [PATCH] box: introduce bitmap_size helper

@locker: comments.

Needed for #1012
---
 src/lib/bit/bit.h    | 15 +++++++++++++++
 test/unit/bit.c      | 15 +++++++++++++++
 test/unit/bit.result |  2 ++
 3 files changed, 32 insertions(+)

diff --git a/src/lib/bit/bit.h b/src/lib/bit/bit.h
index 370a0cc5d5..b11034cb97 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 beb89a7e4e..da514484d2 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 e2c5601f34..2d4ccc6f47 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 ***
-- 
GitLab