Add simple memory arena implementation

This commit is contained in:
Abdelrahman Said 2023-12-31 15:42:55 +00:00
parent 2905b71835
commit 1bb3a0b196
2 changed files with 65 additions and 0 deletions

47
mem_arena/arena.c Normal file
View File

@ -0,0 +1,47 @@
#include "arena.h"
#include "../aliases.h"
#include <stdlib.h>
#include <string.h>
bool arena_init(arena_t *arena, u64 capacity) {
arena->buf = (u8 *)malloc(capacity);
if (!(arena->buf)) {
return false;
}
arena->capacity = capacity;
arena->offset = arena->buf;
return true;
}
u8 *arena_alloc(arena_t *arena, u64 size) {
if (arena->offset + size >= arena->buf + arena->capacity) {
return NULL;
}
u8 *output = arena->offset;
arena->offset += size;
return output;
}
void arena_clear(arena_t *arena) {
memset(arena->buf, 0, arena->offset - arena->buf);
arena->offset = arena->buf;
}
void arena_free(arena_t *arena) {
arena->capacity = 0;
arena->offset = NULL;
if (arena->buf) {
free(arena->buf);
}
arena->buf = NULL;
}

18
mem_arena/arena.h Normal file
View File

@ -0,0 +1,18 @@
#ifndef ARENA_H
#define ARENA_H
#include "../aliases.h"
#include <stdbool.h>
typedef struct {
u64 capacity;
u8 *buf;
u8 *offset;
} arena_t;
bool arena_init(arena_t *arena, u64 capacity);
u8 *arena_alloc(arena_t *arena, u64 size);
void arena_clear(arena_t *arena);
void arena_free(arena_t *arena);
#endif // !ARENA_H