string-util: introduce streq_skip_trailing_chars()

This commit is contained in:
Antony Deepak Thomas
2021-09-29 12:57:30 +09:00
committed by Yu Watanabe
parent 46a0f5cac8
commit 8034b42ca6
3 changed files with 46 additions and 0 deletions
+16
View File
@@ -1146,3 +1146,19 @@ int string_contains_word_strv(const char *string, const char *separators, char *
*ret_word = found;
return !!found;
}
bool streq_skip_trailing_chars(const char *s1, const char *s2, const char *ok) {
if (!s1 && !s2)
return true;
if (!s1 || !s2)
return false;
if (!ok)
ok = WHITESPACE;
for (; *s1 && *s2; s1++, s2++)
if (*s1 != *s2)
break;
return in_charset(s1, ok) && in_charset(s2, ok);
}
+2
View File
@@ -226,3 +226,5 @@ int string_contains_word_strv(const char *string, const char *separators, char *
static inline int string_contains_word(const char *string, const char *separators, const char *word) {
return string_contains_word_strv(string, separators, STRV_MAKE(word), NULL);
}
bool streq_skip_trailing_chars(const char *s1, const char *s2, const char *ok);
+28
View File
@@ -1000,6 +1000,33 @@ static void test_strextendf(void) {
assert_se(streq(p, "<77>,<99>,< 88>,<00001234>"));
}
static void test_streq_skip_trailing_chars(void) {
log_info("/* %s */", __func__);
/* NULL is WHITESPACE by default*/
assert_se(streq_skip_trailing_chars("foo bar", "foo bar", NULL));
assert_se(streq_skip_trailing_chars("foo", "foo", NULL));
assert_se(streq_skip_trailing_chars("foo bar ", "foo bar", NULL));
assert_se(streq_skip_trailing_chars("foo bar", "foo bar\t\t", NULL));
assert_se(streq_skip_trailing_chars("foo bar ", "foo bar\t\t", NULL));
assert_se(streq_skip_trailing_chars("foo\nbar", "foo\nbar", NULL));
assert_se(streq_skip_trailing_chars("\t\tfoo bar", "\t\tfoo bar", NULL));
assert_se(streq_skip_trailing_chars(" foo bar\t", " foo bar\n", NULL));
assert_se(!streq_skip_trailing_chars("foobar", "foo bar", NULL));
assert_se(!streq_skip_trailing_chars("foo\nbar", "foo\tbar", NULL));
assert_se(!streq_skip_trailing_chars("\t\nfoo bar", "\t foo bar", NULL));
assert_se(streq_skip_trailing_chars("foo bar ", "foo bar", WHITESPACE));
assert_se(!streq_skip_trailing_chars("foo bar ", "foo bar", NEWLINE));
assert_se(streq_skip_trailing_chars(NULL, NULL, NULL));
assert_se(streq_skip_trailing_chars("", "", NULL));
assert_se(!streq_skip_trailing_chars(NULL, "foo bar", NULL));
assert_se(!streq_skip_trailing_chars("foo", NULL, NULL));
assert_se(!streq_skip_trailing_chars("", "f", NULL));
}
int main(int argc, char *argv[]) {
test_setup_logging(LOG_DEBUG);
@@ -1039,6 +1066,7 @@ int main(int argc, char *argv[]) {
test_string_contains_word();
test_strverscmp_improved();
test_strextendf();
test_streq_skip_trailing_chars();
return 0;
}