11 #define ELEM_BITS (sizeof (elem_type) * CHAR_BIT)
12 #define ELEM_IDX(BIT_IDX) ((BIT_IDX) / ELEM_BITS)
13 #define BIT_MASK(BIT_IDX) ((elem_type) 1 << ((BIT_IDX) % ELEM_BITS))
16 elem_cnt (const struct bitmap *b)
18 return DIV_ROUND_UP (b->bit_cnt, ELEM_BITS);
22 byte_cnt (const struct bitmap *b)
24 return sizeof (elem_type) * elem_cnt (b);
28 bitmap_init (struct bitmap *b, size_t bit_cnt)
31 b->bits = malloc (byte_cnt (b));
32 if (b->bits == NULL && bit_cnt > 0)
35 bitmap_set_all (b, false);
40 bitmap_storage_size (const struct bitmap *b)
46 bitmap_destroy (struct bitmap *b)
54 bitmap_size (const struct bitmap *b)
60 bitmap_set (struct bitmap *b, size_t idx, bool value)
63 ASSERT (idx < b->bit_cnt);
65 b->bits[ELEM_IDX (idx)] |= BIT_MASK (idx);
67 b->bits[ELEM_IDX (idx)] &= ~BIT_MASK (idx);
71 bitmap_set_all (struct bitmap *b, bool value)
78 for (i = 0; i < elem_cnt (b); i++)
79 b->bits[i] = value ? (elem_type) -1 : 0;
81 leftover_bits = b->bit_cnt % ELEM_BITS;
82 if (leftover_bits != 0)
83 b->bits[i - 1] = ((elem_type) 1 << leftover_bits) - 1;
87 bitmap_mark (struct bitmap *b, size_t idx)
89 bitmap_set (b, idx, true);
93 bitmap_reset (struct bitmap *b, size_t idx)
95 bitmap_set (b, idx, false);
99 bitmap_flip (struct bitmap *b, size_t idx)
102 ASSERT (idx < b->bit_cnt);
103 b->bits[ELEM_IDX (idx)] ^= BIT_MASK (idx);
107 bitmap_test (const struct bitmap *b, size_t idx)
110 ASSERT (idx < b->bit_cnt);
111 return (b->bits[ELEM_IDX (idx)] & BIT_MASK (idx)) != 0;
115 bitmap_scan (const struct bitmap *b, bool value)
121 ignore = value ? 0 : (elem_type) -1;
122 for (idx = 0; idx < elem_cnt (b); idx++)
124 elem_type e = b->bits[idx];
125 if (e != (elem_type) -1)
142 bitmap_find_and_set (struct bitmap *b)
144 size_t idx = bitmap_scan (b, false);
145 if (idx != BITMAP_ERROR)
146 bitmap_mark (b, idx);
151 bitmap_find_and_clear (struct bitmap *b)
153 size_t idx = bitmap_scan (b, true);
154 if (idx != BITMAP_ERROR)
155 bitmap_reset (b, idx);
160 bitmap_set_cnt (const struct bitmap *b)
167 for (i = 0; i < elem_cnt (b); i++)
169 elem_type e = b->bits[i];
180 bitmap_any (const struct bitmap *b)
185 for (i = 0; i < elem_cnt (b); i++)
192 bitmap_clear_cnt (const struct bitmap *b)
194 return b->bit_cnt - bitmap_set_cnt (b);
198 bitmap_none (const struct bitmap *b)
200 return !bitmap_any (b);
204 bitmap_all (const struct bitmap *b)
206 size_t leftover_bits;
214 for (i = 0; i < elem_cnt (b) - 1; i++)
215 if (b->bits[i] != (elem_type) -1)
218 leftover_bits = b->bit_cnt % ELEM_BITS;
219 if (leftover_bits == 0)
220 return b->bits[i] == (elem_type) -1;
222 return b->bits[i] == ((elem_type) 1 << leftover_bits) - 1;
227 bitmap_read (struct bitmap *b, struct file *file)
229 file_read_at (file, b->bits, byte_cnt (b), 0);
233 bitmap_write (const struct bitmap *b, struct file *file)
235 file_write_at (file, b->bits, byte_cnt (b), 0);