memory_arena.cc (1587B)
1 #include "intrinsics.h" 2 #include "memory_arena.h" 3 4 void memarena_init( MemoryArena * arena, u8 * memory, size_t size ) { 5 arena->memory = memory; 6 arena->size = size; 7 arena->used = 0; 8 arena->num_checkpoints = 0; 9 } 10 11 u8 * memarena_push_size( MemoryArena * arena, size_t size, uptr alignment ) { 12 uptr mem_addr = ( uptr ) arena->memory; 13 uptr aligned_addr = align_arbitrary( mem_addr + arena->used, alignment ); 14 uptr new_used = size + ( aligned_addr - mem_addr ); 15 ASSERT( new_used <= arena->size ); 16 ASSERT( new_used >= arena->used ); 17 18 arena->used = new_used; 19 20 return ( u8 * ) aligned_addr; 21 } 22 23 MemoryArena memarena_push_arena( MemoryArena * arena, size_t size ) { 24 u8 * memory = memarena_push_size( arena, size ); 25 26 MemoryArena new_arena = { }; 27 memarena_init( &new_arena, memory, size ); 28 29 return new_arena; 30 } 31 32 void memarena_clear( MemoryArena * arena ) { 33 arena->used = 0; 34 arena->num_checkpoints = 0; 35 } 36 37 MemoryArenaCheckpoint memarena_checkpoint( MemoryArena * arena ) { 38 MemoryArenaCheckpoint cp = { }; 39 // cp.arena = arena; 40 cp.used = arena->used; 41 arena->num_checkpoints++; 42 43 return cp; 44 } 45 46 void memarena_restore( MemoryArena * arena, MemoryArenaCheckpoint * cp ) { 47 ASSERT( arena->num_checkpoints > 0 ); 48 ASSERT( !cp->restored ); 49 ASSERT( arena->used >= cp->used ); 50 51 arena->used = cp->used; 52 arena->num_checkpoints--; 53 cp->restored = true; 54 } 55 56 MemoryArenaAutoCheckpoint::MemoryArenaAutoCheckpoint( MemoryArena * a, MemoryArenaCheckpoint cp ) { 57 arena = a; 58 checkpoint = cp; 59 } 60 61 MemoryArenaAutoCheckpoint::~MemoryArenaAutoCheckpoint() { 62 memarena_restore( arena, &checkpoint ); 63 }