CppCommon 1.0.5.0
C++ Common Library
Loading...
Searching...
No Matches
allocator_stack.inl
Go to the documentation of this file.
1
9namespace CppCommon {
10
11template <size_t N>
13 : _allocated(0),
14 _allocations(0),
15 _capacity(N),
16 _size(0)
17{
18}
19
20template <size_t N>
21inline void* StackMemoryManager<N>::malloc(size_t size, size_t alignment)
22{
23 assert((size > 0) && "Allocated block size must be greater than zero!");
24 assert(Memory::IsValidAlignment(alignment) && "Alignment must be valid!");
25
26 // Allocate memory from the stack buffer
27 uint8_t* buffer = _buffer + _size;
28 uint8_t* aligned = Memory::Align(buffer, alignment);
29
30 // Check if there is enough free space to allocate the block
31 if ((size + (aligned - buffer)) <= (_capacity - _size))
32 {
33 // Memory allocated
34 _size += size;
35
36 // Update allocation statistics
37 _allocated += size;
38 ++_allocations;
39
40 return aligned;
41 }
42
43 // Not enough memory...
44 return nullptr;
45}
46
47template <size_t N>
48inline void StackMemoryManager<N>::free(void* ptr, size_t size)
49{
50 assert((ptr != nullptr) && "Deallocated block must be valid!");
51
52 if (ptr != nullptr)
53 {
54 // Update allocation statistics
55 _allocated -= size;
56 --_allocations;
57 }
58}
59
60template <size_t N>
62{
63 assert((_allocated == 0) && "Memory leak detected! Allocated memory size must be zero!");
64 assert((_allocations == 0) && "Memory leak detected! Count of active memory allocations must be zero!");
65
66 _size = 0;
67}
68
69} // namespace CppCommon
static bool IsValidAlignment(size_t alignment) noexcept
Is the given alignment valid?
Definition memory.inl:13
static T * Align(const T *address, size_t alignment=alignof(T), bool upwards=true) noexcept
Align pointer (upwards or downwards)
Definition memory.inl:29
void free(void *ptr, size_t size)
Free the previously allocated memory block.
void * malloc(size_t size, size_t alignment=alignof(std::max_align_t))
Allocate a new memory block of the given size.
void reset()
Reset the memory manager.
C++ Common project definitions.