Eneboo - Documentación para desarrolladores
|
00001 /* -*- C++ -*- */ 00002 00003 #ifndef _LAZYSLOTHEAP_H_ 00004 #define _LAZYSLOTHEAP_H_ 00005 00006 /* 00007 This heap manages memory in units of Chunks. 00008 malloc returns a slot within a chunk, 00009 while free returns slots back to a chunk. 00010 00011 We completely exhaust the first chunk before we ever get another one. 00012 Once a chunk is COMPLETELY empty, it is returned to the superheap. 00013 */ 00014 00015 #include <assert.h> 00016 #include <new.h> 00017 00018 #include "chunk.h" 00019 00020 template <int chunkSize, int slotSize, class Super> 00021 class LazySlotHeap : public Super { 00022 public: 00023 00024 LazySlotHeap (void) 00025 : myChunk (new (Super::malloc (chunkSize)) Chunk<chunkSize, slotSize>()) 00026 {} 00027 00028 virtual ~LazySlotHeap (void) 00029 { 00030 // Give up our chunk. 00031 Super::free (myChunk); 00032 } 00033 00034 inline void * malloc (size_t sz) { 00035 assert (sz <= chunkSize); 00036 void * ptr = myChunk->getSlot(); 00037 if (ptr == NULL) { 00038 myChunk = new (Super::malloc (chunkSize)) Chunk<chunkSize, slotSize>(); 00039 ptr = myChunk->getSlot(); 00040 assert (ptr != NULL); 00041 } 00042 return ptr; 00043 } 00044 00045 inline void free (void * ptr) { 00047 Chunk<chunkSize, slotSize> * ch = Chunk<chunkSize, slotSize>::getChunk (ptr); 00048 ch->putSlot (ptr); 00049 // Once the chunk is completely empty, free it. 00050 if (ch->getNumSlotsAvailable() == ch->getNumSlots()) { 00051 if (ch == myChunk) { 00052 // If this was 'our' chunk, get another one. 00053 myChunk = new (Super::malloc (chunkSize)) Chunk<chunkSize, slotSize>(); 00054 } 00055 Super::free (ch); 00056 } 00057 } 00058 00059 protected: 00060 00061 inline static size_t size (void * ptr) 00062 { 00063 return slotSize; 00064 } 00065 00066 00067 private: 00068 00069 Chunk<chunkSize, slotSize> * myChunk; 00070 00071 }; 00072 00073 00074 #endif