#define MODULE "xalloc"

#include "compiler.h"
#include "xmalloc.h"
#include "common.h"
#include <assert.h>

no_return __noinline alloc_panic(void)
{
    assert(!"FATAL: OUT OF MEMORY!!!");
    while (1)
	suspend();
}

void *xrealloc(void *ptr, size_t len)
{
    return null_check(realloc(ptr, Max(len,1)));
}

void *xmalloc(size_t len)
{
    return null_check(malloc(Max(len,1)));
}

void *xmalloc_dma(size_t len)
{
    return null_check(heap_caps_malloc(Max(len,1), MALLOC_CAP_DMA));
}

void *xzalloc(size_t len)
{
    return null_check(calloc(Max(len,1), 1));
}

static inline size_t nsize(size_t nmemb, size_t size)
{
    size2_t len = nmemb * size;
    if (unlikely(len >> CHAR_BIT*sizeof(size_t)))
	alloc_panic();
    return (size_t)len;
}

void *xnmalloc(size_t nmemb, size_t size)
{
    return xmalloc(nsize(nmemb, size));
}

void *xcalloc(size_t nmemb, size_t size)
{
    return xzalloc(nsize(nmemb, size));
}

void *xnrealloc(void *ptr, size_t nmemb, size_t size)
{
    return xrealloc(ptr, nsize(nmemb, size));
}
