Last active
November 8, 2019 14:02
-
-
Save ZenToad/e1ef76899c7f2010c30bc2052ac115a1 to your computer and use it in GitHub Desktop.
zen_alloc.h
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "zen_alloc.h" | |
#include <stdlib.h> | |
#include <assert.h> | |
zen_allocator_i *zen_allocator_default; | |
typedef struct zen_alloc_default_t { | |
zen_allocator_i base; | |
uint32_t total_memory; | |
} zen_alloc_default_t; | |
static zen_alloc_default_t zen_alloc_default; | |
static void* default_realloc(zen_allocator_i *a, void *p, uint64_t old_size, uint64_t new_size, const char *file, uint32_t line) { | |
assert(a); | |
void *mem = realloc(p, new_size); | |
assert(new_size == 0 || mem); | |
zen_alloc_default_t *alloc = (zen_alloc_default_t *)a; | |
alloc->total_memory -= old_size; | |
alloc->total_memory += new_size; | |
return mem; | |
} | |
void zen_alloc_init() { | |
zen_alloc_default = (zen_alloc_default_t) { | |
.base = (zen_allocator_i) { | |
.realloc = &default_realloc, | |
}, | |
.total_memory = 0, | |
}; | |
zen_allocator_default = (zen_allocator_i *)&zen_alloc_default; | |
} | |
void zen_alloc_shutdown() { | |
assert(zen_alloc_default.total_memory == 0); | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef ZEN_ALLOC_H | |
#define ZEN_ALLOC_H | |
#ifdef __cplusplus | |
extern "C" { | |
#endif | |
#include <stdint.h> | |
#define ZEN_REALLOC(alloc, ptr, old_size, new_size) ((alloc)->realloc((alloc), (ptr), (old_size), (new_size), __FILE__, __LINE__)) | |
#define ZEN_MALLOC(alloc, size) ZEN_REALLOC(alloc, 0, 0, size) | |
#define ZEN_FREE(alloc, ptr, size) ZEN_REALLOC(alloc, ptr, size, 0) | |
typedef struct zen_allocator_i { | |
void* (*realloc)(struct zen_allocator_i *a, void *p, uint64_t old_size, uint64_t new_size, const char *file, uint32_t line); | |
} zen_allocator_i; | |
extern zen_allocator_i *zen_allocator_default; | |
void zen_alloc_init(); | |
void zen_alloc_shutdown(); | |
#ifdef __cplusplus | |
} | |
#endif | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment