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 Once a chunk is COMPLETELY empty, it is returned to the superheap. 00012 */ 00013 00014 #include <assert.h> 00015 #include <new.h> 00016 00017 template <int chunkSize, int slotSize, class Super> 00018 class LazySlotHeap : public Super { 00019 public: 00020 00021 LazySlotHeap (void) 00022 : myChunk (new (Super::malloc (sz)) Chunk<chunkSize, slotSize>()) 00023 {} 00024 00025 ~LazySlotHeap (void) 00026 { 00027 // Give up our chunk. 00028 Super::free (myChunk); 00029 } 00030 00031 inline void * malloc (size_t sz) { 00032 assert (sz == chunkSize); 00033 void * ptr = myChunk->getSlot(); 00034 if (ptr == NULL) { 00035 myChunk = new (Super::malloc (sz)) Chunk<chunkSize, slotSize>(); 00036 ptr = myChunk->getSlot(); 00037 assert (ptr != NULL); 00038 } 00039 return ; 00040 } 00041 00042 inline void free (void * ptr) { 00044 Chunk<chunkSize, slotSize> * ch = Chunk<chunkSize, slotSize>::getChunk (ptr); 00045 ch->putSlot (ptr); 00046 // Once the chunk is completely empty, free it. 00047 if (ch->getNumSlotsAvailable() == ch->getNumSlots()) { 00048 if (ch == myChunk) { 00049 // If this was 'our' chunk, get another one. 00050 myChunk = new (Super::malloc (sz)) Chunk<chunkSize, slotSize>(); 00051 } 00052 Super::free (ch); 00053 } 00054 } 00055 00056 private: 00057 00058 Chunk<chunkSize, slotSize> * myChunk; 00059 00060 }; 00061 00062 00063 #endif