Files
mem/include/mem.h

49 lines
1.7 KiB
C
Raw Normal View History

2025-10-18 10:00:39 -05:00
#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 */
};
2025-10-18 11:22:09 -05:00
struct Arena{
unsigned char *beg;
unsigned char *end;
};
typedef struct Arena Arena;
2025-10-18 10:00:39 -05:00
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);
2025-10-18 11:22:09 -05:00
extern int mem_is_zero(const void *ptr, size_t nbytes);
extern Arena mem_arena_new(int flags, size_t nbytes, const char *file, int line);
extern void *mem_arena_alloc(int flags, Arena *a,
size_t nbytes, size_t align, size_t count, const char *file, int line);
2025-10-18 10:00:39 -05:00
#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__))
2025-10-18 11:22:09 -05:00
#define ARENA(flags, nbytes)\
mem_arena_new((flags), (nbytes), __FILE__, __LINE__)
#define ARENA_ALLOC(flags, a, nbytes, align, count) \
mem_arena_alloc((flags), (a), (nbytes), (align), (count), __FILE__, __LINE__)
2025-10-18 10:00:39 -05:00
#endif