use super::*;
pub(crate) fn expand_braces(pattern: &str) -> Result<Vec<String>, GlobError> {
let bytes: &[u8] = pattern.as_bytes();
let len: usize = bytes.len();
let mut open_idx: Option<usize> = None;
let mut close_idx: Option<usize> = None;
let mut depth: usize = 0;
let mut in_class: bool = false;
let mut idx: usize = 0;
while idx < len {
let b: u8 = bytes[idx];
if b == b'\\' {
if idx + 1 >= len {
return Err(GlobError::TrailingEscape);
}
let next_len: usize = pattern[idx + 1..].chars().next().map_or(1, char::len_utf8);
idx += 1 + next_len;
continue;
}
if in_class {
if b == b']' {
in_class = false;
}
idx += 1;
continue;
}
if b == b'[' {
in_class = true;
idx += 1;
continue;
}
if b == b'{' {
if depth == 0 {
open_idx = Some(idx);
}
depth += 1;
} else if b == b'}' {
if depth == 0 {
return Err(GlobError::UnmatchedCloseBrace);
}
depth -= 1;
if depth == 0 {
close_idx = Some(idx);
break;
}
}
idx += 1;
}
if in_class {
return Err(GlobError::UnclosedClass);
}
if depth != 0 {
return Err(GlobError::UnclosedBrace);
}
let Some(start) = open_idx else {
return Ok(vec![pattern.to_owned()]);
};
let Some(end) = close_idx else {
return Err(GlobError::UnclosedBrace);
};
let prefix: &str = &pattern[..start];
let suffix: &str = &pattern[end + 1..];
let mut alternatives: Vec<&str> = Vec::new();
let mut alt_start: usize = start + 1;
let mut nested_depth: usize = 0;
let mut inner_class: bool = false;
let mut pos: usize = start + 1;
while pos < end {
let b: u8 = bytes[pos];
if b == b'\\' {
if pos + 1 >= end {
return Err(GlobError::TrailingEscape);
}
let next_len: usize = pattern[pos + 1..end]
.chars()
.next()
.map_or(1, char::len_utf8);
pos += 1 + next_len;
continue;
}
if inner_class {
if b == b']' {
inner_class = false;
}
pos += 1;
continue;
}
if b == b'[' {
inner_class = true;
} else if b == b'{' {
nested_depth += 1;
} else if b == b'}' {
nested_depth = nested_depth.saturating_sub(1);
} else if b == b',' && nested_depth == 0 {
alternatives.push(&pattern[alt_start..pos]);
alt_start = pos + 1;
}
pos += 1;
}
alternatives.push(&pattern[alt_start..end]);
let mut expanded: Vec<String> = Vec::with_capacity(alternatives.len());
let mut combined: String = String::new();
for alt in alternatives {
combined.clear();
combined.reserve(prefix.len() + alt.len() + suffix.len());
combined.push_str(prefix);
combined.push_str(alt);
combined.push_str(suffix);
let sub: Vec<String> = expand_braces(&combined)?;
if expanded.len().saturating_add(sub.len()) > MAX_BRACE_BRANCHES {
return Err(GlobError::ExpansionLimitExceeded);
}
expanded.extend(sub);
}
Ok(expanded)
}
fn build_char_class(negated: bool, ranges: &[(char, char)]) -> CharClass {
let mut ascii_lo: u64 = 0;
let mut ascii_hi: u64 = 0;
let mut non_ascii: Vec<(char, char)> = Vec::new();
for &(lo, hi) in ranges {
let lo_u32: u32 = lo as u32;
let hi_u32: u32 = hi as u32;
if lo_u32 < 128 {
let asc_end: u32 = hi_u32.min(127);
let mut c: u32 = lo_u32;
while c <= asc_end {
if c < 64 {
ascii_lo |= 1u64 << c;
} else {
ascii_hi |= 1u64 << (c - 64);
}
c += 1;
}
}
if hi_u32 >= 128 {
let non_lo: char = if lo_u32 < 128 { char::from(128u8) } else { lo };
non_ascii.push((non_lo, hi));
}
}
if negated {
ascii_lo = !ascii_lo;
ascii_hi = !ascii_hi;
}
CharClass {
ascii_lo,
ascii_hi,
negated,
non_ascii,
}
}
#[inline]
fn collect_literals(tokens: &[GlobToken]) -> Option<String> {
let mut byte_len: usize = 0;
for tok in tokens {
match tok {
GlobToken::Literal(c) => byte_len += c.len_utf8(),
_ => return None,
}
}
let mut out: String = String::with_capacity(byte_len);
for tok in tokens {
if let GlobToken::Literal(c) = tok {
out.push(*c);
}
}
Some(out)
}
pub(crate) fn compile_branch(pattern: &str, path_aware: bool) -> Result<CompiledBranch, GlobError> {
let bytes: &[u8] = pattern.as_bytes();
let len: usize = bytes.len();
let mut tokens: Vec<GlobToken> = Vec::with_capacity(len);
let mut classes: Vec<CharClass> = Vec::new();
let mut idx: usize = 0;
while idx < len {
let ch: char = if bytes[idx] < 128 {
char::from(bytes[idx])
} else {
pattern[idx..].chars().next().unwrap_or_default()
};
let ch_len: usize = ch.len_utf8();
match ch {
'\\' => {
idx += 1;
if idx >= len {
return Err(GlobError::TrailingEscape);
}
let esc: char = if bytes[idx] < 128 {
char::from(bytes[idx])
} else {
pattern[idx..].chars().next().unwrap_or_default()
};
tokens.push(GlobToken::Literal(esc));
idx += esc.len_utf8();
}
'?' => {
tokens.push(GlobToken::AnyChar);
idx += 1;
}
'*' => {
let mut is_double: bool = false;
while idx + 1 < len && bytes[idx + 1] == b'*' {
is_double = true;
idx += 1;
}
let tok: GlobToken = if is_double || !path_aware {
GlobToken::DoubleStar
} else {
GlobToken::Star
};
if tokens.last() != Some(&tok) {
tokens.push(tok);
}
idx += 1;
}
'[' => {
idx += 1;
if idx >= len {
return Err(GlobError::UnclosedClass);
}
let negated: bool = bytes[idx] == b'!' || bytes[idx] == b'^';
if negated {
idx += 1;
}
let mut ranges: Vec<(char, char)> = Vec::new();
let mut closed: bool = false;
let mut first_in_class: bool = true;
while idx < len {
if bytes[idx] == b']' && !first_in_class {
closed = true;
idx += 1;
break;
}
first_in_class = false;
let start_ch: char = if bytes[idx] == b'\\' {
idx += 1;
if idx >= len {
return Err(GlobError::TrailingEscape);
}
if bytes[idx] < 128 {
char::from(bytes[idx])
} else {
pattern[idx..].chars().next().unwrap_or_default()
}
} else if bytes[idx] < 128 {
char::from(bytes[idx])
} else {
pattern[idx..].chars().next().unwrap_or_default()
};
idx += start_ch.len_utf8();
if idx + 1 < len && bytes[idx] == b'-' && bytes[idx + 1] != b']' {
idx += 1;
let end_ch: char = if bytes[idx] == b'\\' {
idx += 1;
if idx >= len {
return Err(GlobError::TrailingEscape);
}
if bytes[idx] < 128 {
char::from(bytes[idx])
} else {
pattern[idx..].chars().next().unwrap_or_default()
}
} else if bytes[idx] < 128 {
char::from(bytes[idx])
} else {
pattern[idx..].chars().next().unwrap_or_default()
};
if start_ch > end_ch {
return Err(GlobError::InvalidRange);
}
ranges.push((start_ch, end_ch));
idx += end_ch.len_utf8();
} else {
ranges.push((start_ch, start_ch));
}
}
if !closed {
return Err(GlobError::UnclosedClass);
}
let cls_idx: u16 = classes.len() as u16;
classes.push(build_char_class(negated, &ranges));
tokens.push(GlobToken::Class(cls_idx));
}
other => {
tokens.push(GlobToken::Literal(other));
idx += ch_len;
}
}
}
if let Some(exact) = collect_literals(&tokens) {
return Ok(CompiledBranch::Exact(exact));
}
if let Some((last, init)) = tokens.split_last()
&& let Some(prefix) = collect_literals(init)
{
match last {
GlobToken::DoubleStar => return Ok(CompiledBranch::Prefix(prefix)),
GlobToken::Star => return Ok(CompiledBranch::StarPrefix(prefix)),
_ => {}
}
}
if let Some((first, tail)) = tokens.split_first()
&& let Some(suffix) = collect_literals(tail)
{
match first {
GlobToken::DoubleStar => return Ok(CompiledBranch::Suffix(suffix)),
GlobToken::Star => return Ok(CompiledBranch::StarSuffix(suffix)),
_ => {}
}
}
if tokens.len() >= 3
&& tokens[0] == GlobToken::DoubleStar
&& tokens[tokens.len() - 1] == GlobToken::DoubleStar
&& let Some(mid) = collect_literals(&tokens[1..tokens.len() - 1])
{
return Ok(CompiledBranch::Contains(mid));
}
if tokens.len() >= 3
&& tokens[0] == GlobToken::DoubleStar
&& tokens[1] == GlobToken::Literal(PATH_SEP)
&& tokens[2] == GlobToken::Star
&& let Some(suffix) = collect_literals(&tokens[3..])
&& !suffix.as_bytes().contains(&PATH_SEP_BYTE)
{
return Ok(CompiledBranch::DoubleStarSlashStarSuffix(suffix));
}
let mut wild_pos: Option<usize> = None;
let mut single_wild: bool = true;
for (i, tok) in tokens.iter().enumerate() {
match tok {
GlobToken::Literal(_) => {}
GlobToken::Star | GlobToken::DoubleStar => {
if wild_pos.is_some() {
single_wild = false;
break;
}
wild_pos = Some(i);
}
_ => {
single_wild = false;
break;
}
}
}
if single_wild
&& let Some(pos) = wild_pos
&& pos > 0
&& pos + 1 < tokens.len()
&& let Some(prefix) = collect_literals(&tokens[..pos])
&& let Some(suffix) = collect_literals(&tokens[pos + 1..])
{
return match tokens[pos] {
GlobToken::DoubleStar => Ok(CompiledBranch::PrefixDoubleStarSuffix { prefix, suffix }),
GlobToken::Star => Ok(CompiledBranch::PrefixStarSuffix { prefix, suffix }),
_ => Ok(CompiledBranch::Tokens { tokens, classes }),
};
}
Ok(CompiledBranch::Tokens { tokens, classes })
}
#[inline]
pub(crate) fn match_branch(branch: &CompiledBranch, candidate: &str, path_aware: bool) -> bool {
match branch {
CompiledBranch::Exact(lit) => candidate == lit.as_str(),
CompiledBranch::Prefix(pre) => candidate.starts_with(pre.as_str()),
CompiledBranch::Suffix(suf) => candidate.ends_with(suf.as_str()),
CompiledBranch::StarPrefix(pre) => {
candidate.starts_with(pre.as_str())
&& !candidate.as_bytes()[pre.len()..].contains(&PATH_SEP_BYTE)
}
CompiledBranch::StarSuffix(suf) => {
candidate.ends_with(suf.as_str())
&& !candidate.as_bytes()[..candidate.len() - suf.len()].contains(&PATH_SEP_BYTE)
}
CompiledBranch::PrefixStarSuffix { prefix, suffix } => {
let min_len: usize = prefix.len() + suffix.len();
candidate.len() >= min_len
&& candidate.starts_with(prefix.as_str())
&& candidate.ends_with(suffix.as_str())
&& !candidate.as_bytes()[prefix.len()..candidate.len() - suffix.len()]
.contains(&PATH_SEP_BYTE)
}
CompiledBranch::PrefixDoubleStarSuffix { prefix, suffix } => {
candidate.len() >= prefix.len() + suffix.len()
&& candidate.starts_with(prefix.as_str())
&& candidate.ends_with(suffix.as_str())
}
CompiledBranch::Contains(sub) => candidate.contains(sub.as_str()),
CompiledBranch::DoubleStarSlashStarSuffix(suf) => {
candidate.ends_with(suf.as_str())
&& candidate.as_bytes()[..candidate.len() - suf.len()].contains(&PATH_SEP_BYTE)
}
CompiledBranch::Tokens { tokens, classes } => {
match_tokens(tokens, classes, candidate, path_aware)
}
}
}
#[inline]
pub(crate) fn match_tokens(
tokens: &[GlobToken],
classes: &[CharClass],
text: &str,
path_aware: bool,
) -> bool {
if text.is_ascii() {
return match_tokens_ascii(tokens, classes, text.as_bytes(), path_aware);
}
match_tokens_utf8(tokens, classes, text, path_aware)
}
#[inline(always)]
fn match_class_ascii(cls: &CharClass, b: u8) -> bool {
let word: u64 = if b < 64 { cls.ascii_lo } else { cls.ascii_hi };
((word >> (b & 63)) & 1) != 0
}
#[inline(always)]
fn match_class_char(cls: &CharClass, ch: char) -> bool {
let code: u32 = ch as u32;
if code < 128 {
return match_class_ascii(cls, code as u8);
}
let in_set: bool = cls
.non_ascii
.iter()
.any(|(lo, hi): &(char, char)| ch >= *lo && ch <= *hi);
in_set != cls.negated
}
fn match_tokens_ascii(
tokens: &[GlobToken],
classes: &[CharClass],
bytes: &[u8],
path_aware: bool,
) -> bool {
let tlen: usize = tokens.len();
let blen: usize = bytes.len();
let mut ti: usize = 0;
let mut bi: usize = 0;
let mut star_ti: Option<usize> = None;
let mut star_bi: usize = 0;
let mut star_is_double: bool = false;
let mut dstar_ti: Option<usize> = None;
let mut dstar_bi: usize = 0;
while bi < blen {
let byte: u8 = bytes[bi];
if ti < tlen {
match tokens[ti] {
GlobToken::DoubleStar => {
dstar_ti = Some(ti);
dstar_bi = bi;
star_ti = None;
ti += 1;
continue;
}
GlobToken::Star => {
star_ti = Some(ti);
star_bi = bi;
star_is_double = !path_aware;
ti += 1;
continue;
}
GlobToken::AnyChar if !path_aware || byte != PATH_SEP_BYTE => {
ti += 1;
bi += 1;
continue;
}
GlobToken::Literal(expected) if expected as u32 == u32::from(byte) => {
ti += 1;
bi += 1;
continue;
}
GlobToken::Class(cls_idx)
if (!path_aware || byte != PATH_SEP_BYTE)
&& match_class_ascii(&classes[cls_idx as usize], byte) =>
{
ti += 1;
bi += 1;
continue;
}
_ => {}
}
}
if let Some(s_ti) = star_ti
&& (star_is_double || bytes[star_bi] != PATH_SEP_BYTE)
{
star_bi += 1;
bi = star_bi;
ti = s_ti + 1;
continue;
}
if let Some(ds_ti) = dstar_ti {
dstar_bi += 1;
bi = dstar_bi;
ti = ds_ti + 1;
star_ti = None;
continue;
}
return false;
}
while ti < tlen && matches!(tokens[ti], GlobToken::Star | GlobToken::DoubleStar) {
ti += 1;
}
ti == tlen
}
fn match_tokens_utf8(
tokens: &[GlobToken],
classes: &[CharClass],
text: &str,
path_aware: bool,
) -> bool {
let tlen: usize = tokens.len();
let blen: usize = text.len();
let bytes: &[u8] = text.as_bytes();
let mut ti: usize = 0;
let mut bi: usize = 0;
let mut star_ti: Option<usize> = None;
let mut star_bi: usize = 0;
let mut star_is_double: bool = false;
let mut dstar_ti: Option<usize> = None;
let mut dstar_bi: usize = 0;
while bi < blen {
let ch: char = if bytes[bi] < 128 {
char::from(bytes[bi])
} else {
text[bi..].chars().next().unwrap_or_default()
};
let ch_len: usize = ch.len_utf8();
if ti < tlen {
match tokens[ti] {
GlobToken::DoubleStar => {
dstar_ti = Some(ti);
dstar_bi = bi;
star_ti = None;
ti += 1;
continue;
}
GlobToken::Star => {
star_ti = Some(ti);
star_bi = bi;
star_is_double = !path_aware;
ti += 1;
continue;
}
GlobToken::AnyChar if !path_aware || ch != PATH_SEP => {
ti += 1;
bi += ch_len;
continue;
}
GlobToken::Literal(expected) if expected == ch => {
ti += 1;
bi += ch_len;
continue;
}
GlobToken::Class(cls_idx)
if (!path_aware || ch != PATH_SEP)
&& match_class_char(&classes[cls_idx as usize], ch) =>
{
ti += 1;
bi += ch_len;
continue;
}
_ => {}
}
}
if let Some(s_ti) = star_ti
&& (star_is_double || bytes[star_bi] != PATH_SEP_BYTE)
{
let step: usize = if bytes[star_bi] < 128 {
1
} else {
text[star_bi..].chars().next().map_or(1, char::len_utf8)
};
star_bi += step;
bi = star_bi;
ti = s_ti + 1;
continue;
}
if let Some(ds_ti) = dstar_ti {
let step: usize = if bytes[dstar_bi] < 128 {
1
} else {
text[dstar_bi..].chars().next().map_or(1, char::len_utf8)
};
dstar_bi += step;
bi = dstar_bi;
ti = ds_ti + 1;
star_ti = None;
continue;
}
return false;
}
while ti < tlen && matches!(tokens[ti], GlobToken::Star | GlobToken::DoubleStar) {
ti += 1;
}
ti == tlen
}