Skip to content

Commit d03f443

Browse files
committed
string-list: optionally omit empty string pieces in string_list_split*()
Teach the unified split_string() machinery a new flag bit, STRING_LIST_SPLIT_NONEMPTY, to cause empty split pieces to be omitted from the resulting string list. Signed-off-by: Junio C Hamano <[email protected]>
1 parent ad8b425 commit d03f443

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

string-list.c

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,9 @@ static int append_one(struct string_list *list,
294294
break;
295295
}
296296

297+
if ((flags & STRING_LIST_SPLIT_NONEMPTY) && (end <= p))
298+
return 0;
299+
297300
if (in_place) {
298301
*((char *)end) = '\0';
299302
string_list_append(list, p);

string-list.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,8 @@ int string_list_split_in_place(struct string_list *list, char *string,
286286
enum {
287287
/* trim() resulting string piece before adding it to the list */
288288
STRING_LIST_SPLIT_TRIM = (1 << 0),
289+
/* omit adding empty string piece to the resulting list */
290+
STRING_LIST_SPLIT_NONEMPTY = (1 << 1),
289291
};
290292

291293
int string_list_split_f(struct string_list *, const char *string,

t/unit-tests/u-string-list.c

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,13 @@ void test_string_list__split_f(void)
9292
"foo", "bar", "baz", NULL);
9393
t_string_list_split_f(" a b c ", " ", 1, STRING_LIST_SPLIT_TRIM,
9494
"a", "b c", NULL);
95+
t_string_list_split_f("::foo::bar:baz:", ":", -1, STRING_LIST_SPLIT_NONEMPTY,
96+
"foo", "bar", "baz", NULL);
97+
t_string_list_split_f("foo:baz", ":", -1, STRING_LIST_SPLIT_NONEMPTY,
98+
"foo", "baz", NULL);
99+
t_string_list_split_f("foo :: : baz", ":", -1,
100+
STRING_LIST_SPLIT_NONEMPTY | STRING_LIST_SPLIT_TRIM,
101+
"foo", "baz", NULL);
95102
}
96103

97104
static void t_string_list_split_in_place_f(const char *data_, const char *delim,
@@ -125,6 +132,14 @@ void test_string_list__split_in_place_f(void)
125132
"foo", "bar", "baz", NULL);
126133
t_string_list_split_in_place_f(" a b c ", " ", 1, STRING_LIST_SPLIT_TRIM,
127134
"a", "b c", NULL);
135+
t_string_list_split_in_place_f("::foo::bar:baz:", ":", -1,
136+
STRING_LIST_SPLIT_NONEMPTY,
137+
"foo", "bar", "baz", NULL);
138+
t_string_list_split_in_place_f("foo:baz", ":", -1, STRING_LIST_SPLIT_NONEMPTY,
139+
"foo", "baz", NULL);
140+
t_string_list_split_in_place_f("foo :: : baz", ":", -1,
141+
STRING_LIST_SPLIT_NONEMPTY | STRING_LIST_SPLIT_TRIM,
142+
"foo", "baz", NULL);
128143
}
129144

130145
void test_string_list__split(void)

0 commit comments

Comments
 (0)