Add memory allocation API with templated C++ delegates & minor fixups #1123

Closed
KitsuneAlex wants to merge 5 commits from main into main
2 changed files with 79 additions and 10 deletions
Showing only changes of commit 1e89a305a7 - Show all commits

View File

@@ -11,7 +11,7 @@
#include <string.h>
#include <algorithm>
#include <atomic>
#include <memory>
#include <malloc.h>
#include "Utils.h"
#include "YGNode.h"
#include "YGNodePrint.h"
@@ -106,8 +106,24 @@ static int YGDefaultLog(
#undef YG_UNUSED
#endif
static YGAllocatorAllocateFunc gAllocatorAllocateFunc = &malloc;
static YGAllocatorFreeFunc gAllocatorFreeFunc = &free;
#ifdef _MSC_VER
#define YG_ALLOC_ALIGNED ([](size_t a, size_t s) -> void* { \
return _aligned_malloc(s, a); \
})
#define YG_FREE_ALIGNED ([](void* m) -> void { \
_aligned_free(m); \
})
#else
#define YG_ALLOC_ALIGNED ([](size_t a, size_t s) -> void* { \
NickGerleman commented 2022-10-03 09:20:49 -07:00 (Migrated from github.com)
Review

nit: why are these macros vs a regular function?

nit: why are these macros vs a regular function?
return aligned_alloc(a, s); \
})
#define YG_FREE_ALIGNED ([](void* m) -> void { \
free(m); \
})
#endif
static YGAllocatorAllocateFunc gAllocatorAllocateFunc = YG_ALLOC_ALIGNED;
static YGAllocatorFreeFunc gAllocatorFreeFunc = YG_FREE_ALIGNED;
YOGA_EXPORT void YGSetAllocationCallbacks(
YGAllocatorAllocateFunc allocFunc,
@@ -127,8 +143,8 @@ YOGA_EXPORT void YGGetAllocationCallbacks(
}
}
YOGA_EXPORT void* YGMemoryAllocate(size_t size) {
return gAllocatorAllocateFunc(size);
YOGA_EXPORT void* YGMemoryAllocate(size_t alignment, size_t size) {
return gAllocatorAllocateFunc(alignment, size);
}
YOGA_EXPORT void YGMemoryFree(void* memory) {

View File

@@ -29,7 +29,7 @@ typedef struct YGSize {
float height;
} YGSize;
typedef void* (*YGAllocatorAllocateFunc)(size_t size);
typedef void* (*YGAllocatorAllocateFunc)(size_t alignment, size_t size);
typedef void (*YGAllocatorFreeFunc)(void* memory);
typedef struct YGConfig* YGConfigRef;
@@ -60,7 +60,7 @@ typedef YGNodeRef (
WIN_EXPORT void YGSetAllocationCallbacks(YGAllocatorAllocateFunc allocFunc, YGAllocatorFreeFunc freeFunc);
WIN_EXPORT void YGGetAllocationCallbacks(YGAllocatorAllocateFunc* allocFunc, YGAllocatorFreeFunc* freeFunc);
WIN_EXPORT void* YGMemoryAllocate(size_t size);
WIN_EXPORT void* YGMemoryAllocate(size_t alignment, size_t size);
WIN_EXPORT void YGMemoryFree(void* memory);
// YGNode
@@ -378,7 +378,7 @@ YG_EXTERN_C_END
// cast nor pass in the size of the allocated chunk of memory explicitly.
template<typename T, typename... A>
T* YGAllocate(A&&... arguments) {
auto* memory = reinterpret_cast<T*>(YGMemoryAllocate(sizeof(T)));
auto* memory = reinterpret_cast<T*>(YGMemoryAllocate(sizeof(T), alignof(T)));
new(memory) T(std::forward<A>(arguments)...);
return memory;
}