45 Block *_free_blocks[32]{};
47 static int32_t lowerLog2(uint32_t val)
56 void addToBlocks(Block *block, int32_t l)
61 block->next_free = _free_blocks[l];
62 _free_blocks[l] = block;
65 void removeFromBlocks(
const Block *block, int32_t l)
70 Block *tmp = _free_blocks[l];
74 _free_blocks[l] = block->next_free;
80 if (tmp->next_free == block)
82 tmp->next_free = block->next_free;
90 void divideBlock(Block *block, int32_t l)
92 int32_t
size = ((block->size +
sizeof(Block)) / 2) -
sizeof(Block);
94 removeFromBlocks(block, l);
97 block->is_free =
true;
102 buddy = (Block *)((uint8_t *)block +
sizeof(Block) +
size);
103 buddy->is_free =
true;
107 addToBlocks(buddy, l - 1);
110 Block *mergeBlock(Block *block)
114 const int32_t l = lowerLog2(block->size +
sizeof(Block));
116 const int64_t address = ((uint8_t *)block - (uint8_t *)_start_block);
117 buddy = (Block *)((address ^ (1LL << l)) + (uint8_t *)_start_block);
119 if (!buddy->is_free || buddy->size != block->size)
129 removeFromBlocks(block, l);
130 removeFromBlocks(buddy, l);
132 block->size = block->size * 2 +
sizeof(Block);
133 block->is_free =
true;
136 addToBlocks(block, l + 1);