]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/bitmap.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
9 #include "alloc-util.h"
13 #include "memory-util.h"
18 size_t bitmaps_allocated
;
21 /* Bitmaps are only meant to store relatively small numbers
22 * (corresponding to, say, an enum), so it is ok to limit
23 * the max entry. 64k should be plenty. */
24 #define BITMAPS_MAX_ENTRY 0xffff
26 /* This indicates that we reached the end of the bitmap */
27 #define BITMAP_END ((unsigned) -1)
29 #define BITMAP_NUM_TO_OFFSET(n) ((n) / (sizeof(uint64_t) * 8))
30 #define BITMAP_NUM_TO_REM(n) ((n) % (sizeof(uint64_t) * 8))
31 #define BITMAP_OFFSET_TO_NUM(offset, rem) ((offset) * sizeof(uint64_t) * 8 + (rem))
33 Bitmap
*bitmap_new(void) {
34 return new0(Bitmap
, 1);
37 Bitmap
*bitmap_copy(Bitmap
*b
) {
44 ret
->bitmaps
= newdup(uint64_t, b
->bitmaps
, b
->n_bitmaps
);
48 ret
->n_bitmaps
= ret
->bitmaps_allocated
= b
->n_bitmaps
;
52 void bitmap_free(Bitmap
*b
) {
60 int bitmap_ensure_allocated(Bitmap
**b
) {
77 int bitmap_set(Bitmap
*b
, unsigned n
) {
83 /* we refuse to allocate huge bitmaps */
84 if (n
> BITMAPS_MAX_ENTRY
)
87 offset
= BITMAP_NUM_TO_OFFSET(n
);
89 if (offset
>= b
->n_bitmaps
) {
90 if (!GREEDY_REALLOC0(b
->bitmaps
, b
->bitmaps_allocated
, offset
+ 1))
93 b
->n_bitmaps
= offset
+ 1;
96 bitmask
= UINT64_C(1) << BITMAP_NUM_TO_REM(n
);
98 b
->bitmaps
[offset
] |= bitmask
;
103 void bitmap_unset(Bitmap
*b
, unsigned n
) {
110 offset
= BITMAP_NUM_TO_OFFSET(n
);
112 if (offset
>= b
->n_bitmaps
)
115 bitmask
= UINT64_C(1) << BITMAP_NUM_TO_REM(n
);
117 b
->bitmaps
[offset
] &= ~bitmask
;
120 bool bitmap_isset(Bitmap
*b
, unsigned n
) {
127 offset
= BITMAP_NUM_TO_OFFSET(n
);
129 if (offset
>= b
->n_bitmaps
)
132 bitmask
= UINT64_C(1) << BITMAP_NUM_TO_REM(n
);
134 return !!(b
->bitmaps
[offset
] & bitmask
);
137 bool bitmap_isclear(Bitmap
*b
) {
143 for (i
= 0; i
< b
->n_bitmaps
; i
++)
144 if (b
->bitmaps
[i
] != 0)
150 void bitmap_clear(Bitmap
*b
) {
155 b
->bitmaps
= mfree(b
->bitmaps
);
157 b
->bitmaps_allocated
= 0;
160 bool bitmap_iterate(Bitmap
*b
, Iterator
*i
, unsigned *n
) {
162 unsigned offset
, rem
;
167 if (!b
|| i
->idx
== BITMAP_END
)
170 offset
= BITMAP_NUM_TO_OFFSET(i
->idx
);
171 rem
= BITMAP_NUM_TO_REM(i
->idx
);
172 bitmask
= UINT64_C(1) << rem
;
174 for (; offset
< b
->n_bitmaps
; offset
++) {
175 if (b
->bitmaps
[offset
]) {
176 for (; bitmask
; bitmask
<<= 1, rem
++) {
177 if (b
->bitmaps
[offset
] & bitmask
) {
178 *n
= BITMAP_OFFSET_TO_NUM(offset
, rem
);
195 bool bitmap_equal(Bitmap
*a
, Bitmap
*b
) {
196 size_t common_n_bitmaps
;
209 common_n_bitmaps
= MIN(a
->n_bitmaps
, b
->n_bitmaps
);
210 if (memcmp_safe(a
->bitmaps
, b
->bitmaps
, sizeof(uint64_t) * common_n_bitmaps
) != 0)
213 c
= a
->n_bitmaps
> b
->n_bitmaps
? a
: b
;
214 for (i
= common_n_bitmaps
; i
< c
->n_bitmaps
; i
++)
215 if (c
->bitmaps
[i
] != 0)