Skip to content

Instantly share code, notes, and snippets.

@rexim
Created November 16, 2019 19:51
Show Gist options
  • Save rexim/d4b8380a354b52d1721c6e6e46066483 to your computer and use it in GitHub Desktop.
Save rexim/d4b8380a354b52d1721c6e6e46066483 to your computer and use it in GitHub Desktop.
#include <assert.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#define KILO 1024
#define MEGA (1024 * KILO)
#define ARENA_CAPACITY 16
typedef struct Arena Arena;
struct Arena {
Arena *next;
size_t size;
size_t capacity;
uint8_t *memory;
};
Arena begin = {0};
Arena *current = &begin;
void *arena_alloc(size_t size)
{
for (;;) {
if (!current->memory) {
current->capacity = size > ARENA_CAPACITY ? size : ARENA_CAPACITY;
current->memory = calloc(1, current->capacity);
}
if (current->size + size <= current->capacity) {
void *result = current->memory + current->size;
current->size += size;
return result;
}
if (!current->next) {
current->next = calloc(1, sizeof(Arena));
}
current = current->next;
}
}
void arena_clean(void)
{
Arena *iter = &begin;
while (iter) {
iter->size = 0;
iter = iter->next;
}
current = &begin;
}
void arena_print(void)
{
Arena *iter = &begin;
while (iter) {
if (iter->memory) {
for (size_t i = 0; i < iter->capacity; ++i) {
printf("%02x ", iter->memory[i]);
}
printf("\n");
for (size_t i = 0; i <= iter->capacity; ++i) {
if (i == iter->size) {
printf("^ ");
} else {
printf(" ");
}
}
printf("\n");
} else {
printf("[Not initialized]\n");
}
iter = iter->next;
}
printf("------------------------------\n");
}
void test_alloc_n_ints(int n)
{
int *xs = arena_alloc(sizeof(int) * n);
for (int i = 0; i < n; ++i) xs[i] = i;
}
int main(int argc, char *argv[])
{
test_alloc_n_ints(2);
test_alloc_n_ints(8);
arena_print();
arena_clean();
arena_print();
test_alloc_n_ints(9);
test_alloc_n_ints(2);
arena_print();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment