CppCommon 1.0.5.0
C++ Common Library
Loading...
Searching...
No Matches
memory.inl
Go to the documentation of this file.
1
9#include <cstdint>
10
11namespace CppCommon {
12
13inline bool Memory::IsValidAlignment(size_t alignment) noexcept
14{
15 return ((alignment > 0) && ((alignment & (alignment - 1)) == 0));
16}
17
18template <typename T>
19inline bool Memory::IsAligned(const T* address, size_t alignment) noexcept
20{
21 assert((address != nullptr) && "Address must be valid!");
22 assert(IsValidAlignment(alignment) && "Alignment must be valid!");
23
24 uintptr_t ptr = (uintptr_t)address;
25 return (ptr & (alignment - 1)) == 0;
26}
27
28template <typename T>
29inline T* Memory::Align(const T* address, size_t alignment, bool upwards) noexcept
30{
31 assert((address != nullptr) && "Address must be valid!");
32 assert(IsValidAlignment(alignment) && "Alignment must be valid!");
33
34 uintptr_t ptr = (uintptr_t)address;
35
36 if (upwards)
37 return (T*)((ptr + (alignment - 1)) & -((int)alignment));
38 else
39 return (T*)(ptr & -((int)alignment));
40}
41
42} // namespace CppCommon
static bool IsValidAlignment(size_t alignment) noexcept
Is the given alignment valid?
Definition memory.inl:13
static bool IsAligned(const T *address, size_t alignment=alignof(T)) noexcept
Is the given pointer aligned?
Definition memory.inl:19
static T * Align(const T *address, size_t alignment=alignof(T), bool upwards=true) noexcept
Align pointer (upwards or downwards)
Definition memory.inl:29
C++ Common project definitions.