102 lines
2.8 KiB
C
102 lines
2.8 KiB
C
#pragma once
|
|
#include "base_core.h"
|
|
|
|
|
|
typedef U32 ArenaFlags;
|
|
typedef struct ArenaOptions ArenaOptions;
|
|
enum {
|
|
ArenaFlag_NoDecommit = 1, // operations which shrinks the arena does not decommit memory.
|
|
// (arena_trim() can still decommit when called explicitly)
|
|
};
|
|
struct ArenaOptions {
|
|
U32 size;
|
|
U32 commit_size;
|
|
ArenaFlags flags;
|
|
};
|
|
|
|
typedef struct MemoryBlock MemoryBlock;
|
|
struct MemoryBlock {
|
|
U8 *base;
|
|
U32 size; // Block size, page aligned
|
|
U32 first_free; // start of next allocation
|
|
U64 arena_offset; // absolute offset of base relative to the first linked arena
|
|
U32 committed_end; // end of committed region. Will be page aligned
|
|
MemoryBlock *prev;
|
|
};
|
|
|
|
typedef struct Arena Arena;
|
|
struct Arena {
|
|
MemoryBlock *current;
|
|
U32 block_size; // requested block size
|
|
U32 commit_size; // requested commit size
|
|
U32 page_size; // cached page size
|
|
ArenaFlags flags;
|
|
S32 temp_level;
|
|
};
|
|
|
|
typedef struct ATemp ATemp;
|
|
struct ATemp {
|
|
Arena *arena;
|
|
U64 total_offset;
|
|
};
|
|
#ifndef ArenaOptions_Default
|
|
#define ArenaOptions_Default ((ArenaOptions){ .size = MB(32), .commit_size = KB(64) })
|
|
#endif
|
|
|
|
StaticAssert(sizeof(MemoryBlock) <= 64);
|
|
// Try keep start of user memory at a cacheline
|
|
#define MemoryBlock_Header_Size 64u
|
|
|
|
void arena_init(Arena *arena, const ArenaOptions *params);
|
|
void arena_free(Arena *arena);
|
|
void *arena_push(Arena *arena, U32 size, U32 align);
|
|
|
|
#define arena_push_type(arena, type) arena_push(arena, (U32)sizeof(type), alignof(type))
|
|
// Invalid for arrays > U32
|
|
#define arena_push_array_of(arena, type, len) arena_push(arena, (U32) (sizeof(type) * (len)), alignof(type))
|
|
|
|
void arena_trim(Arena *arena);
|
|
|
|
ATemp arena_temp_begin(Arena *arena);
|
|
void arena_temp_end(ATemp *checkpoint);
|
|
void arena_reset_to(Arena *arena, U64 total_offset);
|
|
void arena_reset(Arena *arena);
|
|
|
|
static INLINE U32 memoryblock_available(const MemoryBlock *block)
|
|
{
|
|
return block->size - block->first_free;
|
|
}
|
|
|
|
static INLINE U64 arena_used(const Arena *arena)
|
|
{
|
|
const MemoryBlock *block = arena->current;
|
|
return block->arena_offset + block->first_free;
|
|
}
|
|
|
|
|
|
static INLINE void *arena_allocator_func(Allocator *allocator, AllocOperation operation , void *memory, U32 size, U32 align)
|
|
{
|
|
switch (operation) {
|
|
case Alloc_Op_Aligned:
|
|
return arena_push(allocator->data, size, align);
|
|
|
|
case Alloc_Op_Free: // can't free from an marena
|
|
return NULL;
|
|
|
|
case Alloc_Op_Free_All:
|
|
arena_free(allocator->data);
|
|
return NULL;
|
|
}
|
|
|
|
Assert(false);
|
|
}
|
|
|
|
static INLINE Allocator arena_allocator(Arena *arena)
|
|
{
|
|
Allocator allocator = {};
|
|
allocator.op_func_ptr = arena_allocator_func;
|
|
allocator.data = arena;
|
|
|
|
return allocator;
|
|
}
|