Tue, 09 Oct 2012 16:46:29 +0200
some fixes
1 /*
2 *
3 */
5 #include <stdlib.h>
6 #include <string.h>
7 #include <stdio.h>
9 #include "mempool.h"
11 typedef struct {
12 ucx_destructor destructor;
13 char c;
14 } ucx_memchunk;
16 typedef struct {
17 ucx_destructor destructor;
18 void *ptr;
19 } ucx_regdestr;
21 void ucx_mempool_shared_destr(void* ptr) {
22 ucx_regdestr *rd = (ucx_regdestr*)ptr;
23 rd->destructor(rd->ptr);
24 }
26 UcxMempool *ucx_mempool_new(size_t n) {
27 UcxMempool *pool = (UcxMempool*)malloc(sizeof(UcxMempool));
28 if (pool == NULL) return NULL;
30 pool->data = malloc(n * sizeof(void*));
31 if (pool->data == NULL) {
32 free(pool);
33 return NULL;
34 }
36 pool->ndata = 0;
37 pool->size = n;
38 return pool;
39 }
41 int ucx_mempool_chcap(UcxMempool *pool, size_t newcap) {
42 void **data = realloc(pool->data, newcap*sizeof(void*));
43 if (data == NULL) {
44 return 1;
45 } else {
46 pool->data = data;
47 pool->size = newcap;
48 return EXIT_SUCCESS;
49 }
50 }
52 void *ucx_mempool_malloc(UcxMempool *pool, size_t n) {
53 ucx_memchunk *mem = (ucx_memchunk*)malloc(sizeof(ucx_destructor) + n);
54 if (mem == NULL) return NULL;
56 if (pool->ndata >= pool->size) {
57 ucx_mempool_chcap(pool, pool->size + 16);
58 }
60 mem->destructor = NULL;
61 pool->data[pool->ndata] = mem;
62 pool->ndata++;
64 return &mem->c;
65 }
67 void *ucx_mempool_calloc(UcxMempool *pool, size_t nelem, size_t elsize) {
68 void *ptr = ucx_mempool_malloc(pool, nelem*elsize);
69 if(ptr == NULL) {
70 return NULL;
71 }
72 memset(ptr, 0, nelem * elsize);
73 return ptr;
74 }
76 void *ucx_mempool_realloc(UcxMempool *pool, void *ptr, size_t n) {
77 char *mem = ((char*)ptr) - sizeof(ucx_destructor);
78 char *newm = (char*) realloc(mem, n + sizeof(ucx_destructor));
79 if (newm == NULL) return NULL;
80 if (mem != newm) {
81 for(int i=0;i<pool->ndata;i++) {
82 if(pool->data[i] == mem) {
83 pool->data[i] = newm;
84 return newm + sizeof(ucx_destructor);
85 }
86 }
87 fprintf(stderr, "FATAL: %8x not in mpool %8x\n", ptr, pool);
88 exit(1);
89 } else {
90 return newm + sizeof(ucx_destructor);
91 }
92 }
94 void ucx_mempool_free(UcxMempool *pool) {
95 ucx_memchunk *chunk;
96 for(int i=0;i<pool->ndata;i++) {
97 chunk = (ucx_memchunk*) pool->data[i];
98 if(chunk->destructor != NULL) {
99 chunk->destructor(&chunk->c);
100 }
101 free(chunk);
102 }
103 free(pool->data);
104 free(pool);
105 }
107 void ucx_mempool_set_destr(void *ptr, ucx_destructor func) {
108 *(ucx_destructor*)((char*)ptr-sizeof(ucx_destructor)) = func;
109 }
111 void ucx_mempool_reg_destr(UcxMempool *pool, void *ptr, ucx_destructor destr) {
112 ucx_regdestr *rd = (ucx_regdestr*)ucx_mempool_malloc(
113 pool,
114 sizeof(ucx_regdestr));
115 rd->destructor = destr;
116 rd->ptr = ptr;
117 ucx_mempool_set_destr(rd, ucx_mempool_shared_destr);
118 }