00001 #include <stdlib.h>
00002 #include "mb_tools.h"
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022 struct _elmpool {
00023 int elm_sz;
00024 int inc_num;
00025 void *frees;
00026 void *blks;
00027 };
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039 elmpool_t *elmpool_new(int elm_sz, int inc_num) {
00040 int _elm_sz;
00041 elmpool_t *pool;
00042
00043 if(inc_num < 16)
00044 return NULL;
00045
00046 if(elm_sz >= sizeof(void *))
00047 _elm_sz = elm_sz;
00048 else
00049 _elm_sz = sizeof(void *);
00050
00051 pool = (elmpool_t *)malloc(sizeof(elmpool_t));
00052 if(pool == NULL)
00053 return NULL;
00054
00055 pool->elm_sz = _elm_sz;
00056 if(inc_num == 0)
00057 inc_num = 256;
00058 pool->inc_num = inc_num;
00059 pool->frees = NULL;
00060 pool->blks = NULL;
00061
00062 return pool;
00063 }
00064
00065 void *elmpool_elm_alloc(elmpool_t *pool) {
00066 void *blk, *elm;
00067 int elm_sz, inc_num;
00068 int i;
00069
00070 if(pool->frees == NULL) {
00071 inc_num = pool->inc_num;
00072 elm_sz = pool->elm_sz;
00073 blk = malloc(elm_sz * inc_num);
00074 if(blk == NULL)
00075 return NULL;
00076
00077 *(void **)blk = pool->blks;
00078 pool->blks = blk;
00079
00080 blk = blk + elm_sz;
00081 pool->frees = blk;
00082 for(i = 2; i < inc_num; i++) {
00083 *(void **)blk = blk + elm_sz;
00084 blk = *(void **)blk;
00085 }
00086 *(void **)blk = NULL;
00087 }
00088
00089 elm = pool->frees;
00090 pool->frees = *(void **)elm;
00091
00092 return elm;
00093 }
00094
00095 void elmpool_elm_free(elmpool_t *pool, void *elm) {
00096 *(void **)elm = pool->frees;
00097 pool->frees = elm;
00098 }
00099
00100 void elmpool_free(elmpool_t *pool) {
00101 void *blk, *next_blk;
00102
00103 blk = pool->blks;
00104 while(blk) {
00105 next_blk = *(void **)blk;
00106 free(blk);
00107 blk = next_blk;
00108 }
00109 }
00110
00111 #ifdef UNITTEST
00112
00113 #include <CUnit/Basic.h>
00114
00115 void test_elmpool(void) {
00116 elmpool_t *pool;
00117 void *elm;
00118 int i;
00119
00120 pool = elmpool_new(64, 16);
00121 for(i = 0; i < 15; i++) {
00122 elm = elmpool_elm_alloc(pool);
00123 CU_ASSERT(elm != NULL);
00124 }
00125 CU_ASSERT(pool->frees == NULL);
00126
00127 for(i = 0; i < 15; i++) {
00128 elm = elmpool_elm_alloc(pool);
00129 CU_ASSERT(elm != NULL);
00130 }
00131 CU_ASSERT(pool->frees == NULL);
00132
00133 elmpool_elm_free(pool, elm);
00134 CU_ASSERT(pool->frees == elm);
00135
00136 elm = elmpool_elm_alloc(pool);
00137 CU_ASSERT(elm != NULL);
00138 CU_ASSERT(pool->frees == NULL);
00139
00140 elmpool_free(pool);
00141 }
00142
00143 CU_pSuite get_tools_suite(void) {
00144 CU_pSuite suite;
00145
00146 suite = CU_add_suite("Suite_tools", NULL, NULL);
00147 CU_ADD_TEST(suite, test_elmpool);
00148
00149 return suite;
00150 }
00151
00152 #endif