aboutsummaryrefslogtreecommitdiff
path: root/src/buffer.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/buffer.c')
-rw-r--r--src/buffer.c42
1 files changed, 28 insertions, 14 deletions
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 <assert.h>
-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;
}