From: Jonathan Pryor Date: Thu, 16 Aug 2012 19:10:38 +0000 (-0400) Subject: Fix g_strsplit() when delimiter at end-of-string and at max_count. X-Git-Url: http://wien.tomnetworks.com/gitweb/?a=commitdiff_plain;h=b8eb131d3f295af150b4712ba7e507ab28dfd27c;p=mono.git Fix g_strsplit() when delimiter at end-of-string and at max_count. Suppose you want to split a `name=value` string: char** kvp = g_strsplit ("name=value", "=", 2); // kvp[0] is "name", kvp[1] is "value" That works, but what if the string is "malformed" and missses a value? char** kvp = g_strsplit ("name=", "=", 2); // kvp[0] is "name", kvp[1] is "=" A value of "=" makes no sense here: values returned from g_strsplit() shouldn't contain delimeter unless max_count is specified and it's _within_ the last string; it's also not what GLib does. What makes sense is a value of "" (the empty string), which IS what GLib does (so it's compatible and sensible). Fix g_strsplit() to use the empty string when the "rest" value would otherwise be the delimiter. --- diff --git a/eglib/src/gstr.c b/eglib/src/gstr.c index 0f66a43372e..335ccff9365 100644 --- a/eglib/src/gstr.c +++ b/eglib/src/gstr.c @@ -251,8 +251,12 @@ g_strsplit (const gchar *string, const gchar *delimiter, gint max_tokens) } if (*string) { - /* Add the rest of the string as the last element */ - add_to_vector (&vector, size, g_strdup (string)); + if (strcmp (string, delimiter) == 0) + add_to_vector (&vector, size, g_strdup ("")); + else { + /* Add the rest of the string as the last element */ + add_to_vector (&vector, size, g_strdup (string)); + } size++; } diff --git a/eglib/test/string-util.c b/eglib/test/string-util.c index 6c8b8892e94..73efd13f4de 100644 --- a/eglib/test/string-util.c +++ b/eglib/test/string-util.c @@ -174,6 +174,16 @@ test_split () g_strfreev (v); + v = g_strsplit ("value=", "=", 2); + if (strcmp (v [0], "value") != 0) + return FAILED ("Invalid value 18; expected 'value', got '%s'", v [0]); + if (strcmp (v [1], "") != 0) + return FAILED ("Invalid value 19; expected '', got '%s'", v [1]); + if (v [2] != NULL) + return FAILED ("Expected only 2 elements (6)"); + + g_strfreev (v); + return OK; }