| 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_SIZEOWNERHEAP_H_ |
| 19 | #define HL_SIZEOWNERHEAP_H_ |
| 20 | |
| 21 | #include <assert.h> |
| 22 | |
| 23 | #include "addheap.h" |
| 24 | |
| 25 | /** |
| 26 | * @class SizeOwnerHeap |
| 27 | * @brief Adds object size and owner heap information. |
| 28 | */ |
| 29 | |
| 30 | namespace HL { |
| 31 | |
| 32 | template <class Heap> |
| 33 | class SizeOwner { |
| 34 | public: |
| 35 | union tag { |
| 36 | struct { |
| 37 | size_t size; |
| 38 | Heap * owner; |
| 39 | } s; |
| 40 | double dummy; |
| 41 | }; |
| 42 | }; |
| 43 | |
| 44 | template <class Super> |
| 45 | class SizeOwnerHeap : public AddHeap<SizeOwner<Super>, Super> { |
| 46 | private: |
| 47 | |
| 48 | typedef AddHeap<SizeOwner<Super>, Super> SuperHeap; |
| 49 | |
| 50 | public: |
| 51 | |
| 52 | inline void * malloc (size_t sz) { |
| 53 | void * ptr = SuperHeap::malloc (sz); |
| 54 | // Store the requested size. |
| 55 | SizeOwner<Super> * so = (SizeOwner<Super> *) ptr; |
| 56 | so->s.size = sz; |
| 57 | so->s.owner = this; |
| 58 | // Store the owner. |
| 59 | return (void *) (so + 1); |
| 60 | } |
| 61 | |
| 62 | inline void free (void * ptr) { |
| 63 | void * origPtr = (void *) ((SizeOwner<Super> *) ptr - 1); |
| 64 | SuperHeap::free (origPtr); |
| 65 | } |
| 66 | |
| 67 | static inline Super * owner (void * ptr) { |
| 68 | SizeOwner<Super> * so = (SizeOwner<Super> *) ptr - 1; |
| 69 | return so->s.owner; |
| 70 | } |
| 71 | |
| 72 | static inline size_t size (void * ptr) { |
| 73 | SizeOwner<Super> * so = (SizeOwner<Super> *) ptr - 1; |
| 74 | return so->s.size; |
| 75 | } |
| 76 | }; |
| 77 | |
| 78 | } |
| 79 | |
| 80 | #endif |