blob: 668429a50eaf0fa4f4cff91ed05aa65c8f6e9907 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
/* copyright (c) 2022 - 2024 grunfink et al. / MIT license */
#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)
{
const char *b_str;
const char *b_spec = NULL;
const char *o_str = str;
retry:
for (;;) {
char c = *str++;
char p = *spec++;
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;
/* 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;
}
}
}
/* try to find an alternative mark */
while (*spec) {
char p = *spec++;
if (p == '\\')
p = *spec++;
if (p == '|') {
/* no backtrack spec, restart str from the beginning */
b_spec = NULL;
str = o_str;
goto retry;
}
}
return 0;
}
#endif /* XS_IMPLEMENTATION */
#endif /* XS_MATCH_H */
|