[176] | 1 | /* -*- C++ -*- */ |
---|
| 2 | |
---|
| 3 | #ifndef _SLOTHEAP_H_ |
---|
| 4 | #define _SLOTHEAP_H_ |
---|
| 5 | |
---|
| 6 | // NOTE: All size requests to malloc must be identical! |
---|
| 7 | |
---|
| 8 | /* |
---|
| 9 | |
---|
| 10 | A "slot" allocator. |
---|
| 11 | |
---|
| 12 | All allocations come from a fixed-size chunk of memory |
---|
| 13 | that is carved into a number of pieces. |
---|
| 14 | |
---|
| 15 | The "chunk" class must support the following methods: |
---|
| 16 | |
---|
| 17 | void * getSlot (void); // Returns NULL if there is no slot left. |
---|
| 18 | void putSlot (void *); // Puts a slot back into its chunk. |
---|
| 19 | |
---|
| 20 | */ |
---|
| 21 | |
---|
| 22 | #include <assert.h> |
---|
| 23 | |
---|
| 24 | #include "chunkheap.h" |
---|
| 25 | |
---|
| 26 | /* A "slot" heap. |
---|
| 27 | |
---|
| 28 | This heap reserves exactly one "chunk" that is divided into |
---|
| 29 | a number of fixed-size slots. When the chunk is used up, |
---|
| 30 | the heap requests another one. */ |
---|
| 31 | |
---|
| 32 | template <int chunkSize, int slotSize, class Super> |
---|
| 33 | class SlotInterface; |
---|
| 34 | |
---|
| 35 | template <int chunkSize, int slotSize, class Super> |
---|
| 36 | class SlotHeap : public SlotInterface<chunkSize, slotSize, ChunkHeap<chunkSize, slotSize, Super> >{}; |
---|
| 37 | |
---|
| 38 | template <int chunkSize, int slotSize, class Super> |
---|
| 39 | class SlotInterface : public Super { |
---|
| 40 | public: |
---|
| 41 | |
---|
| 42 | SlotInterface (void) |
---|
| 43 | : currentChunk (new (Super::malloc(chunkSize)) Chunk<chunkSize, slotSize>) |
---|
| 44 | {} |
---|
| 45 | |
---|
| 46 | inline void * malloc (size_t sz) { |
---|
| 47 | assert (sz == slotSize); |
---|
| 48 | // Use up all of the slots in one chunk, |
---|
| 49 | // and get another chunk if we need one. |
---|
| 50 | void * ptr = currentChunk->getSlot(); |
---|
| 51 | if (ptr == NULL) { |
---|
| 52 | // This chunk is empty -- get another one. |
---|
| 53 | currentChunk = new (Super::malloc(chunkSize)) Chunk<chunkSize, slotSize>; |
---|
| 54 | ptr = currentChunk->getSlot(); |
---|
| 55 | } |
---|
| 56 | assert (ptr != NULL); |
---|
| 57 | return ptr; |
---|
| 58 | } |
---|
| 59 | |
---|
| 60 | inline void free (void * ptr) { |
---|
| 61 | // If this object belongs to "our" chunk, |
---|
| 62 | // free it directly; otherwise, pass it up. |
---|
| 63 | if (getChunk(ptr) == currentChunk) { |
---|
| 64 | currentChunk->putSlot (ptr); |
---|
| 65 | } else { |
---|
| 66 | Super::free (ptr); |
---|
| 67 | } |
---|
| 68 | } |
---|
| 69 | |
---|
| 70 | private: |
---|
| 71 | |
---|
| 72 | Chunk<chunkSize, slotSize> * currentChunk; |
---|
| 73 | |
---|
| 74 | }; |
---|
| 75 | |
---|
| 76 | #endif |
---|