diff libmlk-core/core/alloc.c @ 252:95c2c4a72410

core: add alloc_set to set SDL allocators as well
author David Demelier <markand@malikania.fr>
date Tue, 01 Dec 2020 21:53:23 +0100
parents 71b3b7036de7
children 9b758eb84556
line wrap: on
line diff
--- a/libmlk-core/core/alloc.c	Tue Dec 01 21:53:00 2020 +0100
+++ b/libmlk-core/core/alloc.c	Tue Dec 01 21:53:23 2020 +0100
@@ -21,6 +21,8 @@
 #include <stdlib.h>
 #include <string.h>
 
+#include <SDL.h>
+
 #include "alloc.h"
 #include "error.h"
 #include "panic.h"
@@ -47,18 +49,34 @@
 	return mem;
 }
 
-struct allocator allocator = {
+static const struct alloc_funcs default_alloc_funcs = {
 	.alloc = panic_alloc,
 	.realloc = panic_realloc,
 	.free = free
 };
 
+static const struct alloc_funcs *funcs = &default_alloc_funcs;
+
+void
+alloc_set(const struct alloc_funcs *newfuncs)
+{
+	assert(funcs);
+	assert(funcs->alloc);
+	assert(funcs->realloc);
+	assert(funcs->free);
+
+	funcs = newfuncs;
+
+	/* Change SDL allocators as well. */
+	SDL_SetMemoryFunctions(alloc_new, alloc_array0, alloc_renew, free);
+}
+
 void *
 alloc_new(size_t size)
 {
 	assert(size != 0);
 
-	return allocator.alloc(size);
+	return funcs->alloc(size);
 }
 
 void *
@@ -68,7 +86,7 @@
 
 	void *ptr;
 
-	if ((ptr = allocator.alloc(size)))
+	if ((ptr = funcs->alloc(size)))
 		memset(ptr, 0, size);
 
 	return ptr;
@@ -85,7 +103,7 @@
 	if (total / n != size)
 		return errorf("%s", strerror(ENOMEM)), NULL;
 
-	return allocator.alloc(total);
+	return funcs->alloc(total);
 }
 
 void *
@@ -100,7 +118,7 @@
 	if (total / n != size)
 		return errorf("%s", strerror(ENOMEM)), NULL;
 
-	if ((mem = allocator.alloc(total)))
+	if ((mem = funcs->alloc(total)))
 		memset(mem, 0, total);
 
 	return mem;
@@ -109,7 +127,7 @@
 void *
 alloc_renew(void *ptr, size_t amount)
 {
-	return allocator.realloc(ptr, amount);
+	return funcs->realloc(ptr, amount);
 }
 
 void *
@@ -120,7 +138,7 @@
 	if (total / n != size)
 		return errorf("%s", strerror(ENOMEM)), NULL;
 
-	return allocator.realloc(ptr, total);
+	return funcs->realloc(ptr, total);
 }
 
 void *
@@ -131,7 +149,7 @@
 
 	void *mem;
 
-	if ((mem = allocator.alloc(size)))
+	if ((mem = funcs->alloc(size)))
 		memcpy(mem, ptr, size);
 
 	return mem;
@@ -145,7 +163,7 @@
 	char *ret;
 	size_t length = strlen(src) + 1;
 
-	if ((ret = allocator.alloc(length)))
+	if ((ret = funcs->alloc(length)))
 		memcpy(ret, src, length + 1);
 
 	return ret;