1 module libraw.alloc; 2 3 import libraw.const_; 4 5 import core.stdc.stdlib; 6 import core.stdc..string; 7 8 9 enum LIBRAW_MSIZE = 512; 10 11 extern(C++) class libraw_memmgr; 12 13 /+extern(C++) class libraw_memmgr { 14 this(unsigned ee) 15 { 16 extra_bytes = ee; 17 size_t alloc_sz = LIBRAW_MSIZE * (void*).sizeof; 18 mems = cast(void**).malloc(alloc_sz); 19 memset(mems, 0, alloc_sz); 20 } 21 ~this() 22 { 23 cleanup(); 24 .free(mems); 25 } 26 void *malloc(size_t sz) 27 { 28 version (LIBRAW_USE_CALLOC_INSTEAD_OF_MALLOC) { 29 void *ptr = .calloc(sz + extra_bytes,1); 30 } else { 31 void *ptr = .malloc(sz + extra_bytes); 32 } 33 mem_ptr(ptr); 34 return ptr; 35 } 36 void *calloc(size_t n, size_t sz) 37 { 38 void *ptr = .calloc(n + (extra_bytes + sz - 1) / (sz ? sz : 1), sz); 39 mem_ptr(ptr); 40 return ptr; 41 } 42 void *realloc(void *ptr, size_t newsz) 43 { 44 void *ret = .realloc(ptr, newsz + extra_bytes); 45 forget_ptr(ptr); 46 mem_ptr(ret); 47 return ret; 48 } 49 void free(void *ptr) 50 { 51 forget_ptr(ptr); 52 .free(ptr); 53 } 54 void cleanup(void) 55 { 56 for (int i = 0; i < LIBRAW_MSIZE; i++) 57 if (mems[i]) 58 { 59 .free(mems[i]); 60 mems[i] = NULL; 61 } 62 } 63 64 private: 65 void **mems; 66 unsigned extra_bytes; 67 void mem_ptr(void *ptr) 68 { 69 if (ptr) 70 { 71 for (int i = 0; i < LIBRAW_MSIZE-1; i++) 72 if (!mems[i]) 73 { 74 mems[i] = ptr; 75 return; 76 } 77 version (LIBRAW_MEMPOOL_CHECK) { 78 /* remember ptr in last mems item to be free'ed at cleanup */ 79 if(!mems[LIBRAW_MSIZE-1]) mems[LIBRAW_MSIZE-1] = ptr; 80 throw LIBRAW_EXCEPTION_MEMPOOL; 81 } 82 } 83 } 84 void forget_ptr(void *ptr) 85 { 86 if (ptr) 87 for (int i = 0; i < LIBRAW_MSIZE; i++) 88 if (mems[i] == ptr) 89 { 90 mems[i] = NULL; 91 break; 92 } 93 } 94 }+/