| 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 | |
| 19 | /* |
| 20 | |
| 21 | StaticHeap: manage a fixed range of memory. |
| 22 | |
| 23 | */ |
| 24 | |
| 25 | #ifndef HL_STATICHEAP_H |
| 26 | #define HL_STATICHEAP_H |
| 27 | |
| 28 | #include <cstddef> |
| 29 | |
| 30 | namespace HL { |
| 31 | |
| 32 | template <int MemorySize> |
| 33 | class StaticHeap { |
| 34 | public: |
| 35 | |
| 36 | StaticHeap() |
| 37 | : _ptr (&_buf[0]), |
| 38 | _remaining (MemorySize) |
| 39 | {} |
| 40 | |
| 41 | enum { Alignment = 1 }; |
| 42 | |
| 43 | inline void * malloc (size_t sz) { |
| 44 | if (_remaining < sz) { |
| 45 | return NULL; |
| 46 | } |
| 47 | void * p = _ptr; |
| 48 | _ptr += sz; |
| 49 | _remaining -= sz; |
| 50 | return p; |
| 51 | } |
| 52 | |
| 53 | void free (void *) {} |
| 54 | int remove (void *) { return 0; } |
| 55 | |
| 56 | int isValid (void * ptr) { |
| 57 | return (((size_t) ptr >= (size_t) _buf) && |
| 58 | ((size_t) ptr < (size_t) _buf)); |
| 59 | } |
| 60 | |
| 61 | private: |
| 62 | |
| 63 | // Disable copying and assignment. |
| 64 | StaticHeap (const StaticHeap&); |
| 65 | StaticHeap& operator= (const StaticHeap&); |
| 66 | |
| 67 | char _buf[MemorySize]; |
| 68 | char * _ptr; |
| 69 | size_t _remaining; |
| 70 | }; |
| 71 | |
| 72 | } |
| 73 | |
| 74 | #endif |