snac2/xs_match.h

94 lines
2 KiB
C
Raw Normal View History

2024-01-04 08:22:03 +00:00
/* copyright (c) 2022 - 2024 grunfink et al. / MIT license */
2023-09-17 00:52:44 +00:00
#ifndef _XS_MATCH_H
#define _XS_MATCH_H
/* spec is very similar to shell file globbing:
an * matches anything;
a ? matches any character;
| select alternative strings to match;
a \\ escapes a special character;
any other char matches itself. */
int xs_match(const char *str, const char *spec);
#ifdef XS_IMPLEMENTATION
int xs_match(const char *str, const char *spec)
{
2023-09-21 09:37:51 +00:00
const char *b_str;
const char *b_spec = NULL;
const char *o_str = str;
2023-09-17 00:52:44 +00:00
2023-09-21 09:37:51 +00:00
retry:
2023-09-17 00:52:44 +00:00
2023-09-21 09:37:51 +00:00
for (;;) {
char c = *str++;
char p = *spec++;
2023-09-17 00:52:44 +00:00
2023-09-21 09:37:51 +00:00
if (c == '\0') {
/* end of string; also end of spec? */
if (p == '\0' || p == '|')
return 1;
else
break;
}
else
if (p == '?') {
/* match anything except the end */
if (c == '\0')
return 0;
}
else
if (p == '*') {
/* end of spec? match */
if (*spec == '\0')
return 1;
2023-09-17 00:52:44 +00:00
2023-09-21 09:37:51 +00:00
/* store spec for later */
b_spec = spec;
/* back one char */
b_str = --str;
}
else {
if (p == '\\')
p = *spec++;
if (c != p) {
/* mismatch; do we have a backtrack? */
if (b_spec) {
/* continue where we left, one char forward */
spec = b_spec;
str = ++b_str;
}
else
break;
}
}
2023-09-17 00:52:44 +00:00
}
2023-09-21 09:37:51 +00:00
/* try to find an alternative mark */
while (*spec) {
char p = *spec++;
2023-09-17 00:52:44 +00:00
2023-09-21 09:37:51 +00:00
if (p == '\\')
p = *spec++;
2023-09-17 00:52:44 +00:00
2023-09-21 09:37:51 +00:00
if (p == '|') {
/* no backtrack spec, restart str from the beginning */
b_spec = NULL;
str = o_str;
2023-09-17 00:52:44 +00:00
2023-09-21 09:37:51 +00:00
goto retry;
}
2023-09-17 00:52:44 +00:00
}
return 0;
}
#endif /* XS_IMPLEMENTATION */
#endif /* XS_MATCH_H */