memory_arena.h (2220B)
1 #pragma once 2 3 #include "intrinsics.h" 4 #include "array.h" 5 6 struct MemoryArena { 7 u8 * memory; 8 uptr size; 9 uptr used; 10 u32 num_checkpoints; 11 }; 12 13 struct MemoryArenaCheckpoint { 14 // MemoryArena * arena; 15 size_t used; 16 bool restored; 17 }; 18 19 struct MemoryArenaAutoCheckpoint { 20 MemoryArenaAutoCheckpoint( MemoryArena * a, MemoryArenaCheckpoint cp ); 21 ~MemoryArenaAutoCheckpoint(); 22 23 MemoryArena * arena; 24 MemoryArenaCheckpoint checkpoint; 25 }; 26 27 void memarena_init( MemoryArena * arena, u8 * memory, size_t size ); 28 29 u8 * memarena_push_size( MemoryArena * arena, size_t size, uptr alignment = 16 ); 30 31 template< typename T > 32 T * alloc( MemoryArena * arena, uptr alignment = alignof( T ) ) { 33 return ( T * ) memarena_push_size( arena, sizeof( T ), alignment ); 34 } 35 36 template< typename T > 37 T * alloc_many( MemoryArena * arena, size_t n, uptr alignment = alignof( T ) ) { 38 return ( T * ) memarena_push_size( arena, sizeof( T ) * n, alignment ); 39 } 40 41 template< typename T > 42 array< T > alloc_array( MemoryArena * arena, size_t n, uptr alignment = alignof( T ) ) { 43 return array< T >( alloc_many< T >( arena, n, alignment ), n ); 44 } 45 46 template< typename T > 47 array2d< T > alloc_array2d( MemoryArena * arena, size_t w, size_t h, uptr alignment = alignof( T ) ) { 48 return array2d< T >( ( T * ) memarena_push_size( arena, sizeof( T ) * w * h, alignment ), w, h ); 49 } 50 51 #define memarena_push_many( arena, type, count, ... ) ( ( type * ) memarena_push_size( arena, sizeof( type ) * count, ##__VA_ARGS__ ) ) 52 53 #define memarena_push_array( arena, type, count, ... ) \ 54 array< type >( ( ( type * ) memarena_push_size( arena, sizeof( type ) * count, ##__VA_ARGS__ ) ), count ) 55 #define memarena_push_array2d( arena, type, width, height, ... ) \ 56 array2d< type >( ( ( type * ) memarena_push_size( arena, sizeof( type ) * width * height, ##__VA_ARGS__ ) ), width, height ) 57 58 MemoryArena memarena_push_arena( MemoryArena * arena, size_t size ); 59 60 void memarena_clear( MemoryArena * arena ); 61 62 MemoryArenaCheckpoint memarena_checkpoint( MemoryArena * arena ); 63 void memarena_restore( MemoryArena * arena, MemoryArenaCheckpoint * cp ); 64 65 #define MEMARENA_SCOPED_CHECKPOINT( arena ) MemoryArenaAutoCheckpoint COUNTER_NAME( mem_cp )( arena, memarena_checkpoint( arena ) );