From 2a016de1c2eb45fc5f9c8cebf6b3c726b01ec340 Mon Sep 17 00:00:00 2001 From: 3gg <3gg@shellblade.net> Date: Tue, 11 Jul 2023 18:37:31 -0700 Subject: Add support for dynamically allocated mempools. --- mempool/src/mempool.c | 44 +++++++++++++++++++++++++++++++++++++------- 1 file changed, 37 insertions(+), 7 deletions(-) (limited to 'mempool/src') diff --git a/mempool/src/mempool.c b/mempool/src/mempool.c index b4693a5..059db93 100644 --- a/mempool/src/mempool.c +++ b/mempool/src/mempool.c @@ -1,24 +1,54 @@ #include "mempool.h" +#include #include static inline size_t min(size_t a, size_t b) { return a < b ? a : b; } -void mempool_make_( +bool mempool_make_( mempool* pool, BlockInfo* block_info, void* blocks, size_t num_blocks, size_t block_size_bytes) { assert(pool); - assert(block_info); - assert(blocks); + assert((block_info && blocks) || (!block_info && !blocks)); assert(num_blocks >= 1); pool->block_size_bytes = block_size_bytes; pool->num_blocks = num_blocks; pool->next_free_block = 0; pool->full = false; - pool->block_info = block_info; - pool->blocks = blocks; - memset(blocks, 0, num_blocks * block_size_bytes); - memset(block_info, 0, num_blocks * sizeof(BlockInfo)); + if (!block_info) { + block_info = calloc(num_blocks, sizeof(BlockInfo)); + blocks = calloc(num_blocks, block_size_bytes); + pool->dynamic = true; + } else { + memset(blocks, 0, num_blocks * block_size_bytes); + memset(block_info, 0, num_blocks * sizeof(BlockInfo)); + pool->dynamic = false; + } + pool->block_info = block_info; + pool->blocks = blocks; + return (block_info != 0) && (blocks != 0); +} + +void mempool_del_(mempool* pool) { + assert(pool); + if (pool->dynamic) { + if (pool->block_info) { + free(pool->block_info); + pool->block_info = 0; + } + if (pool->blocks) { + free(pool->blocks); + pool->blocks = 0; + } + } +} + +void mempool_clear_(mempool* pool) { + assert(pool); + pool->next_free_block = 0; + pool->full = false; + memset(pool->blocks, 0, pool->num_blocks * pool->block_size_bytes); + memset(pool->block_info, 0, pool->num_blocks * sizeof(BlockInfo)); } void* mempool_alloc_(mempool* pool) { -- cgit v1.2.3