From 525694bea7724d612a8b742943a0ed2aed5822f8 Mon Sep 17 00:00:00 2001 From: Aryadev Chavali Date: Wed, 1 Nov 2023 19:08:59 +0000 Subject: Added an arena allocator A page is a flexibly allocated structure of bytes, with a count of the number of bytes already allocated (used) and number of bytes available overall (available), with a pointer to the next page, if any. heap_t is a linked list of pages. One may allocate a requested size off the heap which causes one of two things: 1) Either a page already exists with enough space for the requested size, in which case that page's pointer is used as the base for the requested pointer 2) No pages satisfy the requested size, so a new page is allocated which is the new end of the heap. --- lib/heap.h | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 lib/heap.h (limited to 'lib/heap.h') diff --git a/lib/heap.h b/lib/heap.h new file mode 100644 index 0000000..b84baf0 --- /dev/null +++ b/lib/heap.h @@ -0,0 +1,43 @@ +/* Copyright (C) 2023 Aryadev Chavali + + * You may distribute and modify this code under the terms of the + * GPLv2 license. You should have received a copy of the GPLv2 + * license with this file. If not, please write to: + * aryadev@aryadevchavali.com. + + * Created: 2023-11-01 + * Author: Aryadev Chavali + * Description: Arena allocator + */ + +#ifndef HEAP_H +#define HEAP_H + +#include "./base.h" + +#include + +#define PAGE_DEFAULT_SIZE 64 + +typedef struct Page +{ + struct Page *next; + size_t used, available; + byte data[]; +} page_t; + +page_t *page_create(size_t, page_t *); +size_t page_space_left(page_t *); +void page_delete(page_t *); + +typedef struct +{ + page_t *beg, *end; + size_t pages; +} heap_t; + +void heap_create(heap_t *); +byte *heap_allocate(heap_t *, size_t); +void heap_stop(heap_t *); + +#endif -- cgit v1.2.3-13-gbd6f