feat: (str) str_resize

This commit is contained in:
thetek 2023-02-15 09:56:55 +01:00
parent baac095e9d
commit 6b1ad69a34
2 changed files with 19 additions and 8 deletions

View File

@ -32,5 +32,6 @@ bool str_is_blank (const str_t *str); /* check if a string only consists of whit
void str_downcase (str_t *str); /* transform all uppercase characters in a str_t string to lowercase */
void str_upcase (str_t *str); /* transform all lowercase characters in a str_t string to uppercase */
void str_clone (const str_t *str, str_t *new); /* clone the contents of a str_t string into a new str_t string. */
void str_resize (str_t *str, size_t cap); /* resize the allocated data of a str_t string. */
#endif // CUTILS_STR_H_

View File

@ -114,14 +114,7 @@ str_append (str_t *str, const char *src)
void
str_append_len (str_t *str, const char *src, size_t len)
{
size_t cap;
cap = max (next_pow_of_two (str->len + len + 1), STR_MIN_ALLOC);
if (cap > str->cap)
{
str->str = srealloc (str->str, cap * sizeof (char));
str->cap = cap;
}
str_resize (str, str->len + len + 1);
strncpy (str->str + str->len, src, len);
str->len += len;
str->str[str->len] = '\0';
@ -299,3 +292,20 @@ str_clone (const str_t *str, str_t *new)
{
str_new_from_len (new, str->str, str->len);
}
/**
* resize the allocated data of a str_t string.
*
* @param str: the string to expand
* @param cap: the minimum amount of capacity to resize to
*/
void
str_resize (str_t *str, size_t cap)
{
cap = max (next_pow_of_two (cap), STR_MIN_ALLOC);
if (cap > str->len && cap != str->cap)
{
str->str = srealloc (str->str, cap * sizeof (char));
str->cap = cap;
}
}