Skip to content

Commit f31b7bb

Browse files
committed
Allow to control memory allocation strategy
1 parent 6d00590 commit f31b7bb

File tree

1 file changed

+28
-6
lines changed

1 file changed

+28
-6
lines changed

src/util/hb_arena.c

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,41 @@
33
#endif
44

55
#include "../include/util/hb_arena.h"
6-
#include "../include/macros.h"
76

87
#include <assert.h>
98
#include <stdbool.h>
109
#include <stdint.h>
1110
#include <string.h>
11+
12+
#ifdef HB_USE_MALLOC
13+
#include <stdlib.h>
14+
#else
1215
#include <sys/mman.h>
16+
#endif
1317

1418
#define hb_arena_for_each_page(allocator, page) \
1519
for (hb_arena_page_T* page = (allocator)->head; page != NULL; page = page->next)
1620

21+
static void* hb_system_allocate_memory(size_t size) {
22+
#ifdef HB_USE_MALLOC
23+
return malloc(size);
24+
#else
25+
void* memory = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
26+
27+
if (memory == MAP_FAILED) { return NULL; }
28+
29+
return memory;
30+
#endif
31+
}
32+
33+
static void hb_system_free_memory(void* ptr, size_t size) {
34+
#ifdef HB_USE_MALLOC
35+
free(ptr);
36+
#else
37+
munmap(ptr, size);
38+
#endif
39+
}
40+
1741
static inline size_t hb_arena_align_size(size_t size, size_t alignment) {
1842
assert(size <= SIZE_MAX - (alignment - 1));
1943

@@ -42,10 +66,8 @@ static bool hb_arena_append_page(hb_arena_T* allocator, size_t page_size) {
4266
assert(page_size <= SIZE_MAX - sizeof(hb_arena_page_T));
4367
size_t page_size_with_meta_data = page_size + sizeof(hb_arena_page_T);
4468

45-
hb_arena_page_T* page =
46-
mmap(NULL, page_size_with_meta_data, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
47-
48-
if (page == MAP_FAILED) { return false; }
69+
hb_arena_page_T* page = hb_system_allocate_memory(page_size_with_meta_data);
70+
if (page == NULL) { return false; }
4971

5072
page->next = NULL;
5173
page->capacity = page_size;
@@ -148,7 +170,7 @@ static size_t hb_arena_page_free(hb_arena_page_T* starting_page) {
148170
freed_capacity += current_page->capacity;
149171

150172
size_t total_size = sizeof(hb_arena_page_T) + current_page->capacity;
151-
munmap(current_page, total_size);
173+
hb_system_free_memory(current_page, total_size);
152174

153175
current_page = next_page;
154176
}

0 commit comments

Comments
 (0)