Add arena allocator library
All checks were successful
Build documentation / build-and-deploy (push) Successful in 2m44s

This commit is contained in:
2026-02-25 18:20:59 +01:00
parent 4e09296709
commit f846edf0ff
11 changed files with 138 additions and 0 deletions

4
libarena/.gitignore vendored Normal file
View File

@@ -0,0 +1,4 @@
*.o
*.json
docs/
.cache/

7
libarena/Makefile Normal file
View File

@@ -0,0 +1,7 @@
include ../make/ufuncs.mk
$(eval $(call add_include,liballoc))
libname := libarena
include ../make/lib.mk

78
libarena/arena.c Normal file
View File

@@ -0,0 +1,78 @@
#include <arena.h>
#include <liballoc.h>
#include <stddef.h>
static struct arena_chunk* arena_create_chunk (size_t capacity) {
size_t size = sizeof (struct arena_chunk) + sizeof (uintptr_t) * capacity;
struct arena_chunk* chunk = malloc (size);
if (chunk == NULL)
return NULL;
chunk->next = NULL;
chunk->size = 0;
chunk->capacity = capacity;
return chunk;
}
static void arena_destroy_chunk (struct arena_chunk* chunk) { free (chunk); }
void arena_reset (struct arena* arena) {
for (struct arena_chunk* chunk = arena->begin; chunk != NULL; chunk = chunk->next) {
chunk->size = 0;
}
arena->end = arena->begin;
}
void arena_destroy (struct arena* arena) {
struct arena_chunk* chunk = arena->begin;
while (chunk) {
struct arena_chunk* chunk1 = chunk;
chunk = chunk->next;
arena_destroy_chunk (chunk1);
}
arena->begin = NULL;
arena->end = NULL;
}
void* arena_malloc (struct arena* arena, size_t size) {
size_t size1 = (size + sizeof (uintptr_t) - 1) / sizeof (uintptr_t);
if (arena->end == NULL) {
size_t capacity = ARENA_CHUNK_CAPACITY;
if (capacity < size1) {
capacity = size1;
}
arena->end = arena_create_chunk (capacity);
if (arena->end == NULL) {
return NULL;
}
arena->begin = arena->end;
}
while (arena->end->size + size1 > arena->end->capacity && arena->end->next != NULL) {
arena->end = arena->end->next;
}
if (arena->end->size + size1 > arena->end->capacity) {
size_t capacity = ARENA_CHUNK_CAPACITY;
if (capacity < size1) {
capacity = size1;
}
arena->end = arena_create_chunk (capacity);
arena->end = arena->end->next;
}
void* result = &arena->end->memory[arena->end->size];
arena->end->size += size1;
return result;
}

25
libarena/arena.h Normal file
View File

@@ -0,0 +1,25 @@
#ifndef _LIBARENA_ARENA_H
#define _LIBARENA_ARENA_H
#include <stddef.h>
#define ARENA_CHUNK_CAPACITY (8 * 1024)
struct arena_chunk {
struct arena_chunk* next;
size_t capacity;
size_t size;
uintptr_t memory[];
};
struct arena {
struct arena_chunk *begin, *end;
};
void arena_reset (struct arena* arena);
void arena_destroy (struct arena* arena);
void* arena_malloc (struct arena* arena, size_t size);
#endif // _LIBARENA_ARENA_H

3
libarena/src.mk Normal file
View File

@@ -0,0 +1,3 @@
c += arena.c
o += arena.o