8 #define ELEM_BITS (sizeof (elem_type) * CHAR_BIT)
9 #define ELEM_IDX(BIT_IDX) ((BIT_IDX) / ELEM_BITS)
10 #define BIT_MASK(BIT_IDX) ((elem_type) 1 << ((BIT_IDX) % ELEM_BITS))
13 elem_cnt (const struct bitmap *b)
15 return DIV_ROUND_UP (b->bit_cnt, ELEM_BITS);
19 byte_cnt (const struct bitmap *b)
21 return sizeof (elem_type) * elem_cnt (b);
25 bitmap_init (struct bitmap *b, size_t bit_cnt)
28 b->bits = malloc (byte_cnt (b));
29 if (b->bits == NULL && bit_cnt > 0)
32 bitmap_set_all (b, false);
37 bitmap_storage_size (const struct bitmap *b)
43 bitmap_destroy (struct bitmap *b)
51 bitmap_size (const struct bitmap *b)
57 bitmap_set (struct bitmap *b, size_t idx, bool value)
60 ASSERT (idx < b->bit_cnt);
62 b->bits[ELEM_IDX (idx)] |= BIT_MASK (idx);
64 b->bits[ELEM_IDX (idx)] &= ~BIT_MASK (idx);
68 bitmap_set_all (struct bitmap *b, bool value)
75 for (i = 0; i < elem_cnt (b); i++)
76 b->bits[i] = value ? (elem_type) -1 : 0;
78 leftover_bits = b->bit_cnt % ELEM_BITS;
79 if (leftover_bits != 0)
80 b->bits[i - 1] = ((elem_type) 1 << leftover_bits) - 1;
84 bitmap_mark (struct bitmap *b, size_t idx)
86 bitmap_set (b, idx, true);
90 bitmap_reset (struct bitmap *b, size_t idx)
92 bitmap_set (b, idx, false);
96 bitmap_flip (struct bitmap *b, size_t idx)
99 ASSERT (idx < b->bit_cnt);
100 b->bits[ELEM_IDX (idx)] ^= BIT_MASK (idx);
104 bitmap_test (const struct bitmap *b, size_t idx)
107 ASSERT (idx < b->bit_cnt);
108 return (b->bits[ELEM_IDX (idx)] & BIT_MASK (idx)) != 0;
112 bitmap_scan (const struct bitmap *b, bool value)
118 ignore = value ? 0 : (elem_type) -1;
119 for (idx = 0; idx < elem_cnt (b); idx++)
121 elem_type e = b->bits[idx];
122 if (e != (elem_type) -1)
139 bitmap_find_and_set (struct bitmap *b)
141 size_t idx = bitmap_scan (b, false);
142 if (idx != BITMAP_ERROR)
143 bitmap_mark (b, idx);
148 bitmap_find_and_clear (struct bitmap *b)
150 size_t idx = bitmap_scan (b, true);
151 if (idx != BITMAP_ERROR)
152 bitmap_reset (b, idx);
157 bitmap_set_cnt (const struct bitmap *b)
164 for (i = 0; i < elem_cnt (b); i++)
166 elem_type e = b->bits[i];
177 bitmap_any (const struct bitmap *b)
182 for (i = 0; i < elem_cnt (b); i++)
189 bitmap_clear_cnt (const struct bitmap *b)
191 return b->bit_cnt - bitmap_set_cnt (b);
195 bitmap_none (const struct bitmap *b)
197 return !bitmap_any (b);
201 bitmap_all (const struct bitmap *b)
203 size_t leftover_bits;
211 for (i = 0; i < elem_cnt (b) - 1; i++)
212 if (b->bits[i] != (elem_type) -1)
215 leftover_bits = b->bit_cnt % ELEM_BITS;
216 if (leftover_bits == 0)
217 return b->bits[i] == (elem_type) -1;
219 return b->bits[i] == ((elem_type) 1 << leftover_bits) - 1;