Fix g_strsplit() when delimiter at end-of-string and at max_count.
authorJonathan Pryor <jonpryor@vt.edu>
Thu, 16 Aug 2012 19:10:38 +0000 (15:10 -0400)
committerJonathan Pryor <jonpryor@vt.edu>
Thu, 16 Aug 2012 19:18:12 +0000 (15:18 -0400)
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.

eglib/src/gstr.c
eglib/test/string-util.c

index 0f66a43372e96e0f2ad6db4ac0ec3ef76290ecd6..335ccff9365ba7ae6c3e6cec0a8d7f18083bd151 100644 (file)
@@ -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++;
        }
        
index 6c8b8892e94709c7fb502b03c257e3ce48fb680a..73efd13f4de91ecfbbe8a8139f139d2e56cc795e 100644 (file)
@@ -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;
 }