Helios Engine
A modular ECS based data-oriented C++23 game engine framework
Loading...
Searching...
No Matches
aligned_alloc.cpp
Go to the documentation of this file.
1#include <pch.hpp>
2
4
5#include <helios/assert.hpp>
7#include <helios/memory/details/profile.hpp>
8
9#include <cstddef>
10#include <cstdlib>
11
12#ifdef HELIOS_MEMORY_USE_MIMALLOC
13#include <mimalloc.h>
14#endif
15
16namespace helios::mem {
17
18void* AlignedAlloc(size_t alignment, size_t size,
19 bool enable_profile) noexcept {
20 HELIOS_MEMORY_PROFILE_SCOPE_N("helios::mem::AlignedAlloc");
21 HELIOS_MEMORY_PROFILE_ZONE_VALUE(size);
22 HELIOS_ASSERT(alignment != 0, "alignment cannot be zero!");
23 HELIOS_ASSERT(IsPowerOfTwo(alignment), "alignment must be a power of two!");
24 HELIOS_ASSERT(size != 0, "size cannot be zero!");
25
26#ifdef HELIOS_MEMORY_USE_MIMALLOC
27 void* const ptr = mi_malloc_aligned(size, alignment);
28#elif defined(_MSC_VER)
29 void* const ptr = _aligned_malloc(size, alignment);
30#else
31 void* ptr = nullptr;
32 if (alignment < sizeof(void*)) {
33 ptr = std::malloc(size);
34 } else {
35 ptr = std::aligned_alloc(alignment, AlignUp(size, alignment));
36 }
37#endif
38
39 if (ptr != nullptr && enable_profile) {
40 HELIOS_MEMORY_PROFILE_ALLOC(ptr, size, "AlignedAlloc");
41 }
42 return ptr;
43}
44
45void AlignedFree(void* ptr, bool enable_profile) noexcept {
46 if (ptr == nullptr) [[unlikely]] {
47 return;
48 }
49 if (enable_profile) {
50 HELIOS_MEMORY_PROFILE_FREE(ptr, "AlignedAlloc");
51 }
52
53#ifdef HELIOS_MEMORY_USE_MIMALLOC
54 mi_free(ptr);
55#elif defined(_MSC_VER)
56 _aligned_free(ptr);
57#else
58 std::free(ptr);
59#endif
60}
61
62} // namespace helios::mem
#define HELIOS_ASSERT(condition,...)
Assertion macro that aborts execution in debug builds.
Definition assert.hpp:259
constexpr bool IsPowerOfTwo(size_t value) noexcept
Checks if a value is a power of two.
Definition common.hpp:215
constexpr size_t AlignUp(size_t value, size_t alignment) noexcept
Aligns value up to alignment.
Definition common.hpp:226
void * AlignedAlloc(size_t alignment, size_t size, bool enable_profile=true) noexcept
Allocates memory with the specified alignment.
void AlignedFree(void *ptr, bool enable_profile=true) noexcept
Frees memory allocated with AlignedAlloc.