Last active
July 5, 2024 16:01
-
-
Save brentspell/45489ac145255b77098847febfe6cf3b to your computer and use it in GitHub Desktop.
Fast Efficient Fixed-Size Memory Pool: No Loops and No Overhead
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://arxiv.org/abs/2210.16471v1 | |
#include <stdint.h> | |
#include <stdlib.h> | |
typedef struct { | |
uint8_t* data; | |
uint8_t* head; | |
uint8_t* last; | |
size_t unit; | |
size_t free; | |
} pool_t; | |
int pool_create(pool_t* pool, size_t size, size_t unit) { | |
if (unit < sizeof(void*)) | |
unit = sizeof(void*); | |
if (size < unit) | |
size = unit; | |
pool->data = (uint8_t*)malloc(size); | |
if (pool->data == NULL) | |
return -1; | |
pool->head = pool->data; | |
pool->last = pool->data; | |
pool->unit = unit; | |
pool->free = size / unit; | |
return 0; | |
} | |
void pool_destroy(pool_t* pool) { | |
free(pool->data); | |
} | |
void* pool_alloc(pool_t* pool) { | |
if (pool->free == 0) | |
return NULL; | |
if (pool->head == pool->last) | |
pool->last = *(uint8_t**)pool->last = pool->last + pool->unit; | |
void* data = pool->head; | |
pool->head = *(uint8_t**)pool->head; | |
pool->free--; | |
return data; | |
} | |
void pool_free(pool_t* pool, void* data) { | |
if (data != NULL) { | |
*(uint8_t**)data = pool->head; | |
pool->head = data; | |
pool->free++; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment