-
Notifications
You must be signed in to change notification settings - Fork 5
/
arena.h
49 lines (44 loc) · 867 Bytes
/
arena.h
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
#ifndef SIMPLE_ARENA
#define SIMPLE_ARENA
#include <stddef.h>
#include <malloc.h>
typedef struct arena_s
{
const char *tag;
char *data;
size_t reserved;
size_t used;
} arena_t;
static int arena_create(arena_t **arena_out, const char *tag, size_t n)
{
*arena_out = NULL;
char *ptr = malloc(n + sizeof(arena_t));
if(!ptr)
return 1;
arena_t *a = (arena_t*)ptr;
ptr += sizeof(arena_t);
a->tag = tag;
a->data = ptr;
a->reserved = n;
a->used = 0;
*arena_out = a;
return 0;
}
static char *arena_alloc(arena_t *a, size_t n)
{
if(a->used + n > a->reserved)
{
printf("can't allocate %d bytes, out of memory for arena '%s' size: %d bytes / %d KB\n", n, a->tag, a->reserved, a->reserved / 1000);
return NULL;
}
a->used += n;
return &a->data[a->used - n];
}
static void arena_destroy(arena_t **a)
{
if(!a)
return;
free(*a);
*a = NULL;
}
#endif