diff --git a/src/core/strings/str8/str8.c b/src/core/strings/str8/str8.c index 24cecd5..ef91f73 100644 --- a/src/core/strings/str8/str8.c +++ b/src/core/strings/str8/str8.c @@ -1,9 +1,12 @@ #include "str8.h" #include "aliases.h" #include "mem_allocator.h" +#include #include #include +#define STR8_BUF_ALLOC_SIZE(CAPACITY) (sizeof(Str8) + sizeof(c8) * CAPACITY) + internal Str8List node_to_list(Str8Node *node); Str8 *wapp_str8_alloc_buf(const Allocator *allocator, u64 capacity) { @@ -13,18 +16,12 @@ Str8 *wapp_str8_alloc_buf(const Allocator *allocator, u64 capacity) { goto RETURN_STR8; } - str = wapp_mem_allocator_alloc(allocator, sizeof(Str8)); + str = wapp_mem_allocator_alloc(allocator, STR8_BUF_ALLOC_SIZE(capacity)); if (!str) { goto RETURN_STR8; } - c8 *buf = wapp_mem_allocator_alloc(allocator, sizeof(c8) * capacity); - if (!buf) { - wapp_mem_allocator_free(allocator, (void **)&str, sizeof(Str8)); - goto RETURN_STR8; - } - - str->buf = buf; + str->buf = (u8 *)str + sizeof(Str8); str->size = 0; str->capacity = capacity; @@ -97,6 +94,14 @@ RETURN_ALLOC_SUBSTR: return output; } +void wapp_str8_dealloc_buf(const Allocator *allocator, Str8 **str) { + if (!allocator || !str || !(*str)) { + return; + } + + wapp_mem_allocator_free(allocator, (void **)str, STR8_BUF_ALLOC_SIZE((*str)->capacity)); +} + c8 wapp_str8_get(const Str8 *str, u64 index) { if (index >= str->size) { return '\0'; diff --git a/src/core/strings/str8/str8.h b/src/core/strings/str8/str8.h index d0a9a49..780d8fa 100644 --- a/src/core/strings/str8/str8.h +++ b/src/core/strings/str8/str8.h @@ -61,6 +61,9 @@ Str8 *wapp_str8_alloc_buf(const Allocator *allocator, u64 capacity); Str8 *wapp_str8_alloc_cstr(const Allocator *allocator, const char *str); Str8 *wapp_str8_alloc_str8(const Allocator *allocator, Str8RO *str); Str8 *wapp_str8_alloc_substr(const Allocator *allocator, Str8RO *str, u64 start, u64 end); +// Only needed for allocators like malloc where each allocation has to be freed on its own. +// No need to use it for allocators like Arena. +void wapp_str8_dealloc_buf(const Allocator *allocator, Str8 **str); /** * Str8 utilities