| 1 | /* -*- C++ -*- */ |
| 2 | |
| 3 | #ifndef HL_BOUNDEDFREELISTHEAP_H_ |
| 4 | #define HL_BOUNDEDFREELISTHEAP_H_ |
| 5 | |
| 6 | // Beware -- this is for one "size class" only!! |
| 7 | |
| 8 | #include <cstdlib> |
| 9 | |
| 10 | template <int numObjects, class Super> |
| 11 | class BoundedFreeListHeap : public Super { |
| 12 | public: |
| 13 | |
| 14 | BoundedFreeListHeap() |
| 15 | : nObjects (0), |
| 16 | myFreeList (NULL) |
| 17 | {} |
| 18 | |
| 19 | ~BoundedFreeListHeap() |
| 20 | { |
| 21 | clear(); |
| 22 | } |
| 23 | |
| 24 | inline void * malloc (size_t sz) { |
| 25 | // Check the free list first. |
| 26 | void * ptr = myFreeList; |
| 27 | if (ptr == NULL) { |
| 28 | ptr = Super::malloc (sz); |
| 29 | } else { |
| 30 | myFreeList = myFreeList->next; |
| 31 | } |
| 32 | return ptr; |
| 33 | } |
| 34 | |
| 35 | inline void free (void * ptr) { |
| 36 | if (nObjects < numObjects) { |
| 37 | // Add this object to the free list. |
| 38 | ((freeObject *) ptr)->next = myFreeList; |
| 39 | myFreeList = (freeObject *) ptr; |
| 40 | nObjects++; |
| 41 | } else { |
| 42 | clear(); |
| 43 | // Super::free (ptr); |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | inline void clear (void) { |
| 48 | // Delete everything on the free list. |
| 49 | void * ptr = myFreeList; |
| 50 | while (ptr != NULL) { |
| 51 | void * oldptr = ptr; |
| 52 | ptr = (void *) ((freeObject *) ptr)->next; |
| 53 | Super::free (oldptr); |
| 54 | } |
| 55 | myFreeList = NULL; |
| 56 | nObjects = 0; |
| 57 | } |
| 58 | |
| 59 | private: |
| 60 | |
| 61 | class freeObject { |
| 62 | public: |
| 63 | freeObject * next; |
| 64 | }; |
| 65 | |
| 66 | int nObjects; |
| 67 | freeObject * myFreeList; |
| 68 | }; |
| 69 | |
| 70 | #endif |