use crate::error::Error;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PathSegment<'a> {
Key(&'a str),
Index(usize),
}
pub fn parse_path(s: &str) -> Vec<PathSegment<'_>> {
parse_path_inner(s, false).unwrap_or_default()
}
pub fn try_parse_path(s: &str) -> Result<Vec<PathSegment<'_>>, Error> {
parse_path_inner(s, true)
}
fn parse_path_inner(mut s: &str, strict: bool) -> Result<Vec<PathSegment<'_>>, Error> {
let mut segments = Vec::new();
while !s.is_empty() {
if s.starts_with('.') {
s = &s[1..];
continue;
}
if s.is_empty() {
break;
}
if s.starts_with('[') {
match s.find(']') {
Some(end_idx) => {
let idx_str = &s[1..end_idx];
if idx_str.is_empty() {
if strict {
return Err(Error::InvalidPath {
msg: "Empty array index brackets",
});
}
} else if !idx_str.bytes().all(|b| b.is_ascii_digit()) {
if strict {
return Err(Error::InvalidPath {
msg: "Non-numeric array index",
});
}
} else {
match idx_str.parse::<usize>() {
Ok(idx) => segments.push(PathSegment::Index(idx)),
Err(_) if strict => {
return Err(Error::InvalidPath {
msg: "Array index out of range for usize",
});
}
Err(_) => {}
}
}
s = &s[end_idx + 1..];
}
None => {
if strict {
return Err(Error::InvalidPath {
msg: "Unclosed array index bracket '['",
});
}
break;
}
}
} else {
let end_key = s.find(['.', '[']).unwrap_or(s.len());
let key = &s[..end_key];
if !key.is_empty() {
segments.push(PathSegment::Key(key));
}
s = &s[end_key..];
}
}
Ok(segments)
}