6fde883b7643e7c91ad5b58a35ee63e35679082f
[vg.git] / vg_mem.h
1 #pragma once
2
3 #define VG_MAX_ALLOCATIONS 128
4
5 typedef struct vg_linear_allocator vg_linear_allocator;
6 typedef struct vg_allocation_meta vg_allocation_meta;
7
8 struct vg_global_mem
9 {
10 void *rtmemory,
11 *scratch;
12
13 int use_libc_malloc;
14 u32 quota;
15 }
16 extern vg_mem;
17
18 struct vg_allocation_meta
19 {
20 const char *name;
21 void *data;
22 u32 size;
23 enum allocation_type{
24 k_allocation_type_block = 0,
25 k_allocation_type_linear = 1
26 }
27 type;
28 };
29
30 #define VG_MEMORY_SYSTEM 0x1 /* systems memory, slow and low counts */
31 #define VG_MEMORY_REALTIME 0x2 /* per-frame. no max allocs, only size. fast */
32
33 /*
34 * Stored just behind the array. 32 bytes.
35 */
36 #pragma pack(push,1)
37 struct vg_linear_allocator
38 {
39 u32 size;
40 u32 cur;
41 u16 allocation_count;
42 u16 flags;
43 u32 last_alloc_size;
44 void *last_alloc;
45 vg_allocation_meta *alloc_table;
46 };
47 #pragma pack(pop)
48
49 u32 vg_align8( u32 s );
50 u32 vg_align4( u32 s );
51
52 /* allocate something from a linear allocator */
53 __attribute__((warn_unused_result))
54 void *_vg_linear_alloc( void *buffer, u32 size, const char *constr_name );
55
56 /* resize latest block of memory from linear */
57 __attribute__((warn_unused_result))
58 void *vg_linear_resize( void *buffer, void *data, u32 newsize );
59
60 /* its possible to delete just the last item */
61 void vg_linear_del( void *buffer, void *data );
62
63 /* extend latest block of memory from linear */
64 __attribute__((warn_unused_result))
65 void *_vg_linear_extend( void *buffer, void *data, u32 extra,
66 const char *constr_name );
67
68 /* get the current usage of allocator */
69 u32 vg_linear_get_cur( void *buffer );
70
71 /* get the capacity of allocator. */
72 u32 vg_linear_get_capacity( void *buffer );
73
74 /* get the remaining size of the allocator */
75 u32 vg_linear_remaining( void *buffer );
76
77 /* yeet all memory from linear allocator */
78 void vg_linear_clear( void *buffer );
79
80 /* request all the memory we need in advance */
81 void vg_set_mem_quota( u32 size );
82
83 /* essentially init() */
84 void vg_alloc_quota(void);
85
86 /* print out tree of current memory used. only works with libc mode */
87 void vg_mem_log( void *lin_alloc, int depth, const char *name );
88
89 #define VG_MEM_MCSTR(S) VG_MEM_MCSTR2(S)
90 #define VG_MEM_MCSTR2(S) #S
91
92 #define vg_linear_alloc(...) \
93 _vg_linear_alloc( __VA_ARGS__, __FILE__":"VG_MEM_MCSTR(__LINE__) )
94 #define vg_linear_extend(...) \
95 _vg_linear_extend( __VA_ARGS__, __FILE__":"VG_MEM_MCSTR(__LINE__) )
96 #define vg_create_linear_allocator(...) \
97 _vg_create_linear_allocator( __VA_ARGS__, __FILE__":"VG_MEM_MCSTR(__LINE__) )
98
99 void *_vg_create_linear_allocator( void *lin_alloc, u32 size,
100 u16 flags, const char *constr_name);
101 vg_linear_allocator *vg_linear_header( void *data );