blob: e65b041fcb2423ab67b2ef483930374149458cc3 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
#ifndef __VXGG_REWRITE___ARENA_H___25077218513438___
#define __VXGG_REWRITE___ARENA_H___25077218513438___
#include <stddef.h>
// Whether to use `XALLOC` or normal `malloc` functions for acquiring new memory in an arena. `> 0`
// enables XALLOC functionality
#define ___VXGG___USE_XALLOC_FOR_ARENAS___ 1
#define VALLOC(nmemb, size) ((___VXGG___USE_XALLOC_FOR_ARENAS___ > 0) ? xmalloc((nmemb) * (size)) : malloc((nmemb) * (size)))
// Normal arena. Can expand in size beyond original allocation
typedef struct arena arena;
// A wrapper for the normal arena struct. Can not expand in size
typedef arena simplearena;
// Bitwise operation to check if a number is a power of 2
#define ISPOWOF2(x) (((x) & ((x) - 1)) == 0)
// Variable for memory alignment
static const size_t MEM_ALIGN_BYTES = (2 * sizeof(void*));
// Macro to get the remaining bytes necessary to be on a power of 2
#define MEM_ALIGN(x) ((x) + (((x) & (MEM_ALIGN_BYTES - 1)) != 0) * (MEM_ALIGN_BYTES - ((x) & (MEM_ALIGN_BYTES - 1))))
// Initialize an arena with `bytes` bytes of pre-allocated memory. Exits / returns NULL on error depending on the value of `___VXGG___USE_XALLOC_FOR_ARENAS___`
arena * arena_init(size_t bytes);
// Take `bytes` bytes of memory from `arena`'s memory pool. Exits / returns NULL on error depending on the value of `___VXGG___USE_XALLOC_FOR_ARENAS___`
void * arena_alloc(arena * const arena, size_t bytes);
// Free an arena its memory pool(s). Returns -1 and sets `errno` if the given arena is NULL
int arena_free(arena **arena);
// Clear an arena of its contents (frees and inits an arena in 1). Returns -1 and sets `errno` if the given arena is NULL
int arena_clear(arena **arena);
// Initializes a simple arena.
simplearena * simplearena_init(size_t bytes);
// Grabs some memory from the simple arena's pool. Exits / returns NULL on error depending on the value of `___VXGG___USE_XALLOC_FOR_ARENAS___`
void * simplearena_alloc(simplearena * const a, size_t bytes);
// Free a simple arena. Exits / returns -1 on error depending on the value of `___VXGG___USE_XALLOC_FOR_ARENAS___`
int simplearena_free(simplearena **a);
// Clear a simple arena and its memory pool (frees and inits a simple arena in 1). Exits / returns -1 on error depending on the value of `___VXGG___USE_XALLOC_FOR_ARENAS___`
int simplearena_clear(simplearena **a);
#endif
|