generated from pbentes/ProjectTemplate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArena.hpp
71 lines (56 loc) · 1.59 KB
/
Arena.hpp
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
#pragma once
#include <cstddef>
#define ARENA_SIZE 64000000
typedef struct Arena {
void* buffer;
void* index;
size_t size;
Arena* next;
} Arena;
Arena* arenaCreate(size_t size = ARENA_SIZE);
void* arenaAlloc(Arena* arena, unsigned int size);
void arenaClear(Arena* arena);
void arenaDestroy(Arena* arena);
#ifndef ARENA_IMPLEMENTATION
#define ARENA_IMPLEMENTATION
#include <cstdlib>
#include <new>
Arena* arenaCreate(size_t size) {
Arena* arena = static_cast<Arena*>(malloc(sizeof(Arena)));
if (!arena) {
throw std::bad_alloc();
}
arena->size = size;
arena->buffer = malloc(arena->size);
if (!arena->buffer) {
free(arena);
throw std::bad_alloc();
}
arena->index = arena->buffer;
arena->next = nullptr;
return arena;
}
void* arenaAlloc(Arena* arena, unsigned int size) {
void* ret = arena->index;
arena->index = static_cast<char*>(arena->index) + size;
if (arena->index > static_cast<char*>(arena->buffer) + arena->size) {
if (!arena->next)
arena->next = arenaCreate(arena->size);
return arenaAlloc(arena->next, size);
}
return ret;
}
void arenaClear(Arena* arena) {
arena->index = arena->buffer;
if(arena->next)
arenaDestroy(arena->next);
}
void arenaDestroy(Arena* arena) {
if(arena->next)
arenaDestroy(arena->next);
if(arena) {
free(arena->buffer);
free(arena);
}
}
#endif