Eneboo - Documentación para desarrolladores
|
00001 /* -*- C++ -*- */ 00002 00014 #ifndef _ZONEHEAP_H_ 00015 #define _ZONEHEAP_H_ 00016 00017 #include <assert.h> 00018 00019 namespace HL { 00020 00021 template <class Super, size_t ChunkSize> 00022 class ZoneHeap : public Super { 00023 public: 00024 00025 ZoneHeap (void) 00026 : sizeRemaining (-1), 00027 currentArena (NULL), 00028 pastArenas (NULL) 00029 {} 00030 00031 ~ZoneHeap (void) 00032 { 00033 // printf ("deleting arenas!\n"); 00034 // Delete all of our arenas. 00035 Arena * ptr = pastArenas; 00036 while (ptr != NULL) { 00037 void * oldPtr = (void *) ptr; 00038 ptr = ptr->nextArena; 00039 //printf ("deleting %x\n", ptr); 00040 Super::free (oldPtr); 00041 } 00042 if (currentArena != NULL) 00043 //printf ("deleting %x\n", currentArena); 00044 Super::free (currentArena); 00045 } 00046 00047 inline void * malloc (size_t sz) { 00048 void * ptr = zoneMalloc (sz); 00049 return ptr; 00050 } 00051 00053 inline void free (void *) {} 00054 00056 inline int remove (void *) { return 0; } 00057 00058 00059 private: 00060 00061 inline static size_t align (int sz) { 00062 return (sz + (sizeof(double) - 1)) & ~(sizeof(double) - 1); 00063 } 00064 00065 inline void * zoneMalloc (size_t sz) { 00066 void * ptr; 00067 // Round up size to an aligned value. 00068 sz = align (sz); 00069 // Get more space in our arena if there's not enough room in this one. 00070 if ((currentArena == NULL) || (sizeRemaining < (int) sz)) { 00071 // First, add this arena to our past arena list. 00072 if (currentArena != NULL) { 00073 currentArena->nextArena = pastArenas; 00074 pastArenas = currentArena; 00075 } 00076 // Now get more memory. 00077 size_t allocSize = ChunkSize; 00078 if (allocSize < sz) { 00079 allocSize = sz; 00080 } 00081 currentArena = 00082 (Arena *) Super::malloc (allocSize + sizeof(Arena)); 00083 if (currentArena == NULL) { 00084 return NULL; 00085 } 00086 currentArena->arenaSpace = (char *) (currentArena + 1); 00087 currentArena->nextArena = NULL; 00088 sizeRemaining = ChunkSize; 00089 } 00090 // Bump the pointer and update the amount of memory remaining. 00091 sizeRemaining -= sz; 00092 ptr = currentArena->arenaSpace; 00093 currentArena->arenaSpace += sz; 00094 assert (ptr != NULL); 00095 return ptr; 00096 } 00097 00098 class Arena { 00099 public: 00100 Arena * nextArena; 00101 char * arenaSpace; 00102 double _dummy; // For alignment. 00103 }; 00104 00106 long sizeRemaining; 00107 00109 Arena * currentArena; 00110 00112 Arena * pastArenas; 00113 }; 00114 00115 } 00116 00117 #endif