use std::fmt::{self, Write as _};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Segment {
Key(String),
Index(usize),
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Path {
root: String,
segments: Vec<Segment>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PathError {
pub offset: usize,
pub message: &'static str,
}
impl fmt::Display for PathError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{} at byte {}", self.message, self.offset)
}
}
impl std::error::Error for PathError {}
impl Path {
#[must_use]
pub fn root(name: impl Into<String>) -> Self {
Self {
root: name.into(),
segments: Vec::new(),
}
}
#[must_use]
pub fn key(&self, key: impl Into<String>) -> Self {
let mut path = self.clone();
path.segments.push(Segment::Key(key.into()));
path
}
#[must_use]
pub fn index(&self, index: usize) -> Self {
let mut path = self.clone();
path.segments.push(Segment::Index(index));
path
}
pub fn push(&mut self, segment: Segment) {
self.segments.push(segment);
}
pub fn pop(&mut self) -> Option<Segment> {
self.segments.pop()
}
#[must_use]
pub fn join(&self, segments: impl IntoIterator<Item = Segment>) -> Self {
let mut path = self.clone();
path.segments.extend(segments);
path
}
#[must_use]
pub fn root_name(&self) -> &str {
&self.root
}
#[must_use]
pub fn segments(&self) -> &[Segment] {
&self.segments
}
#[must_use]
pub fn last(&self) -> Option<&Segment> {
self.segments.last()
}
#[must_use]
pub fn last_key(&self) -> Option<&str> {
match self.segments.last() {
Some(Segment::Key(key)) => Some(key),
_ => None,
}
}
#[must_use]
pub fn parent(&self) -> Option<Self> {
let mut path = self.clone();
path.segments.pop().map(|_| path)
}
#[must_use]
pub fn starts_with(&self, other: &Self) -> bool {
self.root == other.root && self.segments.starts_with(&other.segments)
}
#[must_use]
pub fn starred(&self) -> String {
let mut text = self.root.clone();
for segment in &self.segments {
match segment {
Segment::Key(key) => write_key(&mut text, key),
Segment::Index(_) => text.push_str("[*]"),
}
}
text
}
pub fn parse(text: &str) -> Result<Self, PathError> {
let bytes = text.as_bytes();
let mut at = 0;
let root = read_name(text, &mut at);
if root.is_empty() {
return Err(PathError {
offset: 0,
message: "a path starts with a name",
});
}
let mut path = Self::root(root);
path.segments = read_segments(text, bytes, &mut at)?;
Ok(path)
}
pub fn join_text(&self, relative: &str) -> Result<Self, PathError> {
if relative.is_empty() || relative == "." {
return Ok(self.clone());
}
let bytes = relative.as_bytes();
let mut at = 0;
let mut path = self.clone();
if !matches!(bytes[0], b'.' | b'[') {
let first = read_name(relative, &mut at);
if first.is_empty() {
return Err(PathError {
offset: 0,
message: "expected a key",
});
}
path.segments.push(Segment::Key(first.to_owned()));
}
path.segments
.extend(read_segments(relative, bytes, &mut at)?);
Ok(path)
}
}
fn read_name<'a>(text: &'a str, at: &mut usize) -> &'a str {
let start = *at;
let bytes = text.as_bytes();
while *at < bytes.len() && !matches!(bytes[*at], b'.' | b'[' | b']') {
*at += 1;
}
&text[start..*at]
}
fn read_segments(text: &str, bytes: &[u8], at: &mut usize) -> Result<Vec<Segment>, PathError> {
let mut segments = Vec::new();
while *at < bytes.len() {
match bytes[*at] {
b'.' => {
*at += 1;
let key = read_name(text, at);
if key.is_empty() {
return Err(PathError {
offset: *at,
message: "expected a key after `.`",
});
}
segments.push(Segment::Key(key.to_owned()));
}
b'[' => {
*at += 1;
if bytes.get(*at) == Some(&b'"') {
let (key, end) = read_quoted(text, *at)?;
*at = end;
segments.push(Segment::Key(key));
} else {
let start = *at;
while bytes.get(*at).is_some_and(u8::is_ascii_digit) {
*at += 1;
}
let index = text[start..*at].parse().map_err(|_| PathError {
offset: start,
message: "expected an index or a quoted key",
})?;
segments.push(Segment::Index(index));
}
if bytes.get(*at) != Some(&b']') {
return Err(PathError {
offset: *at,
message: "expected `]`",
});
}
*at += 1;
}
_ => {
return Err(PathError {
offset: *at,
message: "expected `.` or `[`",
});
}
}
}
Ok(segments)
}
fn read_quoted(text: &str, start: usize) -> Result<(String, usize), PathError> {
let mut key = String::new();
let mut chars = text[start + 1..].char_indices();
while let Some((offset, char)) = chars.next() {
match char {
'"' => return Ok((key, start + 1 + offset + 1)),
'\\' => match chars.next() {
Some((_, '"')) => key.push('"'),
Some((_, '\\')) => key.push('\\'),
Some((_, 'n')) => key.push('\n'),
Some((_, 't')) => key.push('\t'),
Some((_, 'r')) => key.push('\r'),
Some((offset, 'u')) => {
let begin = start + 1 + offset + 1;
let code = text
.get(begin..begin + 4)
.and_then(|hex| u32::from_str_radix(hex, 16).ok())
.and_then(char::from_u32)
.ok_or(PathError {
offset: begin,
message: "expected four hex digits",
})?;
key.push(code);
for _ in 0..4 {
chars.next();
}
}
_ => {
return Err(PathError {
offset: start + 1 + offset,
message: "unknown escape",
});
}
},
other => key.push(other),
}
}
Err(PathError {
offset: text.len(),
message: "unterminated quoted key",
})
}
fn plain_key(key: &str) -> bool {
!key.is_empty()
&& !key.chars().any(|char| {
matches!(char, '.' | '[' | ']' | '"' | '\\')
|| char.is_whitespace()
|| char.is_control()
})
}
fn write_key(text: &mut String, key: &str) {
if plain_key(key) {
text.push('.');
text.push_str(key);
return;
}
text.push_str("[\"");
for char in key.chars() {
match char {
'"' => text.push_str("\\\""),
'\\' => text.push_str("\\\\"),
'\n' => text.push_str("\\n"),
'\t' => text.push_str("\\t"),
'\r' => text.push_str("\\r"),
char if char.is_control() => {
let _ = write!(text, "\\u{:04x}", u32::from(char));
}
char => text.push(char),
}
}
text.push_str("\"]");
}
impl fmt::Display for Path {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut text = self.root.clone();
for segment in &self.segments {
match segment {
Segment::Key(key) => write_key(&mut text, key),
Segment::Index(index) => {
let _ = write!(text, "[{index}]");
}
}
}
formatter.write_str(&text)
}
}
impl Serialize for Path {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for Path {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let text = String::deserialize(deserializer)?;
Self::parse(&text).map_err(serde::de::Error::custom)
}
}
#[cfg(feature = "schema")]
impl schemars::JsonSchema for Path {
fn schema_name() -> std::borrow::Cow<'static, str> {
"Path".into()
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"description": "A place in the document: a root name, then `.key`, `[\"quoted key\"]` and `[index]` steps.",
"type": "string"
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn writes_and_reads_back() {
let path = Path::root("project")
.key("timeline")
.key("tracks")
.index(0)
.key("a key")
.key("q\"uote");
let text = path.to_string();
assert_eq!(text, r#"project.timeline.tracks[0]["a key"]["q\"uote"]"#);
assert_eq!(Path::parse(&text).unwrap(), path);
}
#[test]
fn reads_the_forms_the_engine_writes() {
let path = Path::parse("spec.body.children[2].path").unwrap();
assert_eq!(path.root_name(), "spec");
assert_eq!(path.segments().len(), 4);
let base = Path::root("project").key("clips").index(1);
assert_eq!(
base.join_text("visual.opacity").unwrap().to_string(),
"project.clips[1].visual.opacity"
);
assert_eq!(
base.join_text("masks[0].feather").unwrap().to_string(),
"project.clips[1].masks[0].feather"
);
assert_eq!(
base.join_text("[3]").unwrap().to_string(),
"project.clips[1][3]"
);
assert_eq!(base.join_text(".").unwrap(), base);
}
#[test]
fn refuses_malformed_paths() {
for bad in ["", ".a", "a..b", "a[x]", "a[1", "a[\"b]", "a]"] {
assert!(Path::parse(bad).is_err(), "{bad}");
}
}
#[test]
fn starred_replaces_indexes() {
let path = Path::parse("project.tracks[3].clips[12].id").unwrap();
assert_eq!(path.starred(), "project.tracks[*].clips[*].id");
}
#[test]
fn parent_and_prefix() {
let path = Path::parse("a.b[1]").unwrap();
assert_eq!(path.parent().unwrap().to_string(), "a.b");
assert!(path.starts_with(&Path::parse("a.b").unwrap()));
assert!(!path.starts_with(&Path::parse("x.b").unwrap()));
assert!(Path::root("a").parent().is_none());
}
}