#include <stdlib.h>
#include <proto/exec.h>

static APTR mempool;

int setup_malloc(void) {
	mempool = IExec->AllocSysObjectTags(ASOT_MEMPOOL,
		ASOPOOL_Name,      "z.library memory pool",
		ASOPOOL_Protected, TRUE,
		ASOPOOL_MFlags,    MEMF_SHARED,
		ASOPOOL_LockMem,   FALSE,
		ASOPOOL_Puddle,    4096,
		ASOPOOL_Threshold, 1024,
		TAG_END);
	return mempool != NULL;
}

void cleanup_malloc(void) {
	IExec->FreeSysObject(ASOT_MEMPOOL, mempool);
}

void *malloc(size_t size) {
	size_t *ptr;
	ptr = IExec->AllocPooled(mempool, sizeof(size_t) + size);
	if (ptr) *ptr++ = size;
	return ptr;
}

void free(void *ptr) {
	if (ptr) {
		size_t *base = (size_t *)ptr - 1;
		IExec->FreePooled(mempool, base, sizeof(size_t) + *base);
	}
}

