blob: 9e15c2a0fefa1d3785209c52b60531a734e22e89 (
plain) (
blame)
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include "arena.h"
union align {
long long int l;
long double d;
void *p;
};
/* alignment for a long-ish builtin type? */
#define ALIGN (sizeof(union align))
/* ensure it's a power of two */
static_assert(ALIGN && !(ALIGN & (ALIGN - 1)), "ALIGN not power of two");
static unsigned char *data;
static size_t total;
static size_t used;
/*
* round up to nearest multiple of ALIGN
*/
static size_t
round_up(size_t minimum)
{
return (minimum + ALIGN - 1) & ~(ALIGN - 1);
}
int
ar_setup(size_t total_size)
{
assert(data == NULL);
size_t adjusted = round_up(total_size);
void *p = calloc(1, adjusted);
if (p == NULL) {
return -1;
}
data = p;
total = adjusted;
return 0;
}
void *
ar_alloc(size_t object_size)
{
assert(data != NULL);
size_t adjusted = round_up(object_size);
if (used + adjusted > total) {
return NULL;
}
void *p = data + used;
used += adjusted;
return p;
}
void
ar_free(void)
{
assert(data != NULL);
memset(data, 0, total);
used = 0;
}
void
ar_cleanup(void)
{
assert(data != NULL);
free(data);
data = NULL;
total = 0;
used = 0;
}
|