string: Split g_string_maybe_expand

Split off g_string_expand, and inline just
the size check.
This commit is contained in:
Matthias Clasen 2023-01-13 22:19:55 -05:00
parent e9fc91550f
commit 34b7992fd6

View File

@ -75,22 +75,29 @@
*/ */
static void static void
g_string_maybe_expand (GString *string, g_string_expand (GString *string,
gsize len) gsize len)
{ {
/* Detect potential overflow */ /* Detect potential overflow */
if G_UNLIKELY ((G_MAXSIZE - string->len - 1) < len) if G_UNLIKELY ((G_MAXSIZE - string->len - 1) < len)
g_error ("adding %" G_GSIZE_FORMAT " to string would overflow", len); g_error ("adding %" G_GSIZE_FORMAT " to string would overflow", len);
if (string->len + len >= string->allocated_len) string->allocated_len = g_nearest_pow (string->len + len + 1);
{ /* If the new size is bigger than G_MAXSIZE / 2, only allocate enough
string->allocated_len = g_nearest_pow (string->len + len + 1); * memory for this string and don't over-allocate.
/* If the new size is bigger than G_MAXSIZE / 2, only allocate enough */
* memory for this string and don't over-allocate. */ if (string->allocated_len == 0)
if (string->allocated_len == 0) string->allocated_len = string->len + len + 1;
string->allocated_len = string->len + len + 1;
string->str = g_realloc (string->str, string->allocated_len); string->str = g_realloc (string->str, string->allocated_len);
} }
static inline void
g_string_maybe_expand (GString *string,
gsize len)
{
if (G_UNLIKELY (string->len + len >= string->allocated_len))
g_string_expand (string, len);
} }
/** /**
@ -113,7 +120,7 @@ g_string_sized_new (gsize dfl_size)
string->len = 0; string->len = 0;
string->str = NULL; string->str = NULL;
g_string_maybe_expand (string, MAX (dfl_size, 64)); g_string_expand (string, MAX (dfl_size, 64));
string->str[0] = 0; string->str[0] = 0;
return string; return string;