1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/ucx/mpool.c Sat Dec 31 21:05:59 2011 +0100 1.3 @@ -0,0 +1,101 @@ 1.4 +/* 1.5 + * 1.6 + */ 1.7 + 1.8 +#include <stdlib.h> 1.9 +#include <string.h> 1.10 +#include <stdio.h> 1.11 + 1.12 +#include "mpool.h" 1.13 + 1.14 +typedef struct { 1.15 + ucx_destructor destructor; 1.16 + char c; 1.17 +} ucx_memchunk; 1.18 + 1.19 +typedef struct { 1.20 + ucx_destructor destructor; 1.21 + void *ptr; 1.22 +} ucx_regdestr; 1.23 + 1.24 +void ucx_mempool_shared_destr(void* ptr) { 1.25 + ucx_regdestr *rd = (ucx_regdestr*)ptr; 1.26 + rd->destructor(rd->ptr); 1.27 +} 1.28 + 1.29 +UcxMempool *ucx_mempool_new(size_t n) { 1.30 + UcxMempool *pool = (UcxMempool*)malloc(sizeof(UcxMempool*)); 1.31 + pool->data = malloc(n * sizeof(void*)); 1.32 + pool->ndata = 0; 1.33 + pool->size = n; 1.34 + return pool; 1.35 +} 1.36 + 1.37 +void ucx_mempool_chcap(UcxMempool *pool, size_t newcap) { 1.38 + void **data = realloc(pool->data, newcap*sizeof(void*)); 1.39 + pool->data = data; 1.40 + pool->size = newcap; 1.41 +} 1.42 + 1.43 +void *ucx_mempool_malloc(UcxMempool *pool, size_t n) { 1.44 + ucx_memchunk *mem = (ucx_memchunk*)malloc(sizeof(ucx_destructor) + n); 1.45 + if(mem == NULL) { 1.46 + return NULL; 1.47 + } 1.48 + 1.49 + if (pool->ndata >= pool->size) { 1.50 + ucx_mempool_chcap(pool, pool->size + 16); 1.51 + } 1.52 + 1.53 + mem->destructor = NULL; 1.54 + pool->data[pool->ndata] = mem; 1.55 + pool->ndata++; 1.56 + 1.57 + return &mem->c; 1.58 +} 1.59 + 1.60 +void *ucx_mempool_calloc(UcxMempool *pool, size_t nelem, size_t elsize) { 1.61 + void *ptr = ucx_mempool_malloc(pool, nelem*elsize); 1.62 + if(ptr == NULL) { 1.63 + return NULL; 1.64 + } 1.65 + memset(ptr, 0, nelem * elsize); 1.66 + return ptr; 1.67 +} 1.68 + 1.69 +void *ucx_mempool_realloc(UcxMempool *pool, void *ptr, size_t n) { 1.70 + void *mem = ((char*)ptr) - sizeof(ucx_destructor); 1.71 + for(int i=0;i<pool->ndata;i++) { 1.72 + if(pool->data[i] == mem) { 1.73 + mem == realloc(mem, n); 1.74 + pool->data[i] = mem; 1.75 + return mem; 1.76 + } 1.77 + } 1.78 +} 1.79 + 1.80 +void ucx_mempool_free(UcxMempool *pool) { 1.81 + ucx_memchunk *chunk; 1.82 + for(int i=0;i<pool->ndata;i++) { 1.83 + chunk = (ucx_memchunk*) pool->data[i]; 1.84 + if(chunk->destructor != NULL) { 1.85 + chunk->destructor(&chunk->c); 1.86 + } 1.87 + free(chunk); 1.88 + } 1.89 + free(pool->data); 1.90 + free(pool); 1.91 +} 1.92 + 1.93 +void ucx_mempool_set_destr(void *ptr, ucx_destructor func) { 1.94 + *(ucx_destructor*)((char*)ptr-sizeof(ucx_destructor)) = func; 1.95 +} 1.96 + 1.97 +void ucx_mempool_reg_destr(UcxMempool *pool, void *ptr, ucx_destructor destr) { 1.98 + ucx_regdestr *rd = (ucx_regdestr*)ucx_mempool_malloc( 1.99 + pool, 1.100 + sizeof(ucx_regdestr)); 1.101 + rd->destructor = destr; 1.102 + rd->ptr; 1.103 + ucx_mempool_set_destr(rd, ucx_mempool_shared_destr); 1.104 +}