Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/include/util/hb_buffer.h
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
#ifndef HERB_BUFFER_H
#define HERB_BUFFER_H

#include "hb_arena.h"
#include "hb_string.h"

#include <stdbool.h>
#include <stdlib.h>

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);
Expand Down
19 changes: 18 additions & 1 deletion src/util/hb_buffer.c
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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));
Expand All @@ -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;
}
Expand Down
Loading