From a2e715a4feea200eb396888f3e7638c1237b3ea5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Timm=20B=C3=A4der?= Date: Fri, 5 Jun 2020 05:29:01 +0200 Subject: [PATCH] strfuncs: Use a GPtrArray in strsplit() This is more efficient and also much easier since we already have the memory allocated that we're going to return from the function. No need to do that ourselves or reverse a list. --- glib/gstrfuncs.c | 26 ++++++++------------------ 1 file changed, 8 insertions(+), 18 deletions(-) diff --git a/glib/gstrfuncs.c b/glib/gstrfuncs.c index f34aca29d..a31ee3c36 100644 --- a/glib/gstrfuncs.c +++ b/glib/gstrfuncs.c @@ -35,6 +35,7 @@ #include #include #include +#include #include /* For tolower() */ #ifdef HAVE_XLOCALE_H @@ -2352,10 +2353,9 @@ g_strsplit (const gchar *string, const gchar *delimiter, gint max_tokens) { - GSList *string_list = NULL, *slist; - gchar **str_array, *s; - guint n = 0; + char *s; const gchar *remainder; + GPtrArray *string_list; g_return_val_if_fail (string != NULL, NULL); g_return_val_if_fail (delimiter != NULL, NULL); @@ -2364,6 +2364,7 @@ g_strsplit (const gchar *string, if (max_tokens < 1) max_tokens = G_MAXINT; + string_list = g_ptr_array_new (); remainder = string; s = strstr (remainder, delimiter); if (s) @@ -2375,28 +2376,17 @@ g_strsplit (const gchar *string, gsize len; len = s - remainder; - string_list = g_slist_prepend (string_list, - g_strndup (remainder, len)); - n++; + g_ptr_array_add (string_list, g_strndup (remainder, len)); remainder = s + delimiter_len; s = strstr (remainder, delimiter); } } if (*string) - { - n++; - string_list = g_slist_prepend (string_list, g_strdup (remainder)); - } + g_ptr_array_add (string_list, g_strdup (remainder)); - str_array = g_new (gchar*, n + 1); + g_ptr_array_add (string_list, NULL); - str_array[n--] = NULL; - for (slist = string_list; slist; slist = slist->next) - str_array[n--] = slist->data; - - g_slist_free (string_list); - - return str_array; + return (char **) g_ptr_array_free (string_list, FALSE); } /**