[glib/wip/baedert/arrays: 150/150] strfuncs: Use a GPtrArray in strsplit()
- From: Timm Bäder <baedert src gnome org>
- To: commits-list gnome org
- Cc:
- Subject: [glib/wip/baedert/arrays: 150/150] strfuncs: Use a GPtrArray in strsplit()
- Date: Fri, 5 Jun 2020 03:30:41 +0000 (UTC)
commit bbbda3814480c247f1c52f3f2d209fb8a4a98490
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, 7 insertions(+), 19 deletions(-)
---
diff --git a/glib/gstrfuncs.c b/glib/gstrfuncs.c
index f34aca29d..19ad2c30e 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,15 @@ 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_slist_free (string_list);
+ g_ptr_array_add (string_list, g_strdup (remainder));
- 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]