aboutsummaryrefslogtreecommitdiff
path: root/lib/arena.c
blob: dd12d0c3c6909344f1041f45e561f0c116638aab (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
#include "arena.h"

region *new_region(size_t cap) {
  size_t size_bytes = sizeof(region) + sizeof(uintptr_t)*cap;
  region *r = (region *)malloc(size_bytes);
  assert(r);
  r->next = NULL;
  r->len = 0;
  r->cap = cap;
  return r;
}

void *arena_alloc(arena *a, size_t size_bytes) {
  size_t size = (size_bytes + sizeof(uintptr_t)-1)/sizeof(uintptr_t);

  if (a->end == NULL) {
	assert(a->beg == NULL);
	size_t capacity = ARENA_REGION_DEFAULT_CAPACITY;
	if (capacity < size) capacity = size;
	a->beg = new_region(capacity);
	a->end = a->beg;
  }

  while (a->end->len + size < a->end->cap && a->end->next != NULL) {
	a->end = a->end->next;
  }

  if (a->end->len + size > a->end->cap) {
	size_t capacity = ARENA_REGION_DEFAULT_CAPACITY;
	if (capacity < size) capacity = size;
	a->beg = new_region(capacity);
	a->end->next = new_region(capacity);
	a->end = a->end->next;
  }

  void *p = &a->end->data[a->end->len];
  a->end->len += size;
  return memset(p, 0, size);
}

void arena_free(arena *a) {
  region *r = a->beg;
  while (r != NULL) {
	region *r0 = r;
	r = r0->next;
	free(r0);
  }
}

void grow_da(void *slice, size_t size, arena *arena) {
  struct {
	void *data;
	size_t len;
	size_t cap;
  } replica;
  memcpy(&replica, slice, sizeof(replica));

  replica.cap = replica.cap ? replica.cap : 1;
  void *data = arena_alloc(arena, size*2*replica.cap);
  replica.cap *= 2;
  if (replica.len) {
	memcpy(data, replica.data, size*replica.len);
  }
  replica.data = data;

  memcpy(slice, &replica, sizeof(replica));
}