From f5c5e4cdd731c557fa9286f1722e0a1ea236283f Mon Sep 17 00:00:00 2001 From: laentropia Date: Sun, 31 May 2026 20:48:45 -0600 Subject: [PATCH] addition: init and destroy ByteString --- include/lae_strings.h | 13 ++++++++++ src/lae_strings.c | 57 ++++++++++++++++++++++++++++++++++++++++--- src/main.c | 15 ++---------- 3 files changed, 69 insertions(+), 16 deletions(-) diff --git a/include/lae_strings.h b/include/lae_strings.h index ea61f21..037e450 100644 --- a/include/lae_strings.h +++ b/include/lae_strings.h @@ -1,6 +1,19 @@ #ifndef LAE_STRINGS_H #define LAE_STRINGS_H +#include "lae_allocator.h" typedef struct ByteStr ByteStr; +typedef enum { + STR_OK, + STR_BAD_ALLOC, + STR_OUT_OF_BOUNDS, + STR_NULL_ARG, + STR_NULL_STRING, + STR_INVALID_CAPACITY, +} StringErr; + +StringErr bstr_init(ByteStr **bstr, Allocator alloc, size_t capacity); +StringErr bstr_destroy(ByteStr **bstr); + #endif diff --git a/src/lae_strings.c b/src/lae_strings.c index ea06c5b..610fd1f 100644 --- a/src/lae_strings.c +++ b/src/lae_strings.c @@ -1,12 +1,63 @@ #include "lae_strings.h" #include "lae_allocator.h" #include +#include #include +#include struct ByteStr { - uint8_t* buf; - size_t len; - size_t cap; + uint8_t *buf; + size_t len; + size_t cap; Allocator allocator; }; + +StringErr bstr_init(ByteStr **bstr, Allocator alloc, size_t capacity) { + if (bstr == NULL) { + return STR_NULL_ARG; + } + + if (capacity < 1) { + return STR_INVALID_CAPACITY; + } + + ByteStr *new_bstr = alloc.alloc(alloc.ctx, sizeof(ByteStr)); + if (new_bstr == NULL) { + return STR_BAD_ALLOC; + } + + uint8_t *new_buf = alloc.alloc(alloc.ctx, capacity); + if (new_buf == NULL) { + alloc.free(alloc.ctx, new_bstr, sizeof(ByteStr)); + return STR_BAD_ALLOC; + } + + *new_bstr = (ByteStr){ + .buf = new_buf, + .len = 0, + .cap = capacity, + .allocator = alloc, + }; + + *bstr = new_bstr; + return STR_OK; +} + +StringErr bstr_destroy(ByteStr **bstr) { + if (bstr == NULL || *bstr == NULL) { + return STR_NULL_ARG; + } + + ByteStr *tmp = *bstr; + + tmp->allocator.free(tmp->allocator.ctx, tmp->buf, tmp->cap); + tmp->buf = NULL; + tmp->cap = 0; + tmp->len = 0; + + tmp->allocator.free(tmp->allocator.ctx, *bstr, sizeof(ByteStr)); + *bstr = NULL; + + return STR_OK; +} diff --git a/src/main.c b/src/main.c index b9c4c40..dbb4d4d 100644 --- a/src/main.c +++ b/src/main.c @@ -1,18 +1,7 @@ -#include "mylib.h" - +#include "lae_strings.h" #include #include int main(void) { - MyLib *lib = mylib_create(); - if (!lib) { - fprintf(stderr, "Error: could not create MyLib\n"); - return EXIT_FAILURE; - } - - int result = mylib_do_something(lib, 42); - printf("Result: %d\n", result); - - mylib_destroy(lib); - return EXIT_SUCCESS; + return EXIT_SUCCESS; }