aboutsummaryrefslogtreecommitdiff
path: root/src/bump_alloc.h
blob: bc9cbacf34bbe9858c1f7cc849fab79603bbeb59 (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
#include <assert.h>
#include <stddef.h> /* NULL, size_t */
#include <stdint.h> /* uintptr_t */

#ifndef MEMSIZE
#define MEMSIZE 1024*4*1024*1024l
#endif

#define unlikely(x)     __builtin_expect((x),0)

#ifdef __cplusplus
extern "C" {
#endif

typedef struct {
	uintptr_t end = 0;
	uintptr_t ptr = 0;
} bumpptr_t;

__thread bumpptr_t* tsd = NULL;

inline void init_tsd() {
	void* mem_start = mmap(NULL, MEMSIZE, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
	if(mem_start == MAP_FAILED) {
		perror("mmap");
		return NULL;
	}
	tsd = (bumpptr_t*)mem_start;
	tsd->ptr = (uintptr_t)mem_start + sizeof(bumpptr_t);
	tsd->end = (uintptr_t)mem_start + MEMSIZE;
}

inline void* bump_up(size_t size, size_t align) {
	assert(align % 2 == 0);

	if (unlikely(tsd == NULL)) {
		init_tsd();
	}

	// align ptr;
	uintptr_t aligned = (tsd->ptr + align - 1) & ~(align - 1);

	uintptr_t new_ptr = aligned + size;
	if (new_ptr > mem_end)
		return NULL;
	else {
		tsd->ptr = new_ptr;
		return (void*)aligned;
	}
}

#ifdef __cplusplus
}
#endif