From 8f874634b1b60e45f4214bcd0c5852f27f05390d Mon Sep 17 00:00:00 2001 From: Francesco Date: Sat, 2 Aug 2025 12:36:52 +0200 Subject: [PATCH] add optional string initial capacity --- string/mystring.c | 12 ++++++++++-- string/mystring.h | 5 +++-- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/string/mystring.c b/string/mystring.c index 932e20e..2e979fc 100644 --- a/string/mystring.c +++ b/string/mystring.c @@ -4,7 +4,7 @@ #include #include -mcl_string *mcl_string_new(const char *text) { +mcl_string *mcl_string_new(const char *text, long initial_capacity) { if (!text) { return NULL; } @@ -17,8 +17,16 @@ mcl_string *mcl_string_new(const char *text) { /* Calculate size and capacity */ str->size = strlen(text); + size_t capacity = initial_capacity; + + if (capacity != -1 && capacity - 1 < str->size) { + return NULL; + } + + if (capacity == -1) { + capacity = (unsigned long)pow(2, (unsigned)log2(str->size) + 1); + } - size_t capacity = (unsigned long)pow(2, (unsigned)log2(str->size) + 1); str->capacity = capacity; /* Allocate data buffer */ diff --git a/string/mystring.h b/string/mystring.h index 63a98df..f6daa54 100644 --- a/string/mystring.h +++ b/string/mystring.h @@ -16,11 +16,12 @@ typedef struct mcl_string_t { * @brief Create a new string * * @param text The text to initialize from + * @param initial_capacity The initial capacity, pass -1 to retrieve it from the text * @return Pointer to the new string, or NULL on failure * - * @note The caller is responsible for freeing the returned string with mcl_string_free() + * @note The caller is responsible for freeing the returned string with mcl_string_free() and to pass the right inital_capacity */ -mcl_string *mcl_string_new(const char *text); +mcl_string *mcl_string_new(const char *text, long initial_capacity); /** * @brief Append text to an existing string