Sat, 31 Dec 2011 22:46:27 +0100
fixed ultra fail + renamed files from mpool to mempool
1 /*
2 *
3 */
5 #include <stdlib.h>
6 #include <string.h>
7 #include <stdio.h>
8 #include <errno.h>
10 #include "mpool.h"
12 typedef struct {
13 ucx_destructor destructor;
14 char c;
15 } ucx_memchunk;
17 typedef struct {
18 ucx_destructor destructor;
19 void *ptr;
20 } ucx_regdestr;
22 void ucx_mempool_shared_destr(void* ptr) {
23 ucx_regdestr *rd = (ucx_regdestr*)ptr;
24 rd->destructor(rd->ptr);
25 }
27 UcxMempool *ucx_mempool_new(size_t n) {
28 UcxMempool *pool = (UcxMempool*)malloc(sizeof(UcxMempool));
29 if (pool == NULL) return NULL;
31 pool->data = malloc(n * sizeof(void*));
32 if (pool->data == NULL) {
33 free(pool);
34 return NULL;
35 }
37 pool->ndata = 0;
38 pool->size = n;
39 return pool;
40 }
42 int ucx_mempool_chcap(UcxMempool *pool, size_t newcap) {
43 void **data = realloc(pool->data, newcap*sizeof(void*));
44 if (data == NULL) {
45 return ENOMEM;
46 } else {
47 pool->data = data;
48 pool->size = newcap;
49 return EXIT_SUCCESS;
50 }
51 }
53 void *ucx_mempool_malloc(UcxMempool *pool, size_t n) {
54 ucx_memchunk *mem = (ucx_memchunk*)malloc(sizeof(ucx_destructor) + n);
55 if (mem == NULL) return NULL;
57 if (pool->ndata >= pool->size) {
58 ucx_mempool_chcap(pool, pool->size + 16);
59 }
61 mem->destructor = NULL;
62 pool->data[pool->ndata] = mem;
63 pool->ndata++;
65 return &mem->c;
66 }
68 void *ucx_mempool_calloc(UcxMempool *pool, size_t nelem, size_t elsize) {
69 void *ptr = ucx_mempool_malloc(pool, nelem*elsize);
70 if(ptr == NULL) {
71 return NULL;
72 }
73 memset(ptr, 0, nelem * elsize);
74 return ptr;
75 }
77 void *ucx_mempool_realloc(UcxMempool *pool, void *ptr, size_t n) {
78 void *mem = ((char*)ptr) - sizeof(ucx_destructor);
79 char *newm = (char*) realloc(mem, n + sizeof(ucx_destructor));
80 if (newm == NULL) return NULL;
81 if (mem != newm) {
82 for(int i=0;i<pool->ndata;i++) {
83 if(pool->data[i] == mem) {
84 pool->data[i] = newm;
85 return ((char*) newm) + sizeof(ucx_destructor);
86 }
87 }
88 fprintf(stderr, "FATAL: %8x not in mpool %8x\n", mem, pool);
89 exit(1);
90 } else {
91 return ((char*) newm) + sizeof(ucx_destructor);
92 }
93 }
95 void ucx_mempool_free(UcxMempool *pool) {
96 ucx_memchunk *chunk;
97 for(int i=0;i<pool->ndata;i++) {
98 chunk = (ucx_memchunk*) pool->data[i];
99 if(chunk->destructor != NULL) {
100 chunk->destructor(&chunk->c);
101 }
102 free(chunk);
103 }
104 free(pool->data);
105 free(pool);
106 }
108 void ucx_mempool_set_destr(void *ptr, ucx_destructor func) {
109 *(ucx_destructor*)((char*)ptr-sizeof(ucx_destructor)) = func;
110 }
112 void ucx_mempool_reg_destr(UcxMempool *pool, void *ptr, ucx_destructor destr) {
113 ucx_regdestr *rd = (ucx_regdestr*)ucx_mempool_malloc(
114 pool,
115 sizeof(ucx_regdestr));
116 rd->destructor = destr;
117 rd->ptr = ptr;
118 ucx_mempool_set_destr(rd, ucx_mempool_shared_destr);
119 }