Last active
December 25, 2015 17:49
-
-
Save dinocore1/7015535 to your computer and use it in GitHub Desktop.
testing storage_pool
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template<class T> | |
class storage_pool { | |
static const size_t mBlockSize = sizeof(T); | |
typedef union freelist_t {char data[mBlockSize];freelist_t* next;} freelist_t; | |
private: | |
int mUsed; | |
freelist_t* mFreelist; | |
public: | |
storage_pool() | |
: mUsed(0) | |
, mFreelist(0) {} | |
void add_block(void* block, size_t blocksize) { | |
freelist_t* p = (freelist_t*)block; | |
freelist_t* q = p; | |
for(size_t i=1;i<blocksize/sizeof(freelist_t);i++){ | |
p->next = &q[i]; | |
p = p->next; | |
} | |
p->next = mFreelist; | |
mFreelist = (freelist_t*)block; | |
} | |
bool empty() { | |
return mFreelist->next == 0; | |
} | |
T* malloc() { | |
if(empty()){ | |
return 0; | |
} | |
T* retval = (T*)&mFreelist->data; | |
mFreelist = mFreelist->next; | |
mUsed++; | |
return retval; | |
} | |
void free(T* ptr) { | |
freelist_t* next = mFreelist->next; | |
mFreelist = (freelist_t*)ptr; | |
mFreelist->next = next; | |
mUsed--; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment