diff --git a/src/include/util/hb_buffer.h b/src/include/util/hb_buffer.h index c5276a357..8e6cfe7f4 100644 --- a/src/include/util/hb_buffer.h +++ b/src/include/util/hb_buffer.h @@ -1,18 +1,21 @@ #ifndef HERB_BUFFER_H #define HERB_BUFFER_H +#include "hb_arena.h" #include "hb_string.h" #include #include typedef struct HB_BUFFER_STRUCT { + hb_arena_T* allocator; char* value; size_t length; size_t capacity; } hb_buffer_T; bool hb_buffer_init(hb_buffer_T* buffer, size_t capacity); +bool hb_buffer_init_arena(hb_buffer_T* buffer, hb_arena_T* allocator, size_t capacity); void hb_buffer_append(hb_buffer_T* buffer, const char* text); void hb_buffer_append_with_length(hb_buffer_T* buffer, const char* text, size_t length); diff --git a/src/util/hb_buffer.c b/src/util/hb_buffer.c index aba843fab..0ce4212b5 100644 --- a/src/util/hb_buffer.c +++ b/src/util/hb_buffer.c @@ -22,8 +22,14 @@ static bool hb_buffer_resize(hb_buffer_T* buffer, const size_t new_capacity) { fprintf(stderr, "Error: Buffer capacity would overflow system limits.\n"); exit(1); } + char* new_value = NULL; - char* new_value = realloc(buffer->value, new_capacity + 1); + if (buffer->allocator == NULL) { + new_value = realloc(buffer->value, new_capacity + 1); + } else { + new_value = hb_arena_alloc(buffer->allocator, new_capacity + 1); + memcpy(new_value, buffer->value, buffer->capacity + 1); + } if (unlikely(new_value == NULL)) { fprintf(stderr, "Error: Failed to resize buffer to %zu.\n", new_capacity); @@ -61,6 +67,7 @@ static bool hb_buffer_expand_if_needed(hb_buffer_T* buffer, const size_t require } bool hb_buffer_init(hb_buffer_T* buffer, const size_t capacity) { + buffer->allocator = NULL; buffer->capacity = capacity; buffer->length = 0; buffer->value = malloc(sizeof(char) * (buffer->capacity + 1)); @@ -76,6 +83,16 @@ bool hb_buffer_init(hb_buffer_T* buffer, const size_t capacity) { return true; } +bool hb_buffer_init_arena(hb_buffer_T* buffer, hb_arena_T* allocator, size_t capacity) { + buffer->allocator = allocator; + buffer->capacity = capacity; + buffer->length = 0; + buffer->value = hb_arena_alloc(allocator, sizeof(char) * (buffer->capacity + 1)); + buffer->value[0] = '\0'; + + return true; +} + char* hb_buffer_value(const hb_buffer_T* buffer) { return buffer->value; }