libpromeki 1.0.0-alpha
PROfessional MEdia toolKIt
 
Loading...
Searching...
No Matches
mempool.h
Go to the documentation of this file.
1
8#pragma once
9
10
11#include <promeki/config.h>
12#if PROMEKI_ENABLE_CORE
13#include <cstddef>
14#include <algorithm>
15#include <promeki/namespace.h>
16#include <promeki/mutex.h>
17#include <promeki/string.h>
18#include <promeki/map.h>
19#include <promeki/set.h>
20
21PROMEKI_NAMESPACE_BEGIN
22
33class MemPool {
34 public:
38 struct Stats {
39 size_t totalFree;
40 size_t totalUsed;
41 size_t numFreeBlocks;
42 size_t numAllocatedBlocks;
43 size_t largestFreeBlock;
44 };
45
49 class Block {
50 public:
51 bool allocated = false;
52 intptr_t address = 0;
53 size_t size = 0;
54 size_t alignment = 1;
55
57 bool operator<(const Block &other) const { return address < other.address; }
58
64 uintptr_t alignedAddress(size_t align) const {
65 uintptr_t _align = align - 1;
66 return (address + _align) & ~(_align);
67 }
68
73 uintptr_t alignedAddress() const { return alignedAddress(alignment); }
74
80 size_t padding(size_t align) const {
81 return align > 1 ? alignedAddress(align) - address : 0;
82 }
83
88 size_t padding() const { return padding(alignment); }
89
95 bool follows(const Block &block) const {
96 return static_cast<uintptr_t>(block.address) + block.size ==
97 static_cast<uintptr_t>(address);
98 }
99 };
100
106 static bool isValidAlignment(size_t val) { return (val > 0) && !(val & (val - 1)); }
107
108 using BlockSet = ::promeki::Set<Block>;
109 using BlockMap = ::promeki::Map<uintptr_t, Block>;
110
112 MemPool();
113
119 void addRegion(uintptr_t startingAddress, size_t size);
120
126 void addRegion(void *startingAddress, size_t size) {
127 addRegion(reinterpret_cast<uintptr_t>(startingAddress), size);
128 return;
129 }
130
132 const String &name() const { return _name; }
133
138 void setName(const String &val) {
139 _name = val;
140 return;
141 }
142
147 Stats stats() const;
148
153 BlockSet memoryMap() const;
154
156 void dump() const;
157
164 void *allocate(size_t size, size_t alignment = 1);
165
173 void free(void *ptr);
174
175 private:
176 String _name;
177 mutable Mutex _mutex;
178 BlockSet _freeBlocks;
179 BlockMap _allocatedBlocks;
180};
181
182PROMEKI_NAMESPACE_END
183
184#endif // PROMEKI_ENABLE_CORE