-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils_memory.hpp
469 lines (422 loc) · 15.4 KB
/
utils_memory.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
#ifndef UTILS_MEMORY_HPP
#define UTILS_MEMORY_HPP
#define UTILS_MEMORY_ALLOC_LOG 0
#define UTILS_MEMORY_NEW_LOG 1
#include "utils_compiler.hpp"
#include "utils_traits.hpp"
#include <algorithm>
#include <vector>
#include <memory>
#include <cstring>
#if UTILS_MEMORY_ALLOC_LOG
#include <cstdio>
#endif
namespace utils::memory {
struct Metrics_t {
size_t TotalAllocated = 0;
size_t TotalFreed = 0;
inline size_t CurrentUsage() {
return TotalAllocated - TotalFreed;
}
template<typename TChar, typename TCharTraits>
friend auto& operator<<(std::basic_ostream<TChar, TCharTraits>& stream, Metrics_t m) {
stream << "Current memory usage: "
#if UTILS_MEMORY_NEW_LOG
<< m.CurrentUsage() << " bytes";
#else
<< "unavailable, set UTILS_MEMORY_ALLOC_LOG macro first"
#endif
return stream;
}
};
static inline Metrics_t Metrics;
}
#if UTILS_MEMORY_NEW_LOG && !defined(ENABLE_TESTS)
void* operator new(size_t size) {
utils::memory::Metrics.TotalAllocated += size;
void* v = std::malloc(size);
#if UTILS_MEMORY_ALLOC_LOG
std::fprintf(stderr, "[new] at 0x%p (len=%lld bytes)\n", v, size);
#endif
return v;
}
void operator delete(void *v, size_t size) noexcept {
utils::memory::Metrics.TotalFreed += size;
#if UTILS_MEMORY_ALLOC_LOG
std::fprintf(stderr, "[delete] at 0x%p (len=%lld bytes)\n", v, size);
#else
UNUSED(size);
#endif
std::free(v);
}
void operator delete[](void *v, size_t size) noexcept {
utils::memory::Metrics.TotalFreed += size;
#if UTILS_MEMORY_ALLOC_LOG
std::fprintf(stderr, "[delete[]] at 0x%p (len=%lld bytes)\n", v, size);
#else
UNUSED(size);
#endif
std::free(v);
}
void operator delete(void *v) noexcept {
#if UTILS_MEMORY_ALLOC_LOG
std::fprintf(stderr, "[delete] at 0x%p (len=? bytes)\n", v);
#endif
std::free(v);
}
void operator delete[](void *v) noexcept {
#if UTILS_MEMORY_ALLOC_LOG
std::fprintf(stderr, "[delete[]] at 0x%p (len=? bytes)\n", v);
#endif
std::free(v);
}
#endif
namespace utils::memory {
/**
* \brief Cast to value to the target type by copying its bytes.
*
* \param value
* A pointer to the given value.
* \return Returns To with the bytes from \p value copied in.
*/
template<
typename To,
typename From,
typename std::enable_if_t<sizeof(From) == sizeof(To)
&& std::is_trivially_copyable_v<From>
&& std::is_trivially_copyable_v<To>
, bool> = false
> ATTR_MAYBE_UNUSED ATTR_NODISCARD
static inline constexpr To bit_cast(const From& value) noexcept {
#if UTILS_CPP_LANG_CHECK(UTILS_CPP_VERSION_20)
return std::bit_cast<To>(value);
#else
To target;
std::memcpy(&target, &value, sizeof(To));
return target;
#endif
}
/*
* Overloaded methods to allocate an array of T of size x, y, z.
*/
////////////////////////////////////////////////////////////////////////////
/// Variable
////////////////////////////////////////////////////////////////////////////
/** \brief Allocate an object of type T on the heap using `new T()`.
* Any argument will be passed down to the ctor of T.
*
* \tparam T
* The type of object to allocate.
* \param args
* Variable argument list passed down to ctor of T.
* \return
* A pointer to the newly allocated object.
*/
template <class T, class ... Type> ATTR_MAYBE_UNUSED ATTR_NODISCARD HEDLEY_MALLOC
static inline T* new_var(Type &&... args) {
return new T(std::forward<Type>(args)...);
}
/** \brief Deallocate an object of type T that was allocated using SysUtils::allocVar<T>().
*
* \tparam T
* The type of object to deallocate.
* \param *v
* A pointer to the object to deallocate.
*/
template <class T> ATTR_MAYBE_UNUSED
static inline void delete_var(T* v) {
#if UTILS_MEMORY_ALLOC_LOG
std::fprintf(stderr, "[delete_var] at 0x%p\n", v);
#endif
delete v;
}
/**
* Self destructing variable type.
* std::unique_ptr that contains a pointer to T.
*/
template <class T, typename _Dp = std::default_delete<T>>
// template <class T, typename _Dp = decltype(&delete_var<T>)>
using unique_t = std::unique_ptr<T, _Dp>;
/**
* \brief Create a unique_t<T> variable that deletes itself.
*
* \param args
* Variable argument list passed down to ctor of T.
*/
template <class T, class ...Args> ATTR_MAYBE_UNUSED ATTR_NODISCARD
static inline constexpr auto new_unique_var(Args&& ...args) {
return unique_t<T, decltype(&delete_var<T>)>(
new_var<T>(std::forward<Args>(args)...),
&delete_var<T>
);
}
/**
* std::shared_ptr that contains a pointer to T,
* possibly referencing this object multiple times.
*/
template <class T>
using shared_t = std::shared_ptr<T>;
/**
* \brief Create a shared_t<T> variable containing a reference.
*
* \param args
* Variable argument list passed down to ctor of T.
*/
template<typename T, typename ...Args> ATTR_MAYBE_UNUSED ATTR_NODISCARD
static inline constexpr shared_t<T> new_shared_ref(Args&& ...args) {
return std::make_shared<T>(std::forward<Args>(args)...);
}
////////////////////////////////////////////////////////////////////////////
/// Arrays
////////////////////////////////////////////////////////////////////////////
/** \brief Allocate an array of objects of type T and length x on the heap using `new T[x]()`.
*
* \tparam T
* The type of object to allocate.
* \param x
* The length of the array in the first dimension.
* \return
* A pointer to the newly allocated object.
*/
template <class T> ATTR_MAYBE_UNUSED ATTR_NODISCARD HEDLEY_MALLOC
static inline T* new_array(size_t x) {
return new T[x]();
}
/**
* \brief Allocate an array of objects of type T on the heap
* with a total length of all dims multiplied.
* Access elements in this array with e.g. `y * y_dim + x` ((x_dim, y_dim) alloced)
*
* \param dims
* Argument list of dimensions.
* \return
* A pointer to the newly allocated object.
*/
template <class T, typename ... size_t> ATTR_MAYBE_UNUSED ATTR_NODISCARD HEDLEY_MALLOC
static inline T* new_flat_array(size_t... dims) {
return new_array<T>((dims * ... * 1));
}
/** \brief Deallocate an array of type T that was allocated using SysUtils::allocArray<T>(size_t).
*
* \tparam T
* The type of object to deallocate.
* \param *a
* A pointer to the object to deallocate.
*/
template <class T> ATTR_MAYBE_UNUSED
static inline void delete_array(T* a) {
#if UTILS_MEMORY_ALLOC_LOG
std::fprintf(stderr, "[delete_array] at 0x%p\n", a);
#endif
delete[] a;
}
/** \brief Reallocate the given array to a new array with different size.
* Elements will be copied to the new array.
*
* \tparam T
* The type of object to allocate.
* \param *&a
* A reference to a pointer to the object to reallocate.
* \param &old_size
* The old length of the array in the first dimension, by reference.
* old_size will contain the new length after reallocation.
* \param new_size
* The new length of the array in the first dimension.
*/
template <class T> ATTR_MAYBE_UNUSED
static void realloc_array(T*& a, size_t& old_size, size_t new_size) {
#if UTILS_MEMORY_ALLOC_LOG
std::fprintf(stderr, "[reallocArray] at 0x%p from %u to %u\n",
a, uint32_t(old_size), uint32_t(new_size));
#endif
T* new_array = utils::memory::new_array<T>(new_size);
if (HEDLEY_LIKELY(a != nullptr)) {
std::copy_n(a, std::min(old_size, new_size), new_array);
utils::memory::delete_array(a);
}
a = new_array;
old_size = new_size;
}
/**
* Self destructing array type.
*/
template <class T, typename _Dp = decltype(&delete_array<T>)>
using unique_arr_t = unique_t<T[], _Dp>;
/**
* \brief Create a unique_arr_t<T> variable that deletes itself.
*
* \param x
* The length of the array in the first dimension.
* \return
* A unique_arr_t instance with the newly allocated object.
*/
template <class T> ATTR_MAYBE_UNUSED ATTR_NODISCARD
static inline unique_arr_t<T> new_unique_array(size_t x) {
return unique_arr_t<T>(new_array<T>(x), &delete_array<T>);
}
/**
* \brief Create a unique_arr_t<T> variable that deletes itself.
*
* \param dims
* Argument list of dimensions.
* \return
* A unique_arr_t instance with the newly allocated object.
*/
template <class T, typename ... size_t> ATTR_MAYBE_UNUSED ATTR_NODISCARD
static inline unique_arr_t<T> new_unique_flat_array(size_t ... dims) {
return unique_arr_t<T>(new_flat_array<T>(dims...), &delete_array<T>);
}
/** \brief Allocate y arrays of objects of type T and length x on the heap.
*
* \tparam T
* The type of object to allocate.
* \param x
* The length of the array in the first dimension.
* \param y
* The length of the array in the second dimension.
* \return
* A pointer to the newly allocated object.
*/
template <class T> ATTR_MAYBE_UNUSED ATTR_NODISCARD HEDLEY_MALLOC
static T** new_array(size_t x, size_t y) {
T **arr = new T*[x];
for(size_t i = 0; i < x; i++) arr[i] = utils::memory::new_array<T>(y);
return arr;
}
/** \brief Deallocate an array of type T that was allocated using SysUtils::allocArray<T>(size_t, size_t).
*
* \tparam T
* The type of object to deallocate.
* \param **a
* A pointer to the object to deallocate.
* \param y
* The length of the array in the second dimension.
*/
template <class T> ATTR_MAYBE_UNUSED
static void delete_array(T** a, size_t y) {
#if UTILS_MEMORY_ALLOC_LOG
std::fprintf(stderr, "[deallocArrayXY] at 0x%p\n", a);
#endif
for(size_t i = 0; i < y; i++) utils::memory::delete_array(a[i]);
utils::memory::delete_array(a);
}
/** \brief Allocate z arrays of y arrays of objects of type T and length x on the heap.
*
* \tparam T
* The type of object to allocate.
* \param x
* The length of the array in the first dimension.
* \param y
* The length of the array in the second dimension.
* \param z
* The length of the array in the third dimension.
* \return
* A pointer to the newly allocated object.
*/
template <class T> ATTR_MAYBE_UNUSED ATTR_NODISCARD HEDLEY_MALLOC
static T*** new_array(size_t x, size_t y, size_t z) {
T ***arr = new T**[x];
for(size_t i = 0; i < x; i++) arr[i] = utils::memory::new_array<T>(y, z);
return arr;
}
/** \brief Deallocate an array of type T that was allocated using SysUtils::allocArray<T>(size_t, size_t, size_t).
*
* \tparam T
* The type of object to deallocate.
* \param ***a
* A pointer to the object to deallocate.
* \param y
* The length of the array in the second dimension.
* \param z
* The length of the array in the third dimension.
*/
template <class T> ATTR_MAYBE_UNUSED
static void delete_array(T*** a, size_t y, size_t z) {
#if UTILS_MEMORY_ALLOC_LOG
std::fprintf(stderr, "[deallocArrayXYZ] at 0x%p\n", a);
#endif
for(size_t i = 0; i < z; i++) utils::memory::delete_array(a[i], y);
utils::memory::delete_array(a);
}
////////////////////////////////////////////////////////////////////////////
/// Containers
////////////////////////////////////////////////////////////////////////////
/** \brief Deallocate a Container with pointers.
* This can be any type where utils::traits::is_container is true.
*
* For map-like structures, if the ::mapped_type is a pointer, it will be freed,
* for others if ::value_type is a pointer it will be freed.
*
* \tparam Container
* A container type that passes utils::traits::is_container<Container>::value.
* \param container
* The container element that holds allocated pointers.
*/
template <
class Container,
typename = typename std::enable_if_t<utils::traits::is_container<Container>::value>
> ATTR_MAYBE_UNUSED
static void delete_container(Container *container) {
if constexpr (utils::traits::is_maplike_v<Container>) {
if constexpr (std::is_pointer_v<typename Container::mapped_type>)
{
#if UTILS_MEMORY_ALLOC_LOG
std::fprintf(stderr, "[delete_map] at 0x%p\n", container);
#endif
for (auto& [key, value] : *container) {
UNUSED(key);
utils::memory::delete_var(value);
}
}
} else if constexpr (std::is_pointer_v<typename Container::value_type>) {
#if UTILS_MEMORY_ALLOC_LOG
std::fprintf(stderr, "[delete_container] at 0x%p\n", container);
#endif
for (auto *value : *container) {
utils::memory::delete_var(value);
}
}
utils::memory::delete_var(container);
}
/**
* Self destructing container type.
* Unique_ptr container that will auto dealloc all elements and itself.
*/
template <class T>
using unique_container_t = unique_t<T, decltype(&delete_container<T>)>;
/**
* Self destructing vector type.
* Unique_ptr vector that contains pointers to T.
* Will auto dealloc all elements and itself.
*/
template <class T>
using unique_vect_t = unique_container_t<std::vector<T*>>;
template <class T, class ... Type> ATTR_MAYBE_UNUSED ATTR_NODISCARD
static inline auto new_unique_container(Type &&... args) {
return unique_container_t<T>(
new_var<T>(std::forward<Type>(args)...),
&delete_container<T>
);
}
/**
* \brief Create a unique_vect_t<T> variable that deletes
* its contents and itself. The vector will contain T* items.
*
* \param args
* Variable argument list passed down to ctor of std::vector<T>.
*/
template <class T, class ... Type> ATTR_MAYBE_UNUSED ATTR_NODISCARD
static inline auto new_unique_vector(Type &&... args) {
return unique_vect_t<T>(
new_var<std::vector<T*>>(std::forward<Type>(args)...),
&delete_container<std::vector<T*>>
);
}
}
#ifdef UTILS_MEMORY_ALLOC_LOG
#undef UTILS_MEMORY_ALLOC_LOG
#endif
#ifdef UTILS_MEMORY_NEW_LOG
#undef UTILS_MEMORY_NEW_LOG
#endif
#endif // UTILS_MEMORY_HPP