use crate::syntax::{CaseSensitivity, CodePoint, PatternSegment, Segment, Token};
#[cfg(test)]
mod tests;
pub(crate) fn fold(cp: CodePoint) -> CodePoint {
if cp <= 0xFFFF {
let unit = cp as u16;
match super::upcase::UPCASE.binary_search_by_key(&unit, |&(from, _)| from) {
Ok(i) => super::upcase::UPCASE[i].1 as CodePoint,
Err(_) => cp,
}
} else {
cp
}
}
fn cp_eq(a: CodePoint, b: CodePoint, cs: CaseSensitivity) -> bool {
match cs {
CaseSensitivity::Sensitive => a == b,
CaseSensitivity::Insensitive => fold(a) == fold(b),
}
}
pub fn match_segment(tokens: &[Token], input: &[CodePoint], cs: CaseSensitivity) -> bool {
match tokens.split_first() {
None => input.is_empty(),
Some((tok, rest)) => match tok {
Token::Literal(cp) => {
!input.is_empty()
&& cp_eq(*cp, input[0], cs)
&& match_segment(rest, &input[1..], cs)
}
Token::Any => !input.is_empty() && match_segment(rest, &input[1..], cs),
Token::Star => (0..=input.len()).any(|k| match_segment(rest, &input[k..], cs)),
Token::Alt(arms) => arms.iter().any(|arm| match_arm_then(arm, rest, input, cs)),
},
}
}
fn match_arm_then(arm: &Segment, rest: &[Token], input: &[CodePoint], cs: CaseSensitivity) -> bool {
(0..=input.len())
.any(|k| match_segment(arm, &input[..k], cs) && match_segment(rest, &input[k..], cs))
}
pub fn match_path(pattern: &[PatternSegment], path: &[&[CodePoint]], cs: CaseSensitivity) -> bool {
match pattern.split_first() {
None => path.is_empty(),
Some((PatternSegment::DoubleStar, rest)) => {
(0..=path.len()).any(|k| match_path(rest, &path[k..], cs))
}
Some((PatternSegment::Match(seg), rest)) => {
!path.is_empty() && match_segment(seg, path[0], cs) && match_path(rest, &path[1..], cs)
}
}
}