summaryrefslogtreecommitdiff
path: root/arena.h
blob: c7340a0fcb2ce7d7d9df5d0ca504cb53840dc93d (plain)
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
#pragma once

#include <string.h>

#ifdef ARENA_TYPES
#include <assert.h>
#include <stdint.h>
typedef uint8_t b8;
#endif

#ifndef ALIGNMENT
#define ALIGNMENT (2*sizeof(void*))
#endif

struct Arena {
  unsigned char* buffer;
  size_t prev_offset;
  size_t curr_offset;
  size_t capacity;
};
typedef struct Arena Arena;

struct TempArena {
    Arena *a;
    size_t saved_prev_offset;
    size_t saved_curr_offset;
};
typedef struct TempArena TempArena;

// definition
b8 is_power_of_two(uintptr_t x);
uintptr_t fast_modulo(uintptr_t p, uintptr_t a);
uintptr_t align_forward(uintptr_t ptr, uintptr_t alignment);
void arena_init(Arena* a, unsigned char *memory, size_t capacity);
void* arena_alloc(Arena* a, size_t size);
void arena_clear(Arena* a);

TempArena temp_arena_start(Arena *a);
void temp_arena_end(Arena* a);

// implementation
b8 is_power_of_two(uintptr_t x) {
  return (x & (x-1)) == 0;
}

uintptr_t fast_modulo(uintptr_t p, uintptr_t a) { 
  return (p & (a - 1)); 
}

uintptr_t align_forward(uintptr_t ptr, size_t alignment) {
  uintptr_t p, a, modulo;

  assert(is_power_of_two(alignment));

  p = ptr;
  a = (uintptr_t)alignment;
  modulo = fast_modulo(p, a);

  if (modulo != 0) {
    p += (a - modulo);
  }

  return p;
}

void arena_init(Arena* a, unsigned char *memory, size_t capacity) {
  a->buffer = memory;
  a->prev_offset = 0;
  a->curr_offset = 0;
  a->capacity = capacity;
}

void* arena_alloc(Arena* a, size_t size) {
  void *ptr = NULL;

  assert(is_power_of_two(ALIGNMENT));

  uintptr_t curr_ptr = (uintptr_t)a->buffer + a->curr_offset;
  uintptr_t offset = align_forward(curr_ptr, ALIGNMENT);
  offset = offset - (uintptr_t)a->buffer;
  size_t next_offset = offset + size;

  assert(next_offset <= a->capacity);

  ptr = &a->buffer[offset];
  a->prev_offset = a->curr_offset;
  a->curr_offset = next_offset;
  memset(ptr, 0, size);

  return ptr;
}

void arena_clear(Arena* a) {
  a->curr_offset = 0;
  a->prev_offset = 0;
}

TempArena temp_arena_start(Arena* main) {
    TempArena tmp = {};
    tmp.a = main;
    tmp.saved_prev_offset = main->prev_offset;
    tmp.saved_curr_offset = main->curr_offset;

    return tmp;
}

void temp_arena_end(TempArena tmp) {
    tmp.a->prev_offset = tmp.saved_prev_offset;
    tmp.a->curr_offset = tmp.saved_curr_offset;
}