add optional string initial capacity
This commit is contained in:
@@ -4,7 +4,7 @@
|
||||
#include <stdlib.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) {
|
||||
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 */
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user