From ec1c5c8844d20e1407c298b57acae31fd506dea5 Mon Sep 17 00:00:00 2001 From: fallenoak Date: Mon, 7 Sep 2020 17:00:14 -0500 Subject: [PATCH] feat(memory): add SMemAlloc, SMemFree, and SMemReAlloc --- storm/CMakeLists.txt | 5 ++++ storm/Memory.cpp | 66 ++++++++++++++++++++++++++++++++++++++++++++ storm/Memory.hpp | 15 ++++++++++ 3 files changed, 86 insertions(+) create mode 100644 storm/Memory.cpp create mode 100644 storm/Memory.hpp diff --git a/storm/CMakeLists.txt b/storm/CMakeLists.txt index e69de29..88ea5ca 100644 --- a/storm/CMakeLists.txt +++ b/storm/CMakeLists.txt @@ -0,0 +1,5 @@ +file(GLOB STORM_SOURCES "*.cpp") + +add_library(storm STATIC + ${STORM_SOURCES} +) diff --git a/storm/Memory.cpp b/storm/Memory.cpp new file mode 100644 index 0000000..aa623c6 --- /dev/null +++ b/storm/Memory.cpp @@ -0,0 +1,66 @@ +#include "Memory.hpp" + +constexpr size_t ALIGNMENT = 8; + +void* SMemAlloc(size_t bytes, const char* filename, int32_t linenumber, uint32_t flags) { + size_t alignedBytes = (bytes + (ALIGNMENT - 1)) & ~(ALIGNMENT - 1); + + void* result; + + if (flags & 0x8) { + result = calloc(1, alignedBytes); + } else { + result = malloc(alignedBytes); + } + + if (result) { + return result; + } else { + // TODO handle errors + return nullptr; + } +} + +void SMemFree(void* ptr) { + if (ptr) { + free(ptr); + } +} + +void SMemFree(void* ptr, const char* filename, int32_t linenumber, uint32_t flags) { + if (ptr) { + free(ptr); + } +} + +void* SMemReAlloc(void* ptr, size_t bytes, const char* filename, int32_t linenumber, uint32_t flags) { + if (flags == 0xB00BEEE5) { + return nullptr; + } + + if (!ptr) { + return SMemAlloc(bytes, filename, linenumber, flags); + } + + if (flags & 0x10) { + return nullptr; + } + + size_t alignedBytes = (bytes + (ALIGNMENT - 1)) & ~(ALIGNMENT - 1); + + void* result = realloc(ptr, alignedBytes); + + if (result) { + if (flags & 0x8) { + // TODO zero out expanded portion + } + + return result; + } else { + if (alignedBytes) { + // TODO handle errors + } + + return NULL; + } +} diff --git a/storm/Memory.hpp b/storm/Memory.hpp new file mode 100644 index 0000000..07c8186 --- /dev/null +++ b/storm/Memory.hpp @@ -0,0 +1,15 @@ +#ifndef STORM_MEMORY_HPP +#define STORM_MEMORY_HPP + +#include +#include + +void* SMemAlloc(size_t bytes, const char* filename, int32_t linenumber, uint32_t flags); + +void SMemFree(void* ptr); + +void SMemFree(void* ptr, const char* filename, int32_t linenumber, uint32_t flags); + +void* SMemReAlloc(void* ptr, size_t bytes, const char* filename, int32_t linenumber, uint32_t flags); + +#endif