[glib/wip/baedert/arrays] strfuncs: Use a GPtrArray in strsplit()



commit c9a43c4c25c6ded6cf1aa13cf4a24cef588cacdc
Author: Timm Bäder <mail baedert org>
Date:   Fri Jun 5 05:29:01 2020 +0200

    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..b4dcb636c 100644
--- a/glib/gstrfuncs.c
+++ b/glib/gstrfuncs.c
@@ -35,6 +35,7 @@
 #include <string.h>
 #include <locale.h>
 #include <errno.h>
+#include <garray.h>
 #include <ctype.h>              /* 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));
-    }
-
-  str_array = g_new (gchar*, n + 1);
-
-  str_array[n--] = NULL;
-  for (slist = string_list; slist; slist = slist->next)
-    str_array[n--] = slist->data;
+    g_ptr_array_add (string_list, g_strdup (remainder));
 
-  g_slist_free (string_list);
+  g_ptr_array_add (string_list, NULL);
 
-  return str_array;
+  return (char **)g_ptr_array_free (string_list, FALSE);
 }
 
 /**


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]