freelist.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #ifndef _FREELIST_H
  2. #define _FREELIST_H
  3. #include <bfc/wasabi_std.h>
  4. #include <bfc/memblock.h>
  5. #include <bfc/ptrlist.h>
  6. // actual implementation
  7. class FreelistPriv {
  8. protected:
  9. FreelistPriv();
  10. ~FreelistPriv();
  11. void *getRecord(int typesize, int blocksize, int initialblocksize);
  12. void freeRecord(void *rec);
  13. private:
  14. int total_allocated;
  15. typedef uint8_t MBT;
  16. class FLMemBlock : public MemBlock<MBT> {
  17. public:
  18. FLMemBlock(int siz) : MemBlock<MBT>(siz) {
  19. freelist = getMemory();
  20. nallocated = 0;
  21. }
  22. void *freelist;
  23. int nallocated; // # of records assigned from block
  24. };
  25. PtrList< FLMemBlock > blocks; // the blocks of mem we alloc from
  26. };
  27. // type-safe template
  28. static const int DEF_BLOCKSIZE=250;
  29. template
  30. <class T, int BLOCKSIZE=DEF_BLOCKSIZE, int INITIALBLOCKSIZE=DEF_BLOCKSIZE, int ALIGNMENT=4>
  31. class Freelist : private FreelistPriv {
  32. public:
  33. // just returns the memory, you have to call constructor manually
  34. T *getRecord() {
  35. return static_cast<T *>(FreelistPriv::getRecord(itemsize(), BLOCKSIZE, INITIALBLOCKSIZE));
  36. }
  37. // creates object via default constructor
  38. T *newRecord() {
  39. T *ret = getRecord();
  40. #ifdef FORTIFY
  41. #undef new
  42. #endif
  43. new(ret) T;
  44. #ifdef FORTIFY
  45. #define new ZFortify_New
  46. #endif
  47. return ret;
  48. }
  49. // creates object via 1-parameter constructor
  50. template<class P1>
  51. T *newRecord(P1 p1) {
  52. T *ret = getRecord();
  53. #ifdef FORTIFY
  54. #undef new
  55. #endif
  56. new(ret) T(p1);
  57. #ifdef FORTIFY
  58. #define new ZFortify_New
  59. #endif
  60. return ret;
  61. }
  62. // just frees it, you have to call destructor manually
  63. void freeRecord(T *record) { FreelistPriv::freeRecord(record); }
  64. // calls delete for you, and frees it
  65. void deleteRecord(T *record) {
  66. if (record != NULL) {
  67. record->~T();
  68. freeRecord(record);
  69. }
  70. }
  71. void deletePtrList(PtrList<T> *list) {
  72. ASSERT(list != NULL);
  73. for (int i = 0; i < list->getNumItems(); i++) {
  74. deleteRecord(list->enumItem(i));
  75. }
  76. list->removeAll();
  77. }
  78. protected:
  79. int itemsize() { return (sizeof(T) + (ALIGNMENT-1)) - (sizeof(T) % ALIGNMENT); }
  80. };
  81. #endif