Skip to content

Commit

Permalink
Add strlist_contains()
Browse files Browse the repository at this point in the history
Add a function to know if a string list, using some separator, contains
a specific string.
  • Loading branch information
rom1v committed Apr 19, 2021
1 parent b2e67b5 commit 9d3bf09
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
18 changes: 18 additions & 0 deletions app/src/util/str_util.c
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,24 @@ parse_integer_with_suffix(const char *s, long *out) {
return true;
}

bool
strlist_contains(const char *list, char sep, const char *s) {
char *p;
do {
p = strchr(list, sep);

size_t token_len = p ? (size_t) (p - list) : strlen(list);
if (!strncmp(list, s, token_len)) {
return true;
}

if (p) {
list = p + 1;
}
} while (p);
return false;
}

size_t
utf8_truncation_index(const char *utf8, size_t max_len) {
size_t len = strlen(utf8);
Expand Down
5 changes: 5 additions & 0 deletions app/src/util/str_util.h
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ parse_integers(const char *s, const char sep, size_t max_items, long *out);
bool
parse_integer_with_suffix(const char *s, long *out);

// search s in the list separated by sep
// for example, strlist_contains("a,bc,def", ',', "bc") returns true
bool
strlist_contains(const char *list, char sep, const char *s);

// return the index to truncate a UTF-8 string at a valid position
size_t
utf8_truncation_index(const char *utf8, size_t max_len);
Expand Down
13 changes: 13 additions & 0 deletions app/tests/test_strutil.c
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,18 @@ static void test_parse_integer_with_suffix(void) {
assert(!ok);
}

static void test_strlist_contains(void) {
assert(strlist_contains("a,bc,def", ',', "bc"));
assert(!strlist_contains("a,bc,def", ',', "b"));
assert(strlist_contains("", ',', ""));
assert(strlist_contains("abc,", ',', ""));
assert(strlist_contains(",abc", ',', ""));
assert(strlist_contains("abc,,def", ',', ""));
assert(!strlist_contains("abc", ',', ""));
assert(strlist_contains(",,|x", '|', ",,"));
assert(strlist_contains("xyz", '\0', "xyz"));
}

int main(int argc, char *argv[]) {
(void) argc;
(void) argv;
Expand All @@ -304,5 +316,6 @@ int main(int argc, char *argv[]) {
test_parse_integer();
test_parse_integers();
test_parse_integer_with_suffix();
test_strlist_contains();
return 0;
}

0 comments on commit 9d3bf09

Please sign in to comment.