Add support to rz_str_glob and add tests (#18420)

This commit is contained in:
Murphy 2021-03-08 23:23:18 +01:00 committed by Anton Kochkov
parent 6aedaaa678
commit 603edca005
2 changed files with 37 additions and 39 deletions

View file

@ -2253,55 +2253,47 @@ RZ_API void rz_str_filter(char *str, int len) {
}
RZ_API bool rz_str_glob(const char *str, const char *glob) {
const char *cp = NULL, *mp = NULL;
if (!glob || !strcmp(glob, "*")) {
if (!glob) {
return true;
}
if (!strchr(glob, '*')) {
if (*glob == '^') {
glob++;
while (*str) {
if (*glob != *str) {
return false;
}
if (!*++glob) {
return true;
}
str++;
}
} else {
return strstr(str, glob) != NULL;
}
}
if (*glob == '^') {
glob++;
}
while (*str && (*glob != '*')) {
if (*glob != *str) {
return false;
}
glob++;
str++;
char *begin = strchr(glob, '^');
if (begin) {
glob = ++begin;
}
while (*str) {
if (*glob == '*') {
if (!*glob) {
return true;
}
switch (*glob) {
case '*':
if (!*++glob) {
return true;
}
mp = glob;
cp = str + 1;
} else if (*glob == *str) {
glob++;
while (*str) {
if (*glob == *str) {
break;
}
str++;
}
break;
case '$':
return (*++glob == '\x00');
case '?':
str++;
} else {
glob = mp;
str = cp++;
glob++;
break;
default:
if (*glob != *str) {
return false;
}
str++;
glob++;
}
}
while (*glob == '*') {
++glob;
}
return (*glob == '\x00');
return ((*glob == '$' && !*glob++) || !*glob);
}
// Escape the string arg so that it is parsed as a single argument by rz_str_argv

View file

@ -9,9 +9,15 @@ bool test_rz_glob(void) {
mu_assert_eq(rz_str_glob("foo.c", "*.d"), 0, "foo.c -> *.d -> 0");
mu_assert_eq(rz_str_glob("foo.c", "foo*"), 1, "foo.c -> foo* -> 1");
mu_assert_eq(rz_str_glob("foo.c", "*oo*"), 1, "foo.c -> *oo* -> 1");
mu_assert_eq(rz_str_glob("foo.c", "*uu*"), 0, "foo.c -> *uu* -> 1");
mu_assert_eq(rz_str_glob("foo.c", "*uu*"), 0, "foo.c -> *uu* -> 0");
mu_assert_eq(rz_str_glob("foo.c", "f*c*"), 1, "foo.c -> f*c* -> 1");
mu_assert_eq(rz_str_glob("foo.c", "f*d"), 0, "foo.c -> f*d -> 1");
mu_assert_eq(rz_str_glob("foo.c", "f*c**"), 1, "foo.c -> f*c** -> 1");
mu_assert_eq(rz_str_glob("foo.c", "f*d"), 0, "foo.c -> f*d -> 0");
mu_assert_eq(rz_str_glob("foo.c", "*"), 1, "foo.c -> * -> 1");
mu_assert_eq(rz_str_glob("foo.c", "fo?.c"), 1, "foo.c -> fo?.c -> 1");
mu_assert_eq(rz_str_glob("foo.c", "^f"), 1, "foo.c -> ^f -> 1");
mu_assert_eq(rz_str_glob("foo.c", "foo.c$"), 1, "foo.c -> foo.c$ -> 1");
mu_assert_eq(rz_str_glob("foo.c", "fooooooo"), 0, "foo.c -> fooooooo -> 0");
mu_end;
}
@ -20,4 +26,4 @@ int all_tests() {
return tests_passed != tests_run;
}
mu_main(all_tests)
mu_main(all_tests)