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

62 lines
1.5 KiB
C

#include <librr/alloc/arena.h>
#include <librr/strutil.h>
#include <librr/memory.h>
#include <stdlib.h>
typedef struct rr_arena rr_arena_s;
struct rr_arena
{
usz_t capacity;
usz_t offset;
char *allocation;
};
rr_generic_arena_s rr_new_arena(usz_t capacity)
{
rr_arena_s *specifics = malloc(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));
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)
{
free(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;
}