Full rewrite

This commit is contained in:
Ole Morud
2023-06-17 12:14:28 +02:00
committed by Ole Morud
parent e5fa743d85
commit 069f6b11dc
9 changed files with 176 additions and 272 deletions

View File

@@ -2,23 +2,60 @@
#ifndef ARENA_H
#define ARENA_H
#include <stddef.h> // ptrdiff_t
#include <stdint.h> // uintptr_t
#include <stdbool.h>
#include <stddef.h> // size_t
#define _WORD_SIZE (sizeof(intptr_t))
// linked list terminology:
// https://web.archive.org/web/20230604145332/https://i.stack.imgur.com/2FbXf.png
typedef struct arena {
struct page *head, *last;
} __attribute__((aligned(_WORD_SIZE))) arena_t;
char *data;
size_t size;
size_t cap;
bool grow;
} arena_t;
arena_t arena_new(void);
void arena_reset(arena_t* a);
void* arena_alloc(arena_t* a, size_t len);
void* arena_calloc(arena_t* a, size_t nmemb, size_t size);
void* arena_realloc_tail(arena_t* a, size_t len);
void arena_delete(arena_t* a);
void arena_free(arena_t* a, void* p);
/**
* Allocate a new arena.
* The underlying memory is allocated with mmap.
*/
arena_t arena_new();
/**
* Delete memory mapped for arena.
* Should only be used with arenas from arena_new().
*/
void arena_delete(arena_t *a);
/**
* Attach an arena to an existing memory region.
* The arena will not expand the region if space is exceeded.
*/
static inline arena_t arena_attach(void *ptr, size_t size)
{
return (arena_t) { .data = ptr, .size = 0, .cap = size, .grow = false };
}
/**
* Detach an arena from an existing memory region.
*/
static inline void *arena_detatch(arena_t arena)
{
return arena.data;
}
/**
* Reset an arena.
*/
void arena_reset(arena_t *a);
/**
* Allocate memory from an arena.
* Returns NULL and sets errno on failure.
*/
void *arena_alloc(arena_t *a, size_t len);
/**
* Allocate and zero memory from an arena.
* Returns NULL and sets errno on failure.
*/
void *arena_calloc(arena_t *a, size_t nmemb, size_t size);
#endif