|
3 | 3 | #endif |
4 | 4 |
|
5 | 5 | #include "../include/util/hb_arena.h" |
6 | | -#include "../include/macros.h" |
7 | 6 |
|
8 | 7 | #include <assert.h> |
9 | 8 | #include <stdbool.h> |
10 | 9 | #include <stdint.h> |
11 | 10 | #include <string.h> |
| 11 | + |
| 12 | +#ifdef HB_USE_MALLOC |
| 13 | +#include <stdlib.h> |
| 14 | +#else |
12 | 15 | #include <sys/mman.h> |
| 16 | +#endif |
13 | 17 |
|
14 | 18 | #define hb_arena_for_each_page(allocator, page) \ |
15 | 19 | for (hb_arena_page_T* page = (allocator)->head; page != NULL; page = page->next) |
16 | 20 |
|
| 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 | + |
17 | 41 | static inline size_t hb_arena_align_size(size_t size, size_t alignment) { |
18 | 42 | assert(size <= SIZE_MAX - (alignment - 1)); |
19 | 43 |
|
@@ -42,10 +66,8 @@ static bool hb_arena_append_page(hb_arena_T* allocator, size_t page_size) { |
42 | 66 | assert(page_size <= SIZE_MAX - sizeof(hb_arena_page_T)); |
43 | 67 | size_t page_size_with_meta_data = page_size + sizeof(hb_arena_page_T); |
44 | 68 |
|
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; } |
49 | 71 |
|
50 | 72 | page->next = NULL; |
51 | 73 | page->capacity = page_size; |
@@ -148,7 +170,7 @@ static size_t hb_arena_page_free(hb_arena_page_T* starting_page) { |
148 | 170 | freed_capacity += current_page->capacity; |
149 | 171 |
|
150 | 172 | 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); |
152 | 174 |
|
153 | 175 | current_page = next_page; |
154 | 176 | } |
|
0 commit comments