Helios Engine 0.1.0
A modular ECS based data-oriented C++23 game engine
 
Loading...
Searching...
No Matches
common.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <helios/core_pch.hpp>
4
8
9#include <cstddef>
10#include <cstdlib>
11
12namespace helios::memory {
13
14/**
15 * @brief Allocate memory with the specified alignment.
16 * @details Allocates a block of memory of the specified size aligned to the specified alignment boundary.
17 * The alignment must be a power of two and non-zero. The size must also be non-zero.
18 *
19 * Uses `_aligned_malloc` on MSVC and `std::aligned_alloc` on other platforms.
20 *
21 * @warning Triggers assertion in next cases:
22 * - alignment is zero
23 * - alignment is not a power of two
24 * - size is zero
25 * @param alignment The alignment in bytes (must be a power of two and non-zero).
26 * @param size The size of the memory block to allocate in bytes (must be non-zero).
27 * @return A pointer to the allocated memory block.
28 * @throws std::bad_alloc if the allocation fails.
29 */
30inline void* AlignedAlloc(size_t alignment, size_t size) {
31 HELIOS_ASSERT(alignment != 0, "Failed to allocate memory: alignment cannot be zero!");
32 HELIOS_ASSERT(IsPowerOfTwo(alignment), "Failed to allocate memory: alignment must be a power of two!");
33 HELIOS_ASSERT(size != 0, "Failed to allocate memory: size cannot be zero!");
34#ifdef _MSC_VER
35 return _aligned_malloc(size, alignment);
36#else
37 // POSIX aligned_alloc requires size to be a multiple of alignment
38 // Round up size to the next multiple of alignment
39 return std::aligned_alloc(alignment, AlignUp(size, alignment));
40#endif
41}
42
43/**
44 * @brief Free memory allocated with AlignedAlloc.
45 * @details Frees a block of memory allocated with AlignedAlloc.
46 * The ptr must be a pointer returned by AlignedAlloc.
47 *
48 * Uses `_aligned_free` on MSVC and `std::free` on other platforms.
49 *
50 * @warning Triggers assertion if ptr is nullptr.
51 * @param ptr The pointer to the memory block to free.
52 */
53inline void AlignedFree(void* ptr) {
54 HELIOS_ASSERT(ptr != nullptr, "Failed to free memory: pointer cannot be nullptr!");
55#ifdef _MSC_VER
56 _aligned_free(ptr);
57#else
58 std::free(ptr);
59#endif
60}
61
62} // namespace helios::memory
#define HELIOS_ASSERT(condition,...)
Assertion macro that aborts execution in debug builds.
Definition assert.hpp:140
void * AlignedAlloc(size_t alignment, size_t size)
Allocate memory with the specified alignment.
Definition common.hpp:30
constexpr size_t AlignUp(size_t size, size_t alignment) noexcept
Helper function to align a size up to the given alignment.
constexpr bool IsPowerOfTwo(size_t size) noexcept
Helper function to check if a size is a power of 2.
void AlignedFree(void *ptr)
Free memory allocated with AlignedAlloc.
Definition common.hpp:53