-
Notifications
You must be signed in to change notification settings - Fork 0
/
arena.h
79 lines (66 loc) · 1.91 KB
/
arena.h
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
#pragma once
/*
* Arena allocator
*
* Copyright 2024 amateur80lvl
* License: LGPLv3, see LICENSE for details
*/
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct _Arena Arena;
/*
* Arena consists of regions.
* Arena itself and all its regions are allocated with mmap
* and are always multiple of page size.
*
* The first region is embedded into the arena to avoid
* separately allocating its small structure and fully utilize
* allocated page.
*/
Arena* create_arena(size_t capacity);
/*
* Create new arena with desired capacity
* or at least one page.
*
* The capacity of subsequent regions will be
* same capacity unless adjusted with `set_region_capacity`.
*/
void delete_arena(Arena* arena);
/*
* Free arena and all its regions.
*/
void set_region_capacity(Arena* arena, size_t capacity);
/*
* Set desired capacity of newly created regions.
*/
void* _arena_alloc(Arena* arena, size_t size, size_t alignment);
/*
* Allocate `size` bytes from the last region aligned at `alignment` boundary.
* If the last region has no space available, allocate new region.
*
* This is a low-level function because its arguments
* tell how to allocate a block.
*
* The following macro gets what to allocate:
*/
#define arena_alloc(arena, num_elements, element_type) \
_arena_alloc((arena), (num_elements) * sizeof(element_type), alignof(element_type))
void* _arena_fit(Arena* arena, size_t size, size_t element_size);
/*
* Try to find a region with sufficient free space
* and allocate from it.
* If no region has space available, allocate new region.
*
* This is a low-level function because its arguments
* tell how to allocate a block.
*
* The following macro gets what to allocate:
*/
#define arena_fit(arena, num_elements, element_type) \
_arena_fit((arena), (num_elements) * sizeof(element_type), alignof(element_type))
void arena_print(Arena* arena);
#ifdef __cplusplus
}
#endif