Added, but neither tested nor documented arena allocator.

This commit is contained in:
Eric-Paul Ickhorn 2024-01-18 21:46:29 +01:00
parent 77b4091a66
commit dd80cb179e
Signed by: epickh
GPG Key ID: F5EBBE013924D95F
2 changed files with 57 additions and 0 deletions

View File

@ -4,6 +4,15 @@
#include <librr/types.h> #include <librr/types.h>
typedef struct rr_arena rr_arena_s;
struct rr_arena
{
usz_t capacity;
usz_t offset;
char *allocation;
};
/// @brief Tests if two memory regions overlap partially or completely. /// @brief Tests if two memory regions overlap partially or completely.
/// @param block1 Block to check for overlapping with block2. /// @param block1 Block to check for overlapping with block2.
// If the address of this block is higher than that of block2, the blocks will be swapped internally. // If the address of this block is higher than that of block2, the blocks will be swapped internally.
@ -43,4 +52,10 @@ usz_t rr_memrep(void *destination, usz_t num_bytes, void *sequence, usz_t len_se
/// @param num_bytes Number of bytes to copy from the source to the destination. /// @param num_bytes Number of bytes to copy from the source to the destination.
void rr_memcopy(void *destination, void *source, usz_t num_bytes); void rr_memcopy(void *destination, void *source, usz_t num_bytes);
rr_arena_s rr_new_arena(usz_t capacity);
void rr_delete_arena(rr_arena_s *arena);
void * rr_arena_alloc(rr_arena_s *arena, usz_t length);
char * rr_arena_clone_string(rr_arena_s *arena, char *string);
#endif // RR_MEMORY_H #endif // RR_MEMORY_H

View File

@ -1,4 +1,6 @@
#include <librr/memory.h> #include <librr/memory.h>
#include <librr/strutil.h>
#include <stdlib.h>
bool_t rr_mem_overlap(void *block1, usz_t length1, void *block2, usz_t length2) bool_t rr_mem_overlap(void *block1, usz_t length1, void *block2, usz_t length2)
{ {
@ -60,3 +62,43 @@ void rr_memcopy(void *destination, void *source, usz_t num_bytes)
for(usz_t index = 0; index < num_bytes; ++index) for(usz_t index = 0; index < num_bytes; ++index)
destination_8[index] = source_8[index]; destination_8[index] = source_8[index];
} }
rr_arena_s rr_new_arena(usz_t capacity)
{
rr_arena_s arena;
arena.capacity = capacity;
arena.offset = 0;
arena.allocation = malloc(capacity);
return arena;
}
void rr_delete_arena(rr_arena_s *arena)
{
if(arena->allocation == NULL) return;
free(arena->allocation);
arena->allocation = NULL;
}
void * rr_arena_alloc(rr_arena_s *arena, usz_t length)
{
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_arena_s *arena, char *string)
{
usz_t len_string = rr_measure_string(string);
char *cloned_string = rr_arena_alloc(arena, len_string+1);
rr_memcopy(cloned_string, string, len_string);
cloned_string[len_string] = 0x00;
return cloned_string;
}