Customizable thread-local and global variables for memory handling.
This class holds pointers to systems that must be globally available, like the memory allocator. It allows "stacking" different Globals through a push / pop mechanism, connecting them through a linked list. The Default allocator is automatically setup and uses standard malloc
, realloc
, free
for allocations.
- Note
- Globals use no locking mechanism so they are thread-unsafe. Every method however requires a Globals::Type parameter that can be set to Globals::ThreadLocal to avoid such issues.
Example (Fixed Allocator):
alignas(
uint64_t)
char stackMemory[256] = {0};
FixedAllocator fixedAllocator = {stackMemory, sizeof(stackMemory)};
Globals globals = {fixedAllocator};
(void)buffer.append({"ASDF"});
unsigned long long uint64_t
Platform independent (8) bytes unsigned int.
Definition: PrimitiveTypes.h:42
static Globals * push(Type type, Globals &globals)
Sets Globals as current, saving previous one.
static Globals & get(Type type)
Obtains current set of Globals.
static Globals * pop(Type type)
Restores Globals previously replaced by a push.
@ Global
Shared globals (NOT thread-safe)
Definition: Globals.h:40
T * create(U &&... u)
Allocate and construct an object of type T using this allocator.
Definition: Memory.h:48
Example (Virtual Allocator):
VirtualMemory virtualMemory;
VirtualAllocator virtualAllocator = {virtualMemory};
Globals virtualGlobals = {virtualAllocator};
(void)buffer.append({"ASDF"});
#define SC_TEST_EXPECT(e)
Records a test expectation (eventually aborting or breaking o n failed test)
Definition: Testing.h:116
Example (Memory dump):
struct NestedStruct
{
VectorMap<String, int> someMap;
VectorSet<int> someSet;
};
struct ComplexStruct
{
Vector<String> someStrings;
int someField = 0;
String singleString;
NestedStruct nestedStruct;
};
Buffer memoryDump;
VirtualMemory virtualMemory;
VirtualAllocator allocator = {virtualMemory};
Globals globals = {allocator};
ComplexStruct&
object = *allocator.
create<ComplexStruct>();
object.someField = 42;
object.singleString = "ASDF";
object.someStrings = {"First", "Second"};
SC_TEST_EXPECT(
object.nestedStruct.someMap.insertIfNotExists({
"1", 1}));
Span<const void> memory = {allocator.data(), allocator.size()};
SC_TEST_EXPECT(virtualMemory.committedBytes == virtualMemory.getPageSize());
SC_TEST_EXPECT((
size_t(memoryDump.data()) %
alignof(ComplexStruct)) == 0);
const Span<const void> span = memoryDump.toSpanConst();
const ComplexStruct& readonly = *span.start_lifetime_as<const ComplexStruct>();
ComplexStruct modifiable = readonly;
modifiable.someStrings[0] = "First modified";