1#ifndef c89atomic_bitmap_allocator_c
2#define c89atomic_bitmap_allocator_c
9static c89atomic_uint32 c89atomic_clz_32(c89atomic_uint32 x)
13 for (i = 0; i < 32; i += 1) {
14 if ((x & (0x80000000 >> i)) != 0) {
24C89ATOMIC_BITMAP_ALLOCATOR_API c89atomic_bitmap_allocator_result c89atomic_bitmap_allocator_init(
void* pBitmap, size_t sizeInBits, c89atomic_bitmap_allocator* pAllocator)
28 if (pAllocator == NULL || pBitmap == NULL) {
29 return C89ATOMIC_BITMAP_ALLOCATOR_INVALID_ARGS;
33 if ((sizeInBits & 31) != 0) {
34 return C89ATOMIC_BITMAP_ALLOCATOR_INVALID_ARGS;
37 pAllocator->sizeInWords = sizeInBits / (
sizeof(pAllocator->bitmap[0]) * 8);
38 pAllocator->bitmap = (c89atomic_uint32*)pBitmap;
41 for (i = 0; i < pAllocator->sizeInWords; i += 1) {
42 pAllocator->bitmap[i] = 0;
45 return C89ATOMIC_BITMAP_ALLOCATOR_SUCCESS;
48C89ATOMIC_BITMAP_ALLOCATOR_API c89atomic_bitmap_allocator_result c89atomic_bitmap_allocator_alloc(c89atomic_bitmap_allocator* pAllocator, size_t* pIndex)
53 for (i = 0; i < pAllocator->sizeInWords; i += 1) {
54 c89atomic_uint32 oldWord;
55 c89atomic_uint32 newWord;
56 c89atomic_uint32 bitIndex;
60 if (oldWord == 0xFFFFFFFF) {
64 bitIndex = c89atomic_clz_32(~oldWord);
65 assert(bitIndex < 32);
67 newWord = oldWord | (0x80000000UL >> bitIndex);
70 *pIndex = (i *
sizeof(pAllocator->bitmap[0]) * 8) + bitIndex;
71 return C89ATOMIC_BITMAP_ALLOCATOR_SUCCESS;
77 return C89ATOMIC_BITMAP_ALLOCATOR_OUT_OF_MEMORY;
82 c89atomic_uint32 wordIndex;
83 c89atomic_uint32 bitIndex;
84 c89atomic_uint32 oldWord;
85 c89atomic_uint32 newWord;
87 wordIndex = (c89atomic_uint32)((index & 0xFFFFFFFF) >> 5);
88 bitIndex = (c89atomic_uint32)((index & 0xFFFFFFFF) & 31);
90 if (wordIndex >= pAllocator->sizeInWords) {
91 assert(!
"Index out of bounds in c89atomic_bitmap_allocator_free().");
98 newWord = oldWord & ~(0x80000000UL >> bitIndex);
101 if ((oldWord & (0x80000000UL >> bitIndex)) == 0) {
102 assert(!
"Double free detected in c89atomic_bitmap_allocator_free().");
#define c89atomic_memory_order_relaxed
#define c89atomic_memory_order_acq_rel
#define C89ATOMIC_BITMAP_ALLOCATOR_API