summaryrefslogtreecommitdiff
path: root/xs_match.h
blob: 9f12c156323e8a084914e7500251512ad7fc1166 (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
/* copyright (c) 2022 - 2023 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 *o_str = str;

again:
    if (*spec == '*') {
        spec++;                 /* wildcard */

        do {
            if (xs_match(str, spec))
                return 1;
            str++;
        } while (*str);

        return 0;
    }

    if (*spec == '?' && *str) {
        spec++;                 /* any character */
        str++;
        goto again;
    }

    if (*spec == '|')
        return 1;               /* alternative separator? positive match */

    if (!*spec)
        return 1;               /* end of spec? positive match */

    if (*spec == '\\')
        spec++;                 /* escaped char */

    if (*spec == *str) {
        spec++;                 /* matched 1 char */
        str++;
        goto again;
    }

    /* not matched; are there any alternatives? */
    while (*spec) {
        if (*spec == '|')
            return xs_match(o_str, spec + 1);   /* try next alternative */

        if (*spec == '\\')
            spec++;             /* escaped char */
        spec++;
    }

    return 0;
}

#endif /* XS_IMPLEMENTATION */

#endif /* XS_MATCH_H */