// vim:fileencoding=utf-8:foldmethod=marker

#ifndef MEM_ALLOCATOR_H
#define MEM_ALLOCATOR_H

#include "../../../common/aliases/aliases.h"
#include "../../../common/platform/platform.h"
#include <string.h>

#ifdef WP_PLATFORM_CPP
BEGIN_C_LINKAGE
#endif // !WP_PLATFORM_CPP

typedef enum {
	WP_MEM_OP_ALLOC,
	WP_MEM_OP_ALLOC_ALIGNED,
	WP_MEM_OP_REALLOC,
	WP_MEM_OP_REALLOC_ALIGNED,
	WP_MEM_OP_FREE,

	COUNT_MEM_OPS
} WpMemOp;

typedef void  *(WpMemAllocFunc)(u64 size, void *alloc_obj);
typedef void  *(WpMemAllocAlignedFunc)(u64 size, u64 alignment, void *alloc_obj);
typedef void  *(WpMemReallocFunc)(void *ptr, u64 old_size, u64 new_size, void *alloc_obj);
typedef void  *(WpMemReallocAlignedFunc)(void *ptr, u64 old_size, u64 new_size, u64 alignment, void *alloc_obj);
typedef void   (WpMemFreeFunc)(void **ptr, u64 size, void *alloc_obj);

typedef struct WpAllocator WpAllocator;
struct WpAllocator {
	void *obj;
	WpMemAllocFunc *alloc;
	WpMemAllocAlignedFunc *alloc_aligned;
	WpMemReallocFunc *realloc;
	WpMemReallocAlignedFunc *realloc_aligned;
	WpMemFreeFunc *free;
};

#ifdef WP_PLATFORM_CPP
#define wpMemAllocatorInvalid(ALLOCATOR) ([&]() {      \
	WpAllocator alloc{};                                        \
	return memcmp(ALLOCATOR, &alloc, sizeof(WpAllocator)) == 0; \
}())
#else
#define wpMemAllocatorInvalid(ALLOCATOR) (memcmp(ALLOCATOR, &((WpAllocator){0}), sizeof(WpAllocator)) == 0)
#endif // !WP_PLATFORM_CPP

void *wpMemAllocatorAlloc(const WpAllocator *allocator, u64 size);
void *wpMemAllocatorAllocAligned(const WpAllocator *allocator, u64 size, u64 alignment);
void *wpMemAllocatorRealloc(const WpAllocator *allocator, void *ptr, u64 old_size, u64 new_size);
void *wpMemAllocatorReallocAligned(const WpAllocator *allocator, void *ptr, u64 old_size,
                                         u64 new_size, u64 alignment);
void  wpMemAllocatorFree(const WpAllocator *allocator, void **ptr, u64 size);
b8    wpMemAllocatorOpSupported(const WpAllocator *allocator, WpMemOp op);

#ifdef WP_PLATFORM_CPP
END_C_LINKAGE
#endif // !WP_PLATFORM_CPP

#endif // !MEM_ALLOCATOR_H
