From eb83f2a91a615c5fa3788d41c3ec80b43bf5ed28 Mon Sep 17 00:00:00 2001 From: Tavian Barnes Date: Mon, 19 Jun 2023 13:43:46 -0400 Subject: alloc: Implement an arena allocator --- src/alloc.h | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) (limited to 'src/alloc.h') diff --git a/src/alloc.h b/src/alloc.h index 899a4ec..65edb92 100644 --- a/src/alloc.h +++ b/src/alloc.h @@ -146,4 +146,48 @@ void *zalloc(size_t align, size_t size); #define ZALLOC_FLEX(type, member, count) \ (type *)zalloc(alignof(type), sizeof_flex(type, member, count)) +/** + * An arena allocator for fixed-size types. + * + * Arena allocators are intentionally not thread safe. + */ +struct arena { + /** The list of free chunks. */ + void *chunks; + /** The number of allocated slabs. */ + size_t nslabs; + /** The array of slabs. */ + void **slabs; + /** Chunk alignment. */ + size_t align; + /** Chunk size. */ + size_t size; +}; + +/** + * Initialize an arena for chunks of the given size and alignment. + */ +void arena_init(struct arena *arena, size_t align, size_t size); + +/** + * Initialize an arena for the given type. + */ +#define ARENA_INIT(arena, type) \ + arena_init((arena), alignof(type), sizeof(type)) + +/** + * Allocate an object out of the arena. + */ +void *arena_alloc(struct arena *arena); + +/** + * Free an object from the arena. + */ +void arena_free(struct arena *arena, void *ptr); + +/** + * Destroy an arena, freeing all allocations. + */ +void arena_destroy(struct arena *arena); + #endif // BFS_ALLOC_H -- cgit v1.2.3