strv: make strv_split() accept empty string
authorYu Watanabe <watanabe.yu+github@gmail.com>
Thu, 28 Jun 2018 09:18:55 +0000 (18:18 +0900)
committerYu Watanabe <watanabe.yu+github@gmail.com>
Fri, 6 Jul 2018 16:34:18 +0000 (01:34 +0900)
src/basic/strv.c
src/test/test-strv.c

index b371623..abf3fc4 100644 (file)
@@ -253,6 +253,10 @@ char **strv_split(const char *s, const char *separator) {
 
         assert(s);
 
+        s += strspn(s, separator);
+        if (isempty(s))
+                return new0(char*, 1);
+
         n = 0;
         FOREACH_WORD_SEPARATOR(word, l, s, separator, state)
                 n++;
index 1c19223..340b562 100644 (file)
@@ -180,12 +180,31 @@ static void test_strv_split(void) {
         const char str[] = "one,two,three";
 
         l = strv_split(str, ",");
-
         assert_se(l);
+        STRV_FOREACH(s, l)
+                assert_se(streq(*s, input_table_multiple[i++]));
 
-        STRV_FOREACH(s, l) {
+        i = 0;
+        strv_free(l);
+
+        l = strv_split("    one    two\t three", WHITESPACE);
+        assert_se(l);
+        STRV_FOREACH(s, l)
                 assert_se(streq(*s, input_table_multiple[i++]));
-        }
+}
+
+static void test_strv_split_empty(void) {
+        _cleanup_strv_free_ char **l = NULL;
+
+        l = strv_split("", WHITESPACE);
+        assert_se(l);
+        assert_se(strv_isempty(l));
+
+        strv_free(l);
+        l = strv_split("    ", WHITESPACE);
+        assert_se(l);
+        assert_se(strv_isempty(l));
+
 }
 
 static void test_strv_split_extract(void) {
@@ -733,6 +752,7 @@ int main(int argc, char *argv[]) {
         test_invalid_unquote("'x'y'g");
 
         test_strv_split();
+        test_strv_split_empty();
         test_strv_split_extract();
         test_strv_split_newlines();
         test_strv_split_nulstr();