2 * Copyright (C) 2018, 2019 "IoT.bzh"
3 * Author: José Bollo <jose.bollo@iot.bzh>
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
22 #include "globmatch.h"
25 * Matches whether the string 'str' matches the pattern 'pat'
26 * and returns its matching score.
28 * @param pat the glob pattern
29 * @param str the string to match
30 * @return 0 if no match or number representing the matching score
32 static unsigned match(const char *pat, const char *str, int flags)
38 /* scan the prefix without glob */
40 while ((c = *pat++) != GLOB) {
42 eq = (flags & FNM_CASEFOLD) ? (tolower(c) == tolower(x)) : (c == x);
44 return 0; /* no match */
46 return r; /* match up to end */
53 /* not followed by pattern */
54 if (flags & FNM_PATHNAME) {
62 /* evaluate the best score for following pattern */
66 eq = (flags & FNM_CASEFOLD) ? (tolower(c) == tolower(x)) : (c == x);
68 /* first char matches, check remaining string */
69 rr = match(pat, str, flags);
72 } else if ((flags & FNM_PATHNAME) && x == '/')
76 /* best score or not match if rs == 0 */
77 return rs ? rs + r : 0;
81 * Matches whether the string 'str' matches the pattern 'pat'
82 * and returns its matching score.
84 * @param pat the glob pattern
85 * @param str the string to match
86 * @return 0 if no match or number representing the matching score
88 unsigned globmatch(const char *pat, const char *str)
90 return match(pat, str, 0);
94 * Matches whether the string 'str' matches the pattern 'pat'
95 * and returns its matching score.
97 * @param pat the glob pattern
98 * @param str the string to match
99 * @return 0 if no match or number representing the matching score
101 unsigned globmatchi(const char *pat, const char *str)
103 return match(pat, str, FNM_CASEFOLD);
107 int fnmatch(const char *pattern, const char *string, int flags)
109 return !match(pattern, string, flags);