From e0544300fb7da9a660a55eaf25f1996af573cd43 Mon Sep 17 00:00:00 2001 From: dec05eba Date: Sun, 24 Feb 2019 20:01:58 +0100 Subject: Separate buffers from general allocation, but still have them in scoped allocator --- src/buffer.c | 42 ++++++++++++++++++++++++++++-------------- 1 file changed, 28 insertions(+), 14 deletions(-) (limited to 'src/buffer.c') diff --git a/src/buffer.c b/src/buffer.c index ad50771..349c186 100644 --- a/src/buffer.c +++ b/src/buffer.c @@ -1,41 +1,55 @@ #include "../include/buffer.h" #include "../include/alloc.h" #include "../include/mem.h" +#include "../include/scoped_allocator.h" #include -int buffer_init(Buffer *self, ScopedAllocator *allocator, usize initial_capacity) { +int buffer_init(Buffer *self, ScopedAllocator *allocator) { + self->data = NULL; + self->size = 0; + self->capacity = 0; self->allocator = allocator; + if(self->allocator) + return scoped_allocator_add_buffer(self->allocator, self); + return 0; +} + +void buffer_deinit(Buffer *self) { + am_free(self->data); + self->data = NULL; self->size = 0; - self->capacity = initial_capacity; - return scoped_allocator_alloc(self->allocator, initial_capacity, (void**)&self->data); + self->capacity = 0; } -static CHECK_RESULT int buffer_ensure_capacity_for(Buffer *self, usize size) { +static CHECK_RESULT int buffer_ensure_capacity(Buffer *self, usize new_capacity) { + usize capacity; void *new_mem; int alloc_result; - usize new_capacity; - new_capacity = self->size + size; if(self->capacity >= new_capacity) return BUFFER_OK; - /* - We are using alloc here instead of realloc because we are using scoped allocator - which doesn't reallocate. TODO: Verify if scoped allocator node size is enough to hold buffers... - */ - alloc_result = scoped_allocator_alloc(self->allocator, new_capacity, &new_mem); + capacity = self->capacity; + if(capacity == 0) { + capacity = new_capacity; + } else { + while(capacity < new_capacity) { + capacity *= 1.5; + } + } + + alloc_result = am_realloc(self->data, capacity, &new_mem); if(alloc_result != ALLOC_OK) return BUFFER_ALLOC_FAIL; self->data = new_mem; - self->capacity = new_capacity; + self->capacity = capacity; return BUFFER_OK; } int buffer_append(Buffer *self, void *data, usize size) { - return_if_error(buffer_ensure_capacity_for(self, size)); + return_if_error(buffer_ensure_capacity(self, self->size + size)); am_memcpy(self->data + self->size, data, size); - self->size += size; return BUFFER_OK; } -- cgit v1.2.3