-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathats_mem.c
80 lines (60 loc) · 1.49 KB
/
ats_mem.c
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
#include "ats.h"
static mem_arena* mem_stack;
ATS_API mem_arena mem_create(void* data, usize size)
{
mem_arena arena = {0};
arena.cap = size;
arena.buf = (u8*)data;
return arena;
}
#define MEM_GET(arg) ((arg).arena? (arg).arena : (mem_stack))
typedef struct mem_header mem_header;
struct mem_header
{
usize size;
usize count;
};
ATS_API void* _mem_alloc(struct _mem_alloc_desc desc)
{
mem_arena* arena = MEM_GET(desc);
mem_header* header = (mem_header*)(arena->buf + arena->pos);
arena->pos += sizeof (mem_header) + desc.size;
header->size = desc.size;
header->count = desc.count? desc.count : desc.size;
return memset(header + 1, 0, desc.size);
}
ATS_API void _mem_save(struct _mem_arena_desc desc)
{
mem_arena* arena = MEM_GET(desc);
usize pos = arena->pos;
mem_index* node = mem_type(mem_index, arena);
node->pos = pos;
node->next = arena->stack;
arena->stack = node;
}
ATS_API void _mem_restore(struct _mem_arena_desc desc)
{
mem_arena* arena = MEM_GET(desc);
arena->pos = arena->stack->pos;
arena->stack = arena->stack->next;
}
ATS_API void* _mem_begin(struct _mem_arena_desc desc)
{
mem_arena* arena = MEM_GET(desc);
void* ptr = arena->buf + arena->pos;
return ptr;
}
ATS_API void _mem_end(usize size, struct _mem_arena_desc desc)
{
mem_arena* arena = MEM_GET(desc);
arena->pos += size;
}
ATS_API void mem_push(mem_arena* arena)
{
arena->next = mem_stack;
mem_stack = arena;
}
ATS_API void mem_pop(void)
{
mem_stack = mem_stack->next;
}