1 | /* -*- C++ -*- */ |
---|
2 | |
---|
3 | #ifndef _LAZYSLOTHEAP_H_ |
---|
4 | #define _LAZYSLOTHEAP_H_ |
---|
5 | |
---|
6 | /* |
---|
7 | This heap manages memory in units of Chunks. |
---|
8 | malloc returns a slot within a chunk, |
---|
9 | while free returns slots back to a chunk. |
---|
10 | |
---|
11 | Once a chunk is COMPLETELY empty, it is returned to the superheap. |
---|
12 | */ |
---|
13 | |
---|
14 | #include <assert.h> |
---|
15 | #include <new.h> |
---|
16 | |
---|
17 | template <int chunkSize, int slotSize, class Super> |
---|
18 | class LazySlotHeap : public Super { |
---|
19 | public: |
---|
20 | |
---|
21 | LazySlotHeap (void) |
---|
22 | : myChunk (new (Super::malloc (sz)) Chunk<chunkSize, slotSize>()) |
---|
23 | {} |
---|
24 | |
---|
25 | ~LazySlotHeap (void) |
---|
26 | { |
---|
27 | // Give up our chunk. |
---|
28 | Super::free (myChunk); |
---|
29 | } |
---|
30 | |
---|
31 | inline void * malloc (size_t sz) { |
---|
32 | assert (sz == chunkSize); |
---|
33 | void * ptr = myChunk->getSlot(); |
---|
34 | if (ptr == NULL) { |
---|
35 | myChunk = new (Super::malloc (sz)) Chunk<chunkSize, slotSize>(); |
---|
36 | ptr = myChunk->getSlot(); |
---|
37 | assert (ptr != NULL); |
---|
38 | } |
---|
39 | return ; |
---|
40 | } |
---|
41 | |
---|
42 | inline void free (void * ptr) { |
---|
43 | /// Return a slot to its chunk. |
---|
44 | Chunk<chunkSize, slotSize> * ch = Chunk<chunkSize, slotSize>::getChunk (ptr); |
---|
45 | ch->putSlot (ptr); |
---|
46 | // Once the chunk is completely empty, free it. |
---|
47 | if (ch->getNumSlotsAvailable() == ch->getNumSlots()) { |
---|
48 | if (ch == myChunk) { |
---|
49 | // If this was 'our' chunk, get another one. |
---|
50 | myChunk = new (Super::malloc (sz)) Chunk<chunkSize, slotSize>(); |
---|
51 | } |
---|
52 | Super::free (ch); |
---|
53 | } |
---|
54 | } |
---|
55 | |
---|
56 | private: |
---|
57 | |
---|
58 | Chunk<chunkSize, slotSize> * myChunk; |
---|
59 | |
---|
60 | }; |
---|
61 | |
---|
62 | |
---|
63 | #endif |
---|