mem/include/mem.h

29 lines
1.2 KiB
C

#ifndef MEM_INCLUDED
#define MEM_INCLUDED
#include "except.h"
#include <stddef.h>
#define SIZEOF(x) (ptrdiff_t)sizeof(x)
#define NELEMS(a) (sizeof(a) / sizeof(*(a)))
#define LEN(s) (NELEMS(s) - 1)
#define KB(x) ((size_t)(x) << 10) // 1 KB = 1024 bytes
#define MB(x) ((size_t)(x) << 20) // 1 MB = 1024 * 1024 bytes
#define GB(x) ((size_t)(x) << 30) // 1 GB = 1024 * 1024 * 1024 bytes
extern const Exception out_of_memory; // OOM Exception
extern void *mem_alloc (ptrdiff_t nbytes,const char *file, int line);
extern void *mem_calloc(ptrdiff_t count, ptrdiff_t nbytes,const char *file, int line);
extern void mem_free(void *ptr, const char *file, int line);
extern void *mem_realloc(void *ptr, ptrdiff_t nbytes, const char *file, int line);
#define ALLOC(nbytes) mem_alloc((nbytes), __FILE__, __LINE__)
#define CALLOC(count, nbytes) mem_calloc((count), (nbytes), __FILE__, __LINE__)
#define NEW(p) ((p) = ALLOC((ptrdiff_t)sizeof *(p)))
#define NEW0(p) ((p) = CALLOC(1, (ptrdiff_t)sizeof *(p)))
#define FREE(ptr) ((void)(mem_free((ptr), __FILE__, __LINE__), (ptr) = 0))
#define REALLOC(ptr, nbytes) ((ptr) = mem_realloc((ptr), (nbytes), __FILE__, __LINE__))
#endif