1pub fn matches(pattern: &str, path: &str) -> bool {
7 go(pattern.as_bytes(), path.as_bytes())
8}
9
10fn go(pat: &[u8], text: &[u8]) -> bool {
11 match pat.first() {
12 None => text.is_empty(),
13 Some(b'*') if pat.get(1) == Some(&b'*') => {
14 let rest = pat[2..].strip_prefix(b"/").unwrap_or(&pat[2..]);
15 (0..=text.len()).any(|i| go(rest, &text[i..]))
16 }
17 Some(b'*') => {
18 let rest = &pat[1..];
19 let end = text.iter().position(|&c| c == b'/').unwrap_or(text.len());
20 (0..=end).any(|i| go(rest, &text[i..]))
21 }
22 Some(b'?') => text.first().is_some_and(|&c| c != b'/') && go(&pat[1..], &text[1..]),
23 Some(&c) => text.first() == Some(&c) && go(&pat[1..], &text[1..]),
24 }
25}
26
27#[cfg(test)]
28mod tests {
29 use super::matches;
30
31 #[test]
32 fn star_stays_inside_a_segment() {
33 assert!(matches("docs/*.md", "docs/gating.md"));
34 assert!(!matches("docs/*.md", "docs/sub/gating.md"));
35 }
36
37 #[test]
38 fn double_star_crosses_segments_and_matches_none() {
39 assert!(matches("docs/**", "docs/a/b.md"));
40 assert!(matches("**/*.md", "README.md"));
41 assert!(matches("**/*.md", "a/b/README.md"));
42 assert!(!matches("docs/**", "src/a.md"));
43 }
44
45 #[test]
46 fn question_mark_is_one_non_separator_char() {
47 assert!(matches("a?c", "abc"));
48 assert!(!matches("a?c", "a/c"));
49 }
50
51 #[test]
52 fn a_literal_must_match_whole() {
53 assert!(matches("LICENSE", "LICENSE"));
54 assert!(!matches("LICENSE", "LICENSE.md"));
55 }
56}