#[must_use]
pub fn matches(pattern: &str, path: &str) -> bool {
let pat: Vec<&str> = pattern.split('/').collect();
let seg: Vec<&str> = path.split('/').collect();
segments(&pat, &seg)
}
fn segments(pat: &[&str], path: &[&str]) -> bool {
match pat.split_first() {
None => path.is_empty(),
Some((&"**", rest)) => any_split(rest, path),
Some((p, rest)) => path
.split_first()
.is_some_and(|(s, srest)| chars(p, s) && segments(rest, srest)),
}
}
fn any_split(rest: &[&str], path: &[&str]) -> bool {
(0..=path.len()).any(|i| segments(rest, path.get(i..).unwrap_or_default()))
}
fn chars(pattern: &str, seg: &str) -> bool {
let p: Vec<char> = pattern.chars().collect();
let s: Vec<char> = seg.chars().collect();
wild(&p, &s)
}
fn wild(p: &[char], s: &[char]) -> bool {
match p.split_first() {
None => s.is_empty(),
Some((&'*', rest)) => {
(0..=s.len()).any(|i| wild(rest, s.get(i..).unwrap_or_default()))
}
Some((&'?', rest)) => {
s.split_first().is_some_and(|(_, t)| wild(rest, t))
}
Some((c, rest)) => s
.split_first()
.is_some_and(|(f, t)| f == c && wild(rest, t)),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_literal_pattern_is_an_exact_path() {
assert!(matches("SPEC.md", "SPEC.md"));
assert!(!matches("SPEC.md", "src/SPEC.md"));
assert!(!matches("SPEC.md", "SPEC.md.bak"));
}
#[test]
fn a_star_never_crosses_a_separator() {
assert!(matches("src/*.rs", "src/a.rs"));
assert!(!matches("src/*.rs", "src/session/mod.rs"));
assert!(matches("src/*", "src/session"));
assert!(!matches("src/*", "src/session/mod.rs"));
}
#[test]
fn a_double_star_crosses_segments_including_zero() {
assert!(matches("src/**/*.rs", "src/session/mod.rs"));
assert!(matches("src/**/*.rs", "src/a.rs"), "zero segments");
assert!(matches("**", "anything/at/all"));
assert!(matches("**/*.rs", "a.rs"));
assert!(!matches("src/**/*.rs", "tests/a.rs"));
}
#[test]
fn a_question_mark_is_one_character() {
assert!(matches("a?.rs", "ab.rs"));
assert!(!matches("a?.rs", "abc.rs"), "one, not many");
assert!(!matches("a?.rs", "a.rs"), "one, not zero");
assert!(!matches("a?c", "a/c"), "never a separator");
}
#[test]
fn no_pattern_is_invalid() {
assert!(matches("a[b.rs", "a[b.rs"));
assert!(matches("", ""));
assert!(!matches("", "a"));
assert!(!matches("a", ""));
}
#[test]
fn stacked_wildcards_still_terminate() {
assert!(matches("**/**/*.rs", "a/b/c/d.rs"));
assert!(matches("*/*/*", "a/b/c"));
assert!(!matches("*/*/*", "a/b"));
}
}