Cogs.Core
Allocator.cpp
1#include "Allocator.h"
2
3#include "../Logging/Logger.h"
4
5#if defined(_WIN32) && defined(COGS_FOUNDATION_ALIGNED_MALLOC)
6#define USE_ALIGNED_MALLOC
7
8#include <malloc.h>
9#endif
10
11#include <stdlib.h>
12
13namespace{
14 Cogs::Logging::Log logger = Cogs::Logging::getLogger("Allocator");
15}
16
18{
19 static Allocator allocator;
20
21 return &allocator;
22}
23
25{
26 return defaultAllocator();
27}
28
29void * Cogs::Memory::Allocator::allocate(size_t size, size_t alignment, MemBlockType type)
30{
31 allocated += size;
32 ++allocations;
33
34#ifdef USE_ALIGNED_MALLOC
35 void * memory = _aligned_malloc(size, alignment > kDefaultAlignment ? alignment : kDefaultAlignment);
36#else
37 void * memory = nullptr;
38 if (alignment <= kDefaultAlignment) {
39 memory = malloc(size);
40 } else {
41 assert(false && "Unsupported alignment restrictions.");
42 }
43#endif
44
45 if (!memory) {
46 LOG_ERROR(logger, "Failed to allocate %zd bytes of %zd byte aligned memory.", size, alignment);
47 }
48 (void)type;
49 OsoMP_Allocate(uint8_t(type), memory, size, nullptr, 0);
50
51#if 0
52 // Enable to check assumptions regarding default alignment.
53 assert((intptr_t)memory % kDefaultAlignment == 0 && "Invalid base alignment");
54#endif
55 return memory;
56}
57
58void Cogs::Memory::Allocator::deallocate(void * ptr, size_t size, MemBlockType type)
59{
60 (void)type;
61 OsoMP_Free(uint8_t(type), ptr, nullptr, 0);
62
63#ifdef USE_ALIGNED_MALLOC
64 _aligned_free(ptr);
65#else
66 free(ptr);
67#endif
68 allocated -= size;
69 --allocations;
70}
71
72void Cogs::Memory::Allocator::changeType(void* ptr, size_t size, MemBlockType oldType, MemBlockType newType)
73{
74 (void)ptr;
75 (void)size;
76 (void)oldType;
77 (void)newType;
78 OsoMP_Free(uint8_t(oldType), ptr, nullptr, 0);
79 OsoMP_Allocate(uint8_t(newType), ptr, size, nullptr, 0);
80}
Log implementation class.
Definition: LogManager.h:139
Base allocator implementation.
Definition: Allocator.h:30
static Allocator * defaultAllocator()
Gets the system default allocator.
Definition: Allocator.cpp:17
virtual void deallocate(void *ptr, size_t size, MemBlockType type=MemBlockType::Block)
Deallocate the memory block at the given pointer, with the given size.
Definition: Allocator.cpp:58
virtual void * allocate(size_t size, size_t alignment=0, MemBlockType type=MemBlockType::Block)
Allocate raw memory.
Definition: Allocator.cpp:29
static Allocator * overflowAllocator()
Definition: Allocator.cpp:24
constexpr Log getLogger(const char(&name)[LEN]) noexcept
Definition: LogManager.h:180