add optional string initial capacity

This commit is contained in:
2025-08-02 12:36:52 +02:00
parent 3547f570e6
commit 8f874634b1
2 changed files with 13 additions and 4 deletions

View File

@@ -4,7 +4,7 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
mcl_string *mcl_string_new(const char *text) { mcl_string *mcl_string_new(const char *text, long initial_capacity) {
if (!text) { if (!text) {
return NULL; return NULL;
} }
@@ -17,8 +17,16 @@ mcl_string *mcl_string_new(const char *text) {
/* Calculate size and capacity */ /* Calculate size and capacity */
str->size = strlen(text); 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; str->capacity = capacity;
/* Allocate data buffer */ /* Allocate data buffer */

View File

@@ -16,11 +16,12 @@ typedef struct mcl_string_t {
* @brief Create a new string * @brief Create a new string
* *
* @param text The text to initialize from * @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 * @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 * @brief Append text to an existing string