nm-utils: add a wrapper for g_strsplit_set() removing empty strings from array

g_strsplit_set() puts empty strings ("") into the resulting string array when
a delimiter character appears as the first or last character in the string or
when there are adjacent delimiter characters. However, this is not what is
useful in most cases.
This commit is contained in:
Jiří Klimeš
2014-09-10 09:36:59 +02:00
parent 9197d76e96
commit 112c53be32
2 changed files with 41 additions and 2 deletions

View File

@@ -15,7 +15,7 @@
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
* Copyright 2005 - 2008 Red Hat, Inc.
* Copyright 2005 - 2014 Red Hat, Inc.
*/
#ifndef __NM_UTILS_PRIVATE_H__
@@ -78,4 +78,8 @@ void _nm_utils_ip6_routes_from_dbus (const GValue *dbus_value,
GSList * _nm_utils_strv_to_slist (char **strv);
char ** _nm_utils_slist_to_strv (GSList *slist);
char ** _nm_utils_strsplit_set (const char *str,
const char *delimiters,
int max_tokens);
#endif

View File

@@ -16,7 +16,7 @@
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
* Copyright 2005 - 2013 Red Hat, Inc.
* Copyright 2005 - 2014 Red Hat, Inc.
*/
#include "config.h"
@@ -706,6 +706,41 @@ _nm_utils_slist_to_strv (GSList *slist)
return strv;
}
/**
* _nm_utils_strsplit_set:
* @str: string to split
* @delimiters: string of delimiter characters
* @max_tokens: the maximum number of tokens to split string into. When it is
* less than 1, the @str is split completely.
*
* Utility function for splitting string into a string array. It is a wrapper
* for g_strsplit_set(), but it also removes empty strings from the vector as
* they are not useful in most cases.
*
* Returns: (transfer full): a newly allocated NULL-terminated array of strings.
* The caller must free the returned array with g_strfreev().
**/
char **
_nm_utils_strsplit_set (const char *str, const char *delimiters, int max_tokens)
{
char **result;
uint i;
uint j;
result = g_strsplit_set (str, delimiters, max_tokens);
/* remove empty strings */
for (i = 0; result && result[i]; i++) {
if (*result[i] == '\0') {
g_free (result[i]);
for (j = i; result[j]; j++)
result[j] = result[j + 1];
i--;
}
}
return result;
}
static gboolean
device_supports_ap_ciphers (guint32 dev_caps,
guint32 ap_flags,