mirror of
https://github.com/krgamestudios/Toy.git
synced 2026-04-15 23:04:08 +10:00
Added custom allocator support
This commit is contained in:
@@ -5,7 +5,8 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
void* reallocate(void* pointer, size_t oldSize, size_t newSize) {
|
||||
//default allocator
|
||||
void* defaultAllocator(void* pointer, size_t oldSize, size_t newSize) {
|
||||
if (newSize == 0 && oldSize == 0) {
|
||||
//causes issues, so just skip out with a NO-OP
|
||||
return NULL;
|
||||
@@ -20,10 +21,30 @@ void* reallocate(void* pointer, size_t oldSize, size_t newSize) {
|
||||
void* mem = realloc(pointer, newSize);
|
||||
|
||||
if (mem == NULL) {
|
||||
fprintf(stderr, ERROR "[internal]Memory allocation error (requested %d for %ld, replacing %d)\n" ERROR, (int)newSize, (long int)pointer, (int)oldSize);
|
||||
fprintf(stderr, ERROR "[internal] Memory allocation error (requested %d for %ld, replacing %d)\n" RESET, (int)newSize, (long int)pointer, (int)oldSize);
|
||||
exit(-1);
|
||||
}
|
||||
|
||||
return mem;
|
||||
}
|
||||
|
||||
//exposed API
|
||||
static AllocatorFn allocator = defaultAllocator;
|
||||
|
||||
void setAllocator(AllocatorFn fn) {
|
||||
if (fn == NULL) {
|
||||
fprintf(stderr, ERROR "[internal] Memory allocator error (can't be null)\n" RESET);
|
||||
exit(-1);
|
||||
}
|
||||
|
||||
if (fn == reallocate) {
|
||||
fprintf(stderr, ERROR "[internal] Memory allocator error (can't loop the reallocate function)\n" RESET);
|
||||
exit(-1);
|
||||
}
|
||||
|
||||
allocator = fn;
|
||||
}
|
||||
|
||||
void* reallocate(void* pointer, size_t oldSize, size_t newSize) {
|
||||
return allocator(pointer, oldSize, newSize);
|
||||
}
|
||||
Reference in New Issue
Block a user