blob: 327bfd50c822988cb23df2361f129e7f4cfc516b (
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
|
#include "BumpAlloc.h"
#include "Types.h"
#include <stdio.h>
#include <stdlib.h>
struct BumpArena {
void* memory;
usize size;
usize top;
};
BumpArena
Bcreate(usize size) {
struct BumpArena *b = malloc(sizeof(struct BumpArena));
b->memory = malloc(size);
b->size = size;
b->top = 0;
return b;
}
Result
Bdestroy(BumpArena bp) {
if (NULL == bp)
return R_Uninitialized;
struct BumpArena b = *(struct BumpArena*)bp;
if (NULL == b.memory)
return R_Uninitialized;
free(b.memory);
b.memory = NULL;
b.size = b.top = 0;
return R_Ok;
}
static inline usize*
top_size(struct BumpArena* b) {
return (usize*)(b->memory + b->top);
}
void*
Balloc(BumpArena bp, usize size) {
if (bp == NULL || size == 0)
return NULL;
struct BumpArena *b = (struct BumpArena*)bp;
if (size + b->top + sizeof(usize) > b->size)
return NULL;
if (b->top > 0)
b->top += sizeof(usize);
usize start = b->top;
b->top += size;
// Keep allocated memory size at the end of every allocation
*top_size(b) = size;
return b->memory + start;
}
int
Bresizeable(BumpArena bp, void* ptr) {
if (NULL == bp)
return 0;
struct BumpArena *b = (struct BumpArena*)bp;
return b->memory + b->top - *top_size(b) <= ptr &&
ptr < b->memory + b->top;
}
Result
Bresize(BumpArena bp, usize size) {
if (NULL == bp)
return R_Uninitialized;
struct BumpArena *b = (struct BumpArena*)bp;
if (size == 0) {
Bfree(bp);
return R_Ok;
}
usize last_size = *top_size(b);
usize start = b->top - last_size;
if (start > 0)
start -= sizeof(usize);
if (start + size + sizeof(usize) > b->size)
return R_OutOfBounds;
b->top += size;
*top_size(b) = size;
return R_Ok;
}
Result
Bfree(BumpArena bp) {
if (NULL == bp)
return R_Uninitialized;
struct BumpArena *b = (struct BumpArena*)bp;
if (b->top > 0) {
b->top -= *top_size(b);
if (b->top > 0)
b->top -= sizeof(usize);
}
return R_Ok;
}
|