Base/platform/src-c/alloc/arena.c

53 lines
1.5 KiB
C
Raw Normal View History

#include <alloc/arena.h>
#include <librr/strutil.h>
#include <librr/memory.h>
rr_generic_arena_s rr_new_arena(rr_generic_allocator_s *allocator, usz_t capacity)
{
rr_arena_s *specifics = rr_alloc(allocator, sizeof(rr_arena_s) + capacity);
specifics->capacity = capacity;
specifics->offset = 0;
// The arena allocation is right after the head structure.
specifics->allocation = (void *) (specifics + sizeof(rr_arena_s));
specifics->allocator = allocator;
rr_generic_arena_s arena;
arena.fn_alloc = &rr_arena_alloc;
arena.fn_destruct = &rr_destruct_arena;
arena.specifics = specifics;
return arena;
}
void rr_destruct_arena(rr_generic_arena_s *generic_arena)
{
rr_arena_s *arena = generic_arena->specifics;
rr_free(arena->allocator, generic_arena->specifics);
}
void * rr_arena_alloc(rr_generic_arena_s *generic_arena, usz_t length)
{
rr_arena_s *arena = generic_arena->specifics;
if((arena->offset + length) > arena->capacity)
return NULL;
void *block = &arena->allocation[arena->offset];
arena->offset += length;
return block;
}
char * rr_arena_clone_string(rr_generic_arena_s *generic_arena, const char *string)
{
usz_t len_string = rr_measure_string(string);
char *cloned_string = rr_arena_alloc(generic_arena, len_string+1);
if(cloned_string == NULL)
return NULL;
rr_memcopy(cloned_string, string, len_string);
cloned_string[len_string] = 0x00;
return cloned_string;
}