2024-01-19 20:30:43 +00:00
|
|
|
#include <librr/alloc/arena.h>
|
|
|
|
#include <librr/strutil.h>
|
|
|
|
#include <librr/memory.h>
|
|
|
|
|
|
|
|
#include <stdlib.h>
|
2024-01-19 19:41:13 +00:00
|
|
|
|
2024-01-19 21:05:57 +00:00
|
|
|
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)
|
2024-01-19 19:41:13 +00:00
|
|
|
{
|
2024-01-19 21:05:57 +00:00
|
|
|
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;
|
|
|
|
|
2024-01-19 19:41:13 +00:00
|
|
|
return arena;
|
|
|
|
}
|
|
|
|
|
2024-01-19 21:05:57 +00:00
|
|
|
void rr_destruct_arena(rr_generic_arena_s *generic_arena)
|
2024-01-19 19:41:13 +00:00
|
|
|
{
|
2024-01-19 21:05:57 +00:00
|
|
|
free(generic_arena->specifics);
|
2024-01-19 19:41:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
2024-01-19 21:05:57 +00:00
|
|
|
void * rr_arena_alloc(rr_generic_arena_s *generic_arena, usz_t length)
|
2024-01-19 19:41:13 +00:00
|
|
|
{
|
2024-01-19 21:05:57 +00:00
|
|
|
rr_arena_s *arena = generic_arena->specifics;
|
|
|
|
|
2024-01-19 19:41:13 +00:00
|
|
|
if((arena->offset + length) > arena->capacity)
|
|
|
|
return NULL;
|
|
|
|
|
|
|
|
void *block = &arena->allocation[arena->offset];
|
|
|
|
arena->offset += length;
|
|
|
|
return block;
|
|
|
|
}
|
|
|
|
|
2024-01-19 21:05:57 +00:00
|
|
|
char * rr_arena_clone_string(rr_generic_arena_s *generic_arena, const char *string)
|
2024-01-19 19:41:13 +00:00
|
|
|
{
|
|
|
|
usz_t len_string = rr_measure_string(string);
|
2024-01-19 21:05:57 +00:00
|
|
|
char *cloned_string = rr_arena_alloc(generic_arena, len_string+1);
|
2024-01-19 19:41:13 +00:00
|
|
|
if(cloned_string == NULL)
|
|
|
|
return NULL;
|
|
|
|
rr_memcopy(cloned_string, string, len_string);
|
|
|
|
cloned_string[len_string] = 0x00;
|
|
|
|
|
|
|
|
return cloned_string;
|
|
|
|
}
|