diff --git a/app/src/util/str_util.c b/app/src/util/str_util.c index 352d1d2f..287c08de 100644 --- a/app/src/util/str_util.c +++ b/app/src/util/str_util.c @@ -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); diff --git a/app/src/util/str_util.h b/app/src/util/str_util.h index 25bec444..c016a625 100644 --- a/app/src/util/str_util.h +++ b/app/src/util/str_util.h @@ -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); diff --git a/app/tests/test_strutil.c b/app/tests/test_strutil.c index ce0d5d30..dfd99658 100644 --- a/app/tests/test_strutil.c +++ b/app/tests/test_strutil.c @@ -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; @@ -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; }