Add strlist_contains()

Add a function to know if a string list, using some separator, contains
a specific string.
This commit is contained in:
Romain Vimont 2021-04-19 09:22:53 +02:00
parent 243854a408
commit ffc00210e9
3 changed files with 36 additions and 0 deletions

View file

@ -140,6 +140,24 @@ parse_integer_with_suffix(const char *s, long *out) {
return true; 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 size_t
utf8_truncation_index(const char *utf8, size_t max_len) { utf8_truncation_index(const char *utf8, size_t max_len) {
size_t len = strlen(utf8); size_t len = strlen(utf8);

View file

@ -43,6 +43,11 @@ parse_integers(const char *s, const char sep, size_t max_items, long *out);
bool bool
parse_integer_with_suffix(const char *s, long *out); 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 // return the index to truncate a UTF-8 string at a valid position
size_t size_t
utf8_truncation_index(const char *utf8, size_t max_len); utf8_truncation_index(const char *utf8, size_t max_len);

View file

@ -287,6 +287,18 @@ static void test_parse_integer_with_suffix(void) {
assert(!ok); 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[]) { int main(int argc, char *argv[]) {
(void) argc; (void) argc;
(void) argv; (void) argv;
@ -304,5 +316,6 @@ int main(int argc, char *argv[]) {
test_parse_integer(); test_parse_integer();
test_parse_integers(); test_parse_integers();
test_parse_integer_with_suffix(); test_parse_integer_with_suffix();
test_strlist_contains();
return 0; return 0;
} }