| 1 | /* -*- C++ -*- */ |
| 2 | |
| 3 | /* |
| 4 | |
| 5 | Heap Layers: An Extensible Memory Allocation Infrastructure |
| 6 | |
| 7 | Copyright (C) 2000-2020 by Emery Berger |
| 8 | http://www.emeryberger.com |
| 9 | [email protected] |
| 10 | |
| 11 | Heap Layers is distributed under the terms of the Apache 2.0 license. |
| 12 | |
| 13 | You may obtain a copy of the License at |
| 14 | http://www.apache.org/licenses/LICENSE-2.0 |
| 15 | |
| 16 | */ |
| 17 | |
| 18 | #ifndef HL_FREELISTHEAP_H |
| 19 | #define HL_FREELISTHEAP_H |
| 20 | |
| 21 | /** |
| 22 | * @class FreelistHeap |
| 23 | * @brief Manage freed memory on a linked list. |
| 24 | * @warning This is for one "size class" only. |
| 25 | * |
| 26 | * Note that the linked list is threaded through the freed objects, |
| 27 | * meaning that such objects must be at least the size of a pointer. |
| 28 | */ |
| 29 | |
| 30 | #include <assert.h> |
| 31 | #include "utility/freesllist.h" |
| 32 | |
| 33 | namespace HL { |
| 34 | |
| 35 | template <class SuperHeap> |
| 36 | class FreelistHeap : public SuperHeap { |
| 37 | public: |
| 38 | |
| 39 | inline void * malloc (size_t sz) { |
| 40 | // Check the free list first. |
| 41 | void * ptr = _freelist.get(); |
| 42 | // If it's empty, get more memory; |
| 43 | // otherwise, advance the free list pointer. |
| 44 | if (!ptr) { |
| 45 | ptr = SuperHeap::malloc (sz); |
| 46 | } |
| 47 | return ptr; |
| 48 | } |
| 49 | |
| 50 | inline void free (void * ptr) { |
| 51 | if (!ptr) { |
| 52 | return; |
| 53 | } |
| 54 | _freelist.insert (ptr); |
| 55 | } |
| 56 | |
| 57 | inline void clear (void) { |
| 58 | void * ptr; |
| 59 | while ((ptr = _freelist.get())) { |
| 60 | SuperHeap::free (ptr); |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | private: |
| 65 | |
| 66 | FreeSLList _freelist; |
| 67 | |
| 68 | }; |
| 69 | |
| 70 | } |
| 71 | |
| 72 | #endif |