47 lines
984 B
C
47 lines
984 B
C
#include <malloc.h>
|
|
#include <string.h>
|
|
|
|
/* See: https://8dcc.github.io/programming/pool-allocator.html */
|
|
|
|
#define CHUNK_SIZE 64
|
|
|
|
typedef union Chunk Chunk;
|
|
union Chunk {
|
|
Chunk *next; // When not null, it is used
|
|
char arr[CHUNK_SIZE];
|
|
};
|
|
|
|
typedef struct Pool Pool;
|
|
struct Pool {
|
|
Chunk *free_chunk; // Pointer to a linked list of free chunks
|
|
Chunk *chunk_arr;
|
|
};
|
|
|
|
void *pool_alloc(Pool *pool) {
|
|
if (pool == NULL || pool->free_chunk == NULL)
|
|
return NULL;
|
|
|
|
// Pop a new one from the free list
|
|
Chunk *result = pool->free_chunk;
|
|
pool->free_chunk = pool->free_chunk->next;
|
|
|
|
return result;
|
|
}
|
|
|
|
void pool_free(Pool *pool, void *ptr) {
|
|
if (pool == NULL || ptr == NULL)
|
|
return;
|
|
|
|
// This can be done withuot an intermediate ptr
|
|
Chunk *freed = ptr;
|
|
freed->next = pool->free_chunk;
|
|
pool->free_chunk = freed;
|
|
}
|
|
|
|
void pool_close(Pool *pool) {
|
|
if (pool == NULL)
|
|
return;
|
|
|
|
free(pool->chunk_arr);
|
|
free(pool);
|
|
}
|