一个真正的“位“图,想实现一个内存池研究了一下。
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DECLARE_BITMAP(name) uint64_t name[8]
struct memory_pool
{
DECLARE_BITMAP(bitmap);
};
// 1000B => 8H
#define FIRST1_64 0x8000000000000000
void setbitmap(uint64_t* bitmap, uint64_t index)
{
uint64_t visit = FIRST1_64;
visit >>= index;
bitmap[index / 64] |= visit;
}
int findempty(uint64_t* bitmap)
{
uint64_t map;
uint64_t visit = FIRST1_64;
for (int i = 0; i < 8; ++i)
{
map = bitmap[i];
for (int j = 0; j < 64; ++j)
{
if ((map & visit)) {
return j + i * 64;
}
visit >>= 1;
}
visit = FIRST1_64;
}
return -1;
}
void clearbit(uint64_t* bitmap, int index)
{
uint64_t clear = FIRST1_64;
clear >>= index;
bitmap[index / 64] ^= clear;
}
int main() {
struct memory_pool* pool = (struct memory_pool*)malloc(sizeof(struct memory_pool));
memset(pool->bitmap, 0, 8 * sizeof(uint64_t));
setbitmap(pool->bitmap, 127);
setbitmap(pool->bitmap, 64);
printf("%s:%016lx\n", "0x", pool->bitmap[1]);
clearbit(pool->bitmap, 64);
printf("%s:%016lx\n", "after clear: 0x", pool->bitmap[1]);
int index;
if (-1 != (index = findempty(pool->bitmap))) {
printf("index: %d\n", index);
} else {
printf("no found\n");
}
}