Added implementations
This commit is contained in:
35
include/mem.h
Normal file
35
include/mem.h
Normal file
@@ -0,0 +1,35 @@
|
||||
#ifndef MEM_INCLUDED
|
||||
#define MEM_INCLUDED
|
||||
|
||||
#include "except.h" // Exceptions
|
||||
|
||||
#include <stddef.h> // size_t
|
||||
#define MEM_KB(x) ((size_t)(x) * 1024ULL)
|
||||
#define MEM_MB(x) ((size_t)(x) * 1024ULL * 1024ULL)
|
||||
#define MEM_GB(x) ((size_t)(x) * 1024ULL * 1024ULL * 1024ULL)
|
||||
#define MEM_SIZE(x) (ptrdiff_t)sizeof(x)
|
||||
#define MEM_COUNT(a) (MEM_SIZE(a) / MEM_SIZE(*(a)))
|
||||
#define MEM_LEN(s) (MEM_COUNT(s) - 1)
|
||||
|
||||
|
||||
/* Default behavior is to throw exceptions and zero out memory*/
|
||||
enum MemFlags {
|
||||
NOZERO = 1 << 0, /* 0001 */
|
||||
SOFT_FAIL = 1 << 1, /* 0010 */
|
||||
HARD_FAIL = 1 << 2, /* 0100 */
|
||||
};
|
||||
|
||||
extern const Exception OOM; // Out of memory
|
||||
|
||||
extern void *mem_alloc (int flags, size_t nbytes, const char *file, int line);
|
||||
extern void mem_free(void *ptr, const char *file, int line);
|
||||
extern void *mem_resize(int flags, void *ptr, size_t nbytes,
|
||||
const char *file, int line);
|
||||
|
||||
#define ALLOC(flags, nbytes) mem_alloc((flags), (nbytes), __FILE__, __LINE__)
|
||||
#define FREE(ptr) ((void)(mem_free((ptr), __FILE__, __LINE__), (ptr) = 0))
|
||||
#define RESIZE(flags, ptr, nbytes) ((ptr) = mem_resize((flags), (ptr), \
|
||||
(nbytes), __FILE__, __LINE__))
|
||||
|
||||
|
||||
#endif
|
||||
47
src/mem.c
Normal file
47
src/mem.c
Normal file
@@ -0,0 +1,47 @@
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "../include/except.h"
|
||||
#include "../include/mem.h"
|
||||
|
||||
const Exception OOM = { "Out of Memory" };
|
||||
#define ENOMEM 12 /* Out of memory */
|
||||
|
||||
void *mem_alloc(int flags, size_t nbytes, const char *file, int line){
|
||||
void *ptr;
|
||||
ASSERTED(nbytes > 0);
|
||||
ptr = malloc(nbytes);
|
||||
if (ptr == NULL){
|
||||
if (flags & SOFT_FAIL) return 0;
|
||||
if (flags & HARD_FAIL) exit(ENOMEM);
|
||||
|
||||
if (file == NULL) // Wasn't called by macro
|
||||
RAISE(OOM); // Out of Memory Exception
|
||||
else // Called by macro
|
||||
except_raise(&OOM, file, line);
|
||||
}
|
||||
return flags&NOZERO ? ptr : memset(ptr, 0, nbytes);
|
||||
}
|
||||
|
||||
void mem_free(void *ptr, const char *file, int line) {
|
||||
UNUSED(file);
|
||||
UNUSED(line);
|
||||
if (ptr){
|
||||
free(ptr);
|
||||
}
|
||||
}
|
||||
|
||||
void *mem_resize(int flags, void *ptr, size_t nbytes,const char *file, int line) {
|
||||
ASSERTED(ptr);
|
||||
ASSERTED(nbytes > 0);
|
||||
ptr = realloc(ptr, nbytes);
|
||||
if (ptr == NULL){
|
||||
if(flags & SOFT_FAIL) return 0;
|
||||
if(flags & HARD_FAIL) exit(ENOMEM);
|
||||
|
||||
if (file == NULL)
|
||||
RAISE(OOM); // Out of memory exception
|
||||
else // Called by macro
|
||||
except_raise(&OOM, file, line);
|
||||
}
|
||||
return ptr;
|
||||
}
|
||||
Reference in New Issue
Block a user