1use std::fmt::{self, Write as _};
4
5use serde::{Deserialize, Deserializer, Serialize, Serializer};
6
7#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
9pub enum Segment {
10 Key(String),
12 Index(usize),
14}
15
16#[derive(Clone, Debug, PartialEq, Eq, Hash)]
21pub struct Path {
22 root: String,
23 segments: Vec<Segment>,
24}
25
26#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct PathError {
29 pub offset: usize,
31 pub message: &'static str,
33}
34
35impl fmt::Display for PathError {
36 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
37 write!(formatter, "{} at byte {}", self.message, self.offset)
38 }
39}
40
41impl std::error::Error for PathError {}
42
43impl Path {
44 #[must_use]
46 pub fn root(name: impl Into<String>) -> Self {
47 Self {
48 root: name.into(),
49 segments: Vec::new(),
50 }
51 }
52
53 #[must_use]
55 pub fn key(&self, key: impl Into<String>) -> Self {
56 let mut path = self.clone();
57 path.segments.push(Segment::Key(key.into()));
58 path
59 }
60
61 #[must_use]
63 pub fn index(&self, index: usize) -> Self {
64 let mut path = self.clone();
65 path.segments.push(Segment::Index(index));
66 path
67 }
68
69 pub fn push(&mut self, segment: Segment) {
71 self.segments.push(segment);
72 }
73
74 pub fn pop(&mut self) -> Option<Segment> {
76 self.segments.pop()
77 }
78
79 #[must_use]
81 pub fn join(&self, segments: impl IntoIterator<Item = Segment>) -> Self {
82 let mut path = self.clone();
83 path.segments.extend(segments);
84 path
85 }
86
87 #[must_use]
89 pub fn root_name(&self) -> &str {
90 &self.root
91 }
92
93 #[must_use]
95 pub fn segments(&self) -> &[Segment] {
96 &self.segments
97 }
98
99 #[must_use]
101 pub fn last(&self) -> Option<&Segment> {
102 self.segments.last()
103 }
104
105 #[must_use]
107 pub fn last_key(&self) -> Option<&str> {
108 match self.segments.last() {
109 Some(Segment::Key(key)) => Some(key),
110 _ => None,
111 }
112 }
113
114 #[must_use]
116 pub fn parent(&self) -> Option<Self> {
117 let mut path = self.clone();
118 path.segments.pop().map(|_| path)
119 }
120
121 #[must_use]
123 pub fn starts_with(&self, other: &Self) -> bool {
124 self.root == other.root && self.segments.starts_with(&other.segments)
125 }
126
127 #[must_use]
130 pub fn starred(&self) -> String {
131 let mut text = self.root.clone();
132 for segment in &self.segments {
133 match segment {
134 Segment::Key(key) => write_key(&mut text, key),
135 Segment::Index(_) => text.push_str("[*]"),
136 }
137 }
138 text
139 }
140
141 pub fn parse(text: &str) -> Result<Self, PathError> {
147 let bytes = text.as_bytes();
148 let mut at = 0;
149 let root = read_name(text, &mut at);
150 if root.is_empty() {
151 return Err(PathError {
152 offset: 0,
153 message: "a path starts with a name",
154 });
155 }
156 let mut path = Self::root(root);
157 path.segments = read_segments(text, bytes, &mut at)?;
158 Ok(path)
159 }
160
161 pub fn join_text(&self, relative: &str) -> Result<Self, PathError> {
167 if relative.is_empty() || relative == "." {
168 return Ok(self.clone());
169 }
170 let bytes = relative.as_bytes();
171 let mut at = 0;
172 let mut path = self.clone();
173 if !matches!(bytes[0], b'.' | b'[') {
174 let first = read_name(relative, &mut at);
175 if first.is_empty() {
176 return Err(PathError {
177 offset: 0,
178 message: "expected a key",
179 });
180 }
181 path.segments.push(Segment::Key(first.to_owned()));
182 }
183 path.segments
184 .extend(read_segments(relative, bytes, &mut at)?);
185 Ok(path)
186 }
187}
188
189fn read_name<'a>(text: &'a str, at: &mut usize) -> &'a str {
190 let start = *at;
191 let bytes = text.as_bytes();
192 while *at < bytes.len() && !matches!(bytes[*at], b'.' | b'[' | b']') {
193 *at += 1;
194 }
195 &text[start..*at]
196}
197
198fn read_segments(text: &str, bytes: &[u8], at: &mut usize) -> Result<Vec<Segment>, PathError> {
199 let mut segments = Vec::new();
200 while *at < bytes.len() {
201 match bytes[*at] {
202 b'.' => {
203 *at += 1;
204 let key = read_name(text, at);
205 if key.is_empty() {
206 return Err(PathError {
207 offset: *at,
208 message: "expected a key after `.`",
209 });
210 }
211 segments.push(Segment::Key(key.to_owned()));
212 }
213 b'[' => {
214 *at += 1;
215 if bytes.get(*at) == Some(&b'"') {
216 let (key, end) = read_quoted(text, *at)?;
217 *at = end;
218 segments.push(Segment::Key(key));
219 } else {
220 let start = *at;
221 while bytes.get(*at).is_some_and(u8::is_ascii_digit) {
222 *at += 1;
223 }
224 let index = text[start..*at].parse().map_err(|_| PathError {
225 offset: start,
226 message: "expected an index or a quoted key",
227 })?;
228 segments.push(Segment::Index(index));
229 }
230 if bytes.get(*at) != Some(&b']') {
231 return Err(PathError {
232 offset: *at,
233 message: "expected `]`",
234 });
235 }
236 *at += 1;
237 }
238 _ => {
239 return Err(PathError {
240 offset: *at,
241 message: "expected `.` or `[`",
242 });
243 }
244 }
245 }
246 Ok(segments)
247}
248
249fn read_quoted(text: &str, start: usize) -> Result<(String, usize), PathError> {
250 let mut key = String::new();
251 let mut chars = text[start + 1..].char_indices();
252 while let Some((offset, char)) = chars.next() {
253 match char {
254 '"' => return Ok((key, start + 1 + offset + 1)),
255 '\\' => match chars.next() {
256 Some((_, '"')) => key.push('"'),
257 Some((_, '\\')) => key.push('\\'),
258 Some((_, 'n')) => key.push('\n'),
259 Some((_, 't')) => key.push('\t'),
260 Some((_, 'r')) => key.push('\r'),
261 Some((offset, 'u')) => {
262 let begin = start + 1 + offset + 1;
263 let code = text
264 .get(begin..begin + 4)
265 .and_then(|hex| u32::from_str_radix(hex, 16).ok())
266 .and_then(char::from_u32)
267 .ok_or(PathError {
268 offset: begin,
269 message: "expected four hex digits",
270 })?;
271 key.push(code);
272 for _ in 0..4 {
273 chars.next();
274 }
275 }
276 _ => {
277 return Err(PathError {
278 offset: start + 1 + offset,
279 message: "unknown escape",
280 });
281 }
282 },
283 other => key.push(other),
284 }
285 }
286 Err(PathError {
287 offset: text.len(),
288 message: "unterminated quoted key",
289 })
290}
291
292fn plain_key(key: &str) -> bool {
293 !key.is_empty()
294 && !key.chars().any(|char| {
295 matches!(char, '.' | '[' | ']' | '"' | '\\')
296 || char.is_whitespace()
297 || char.is_control()
298 })
299}
300
301fn write_key(text: &mut String, key: &str) {
302 if plain_key(key) {
303 text.push('.');
304 text.push_str(key);
305 return;
306 }
307 text.push_str("[\"");
308 for char in key.chars() {
309 match char {
310 '"' => text.push_str("\\\""),
311 '\\' => text.push_str("\\\\"),
312 '\n' => text.push_str("\\n"),
313 '\t' => text.push_str("\\t"),
314 '\r' => text.push_str("\\r"),
315 char if char.is_control() => {
316 let _ = write!(text, "\\u{:04x}", u32::from(char));
317 }
318 char => text.push(char),
319 }
320 }
321 text.push_str("\"]");
322}
323
324impl fmt::Display for Path {
325 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
326 let mut text = self.root.clone();
327 for segment in &self.segments {
328 match segment {
329 Segment::Key(key) => write_key(&mut text, key),
330 Segment::Index(index) => {
331 let _ = write!(text, "[{index}]");
332 }
333 }
334 }
335 formatter.write_str(&text)
336 }
337}
338
339impl Serialize for Path {
340 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
341 serializer.collect_str(self)
342 }
343}
344
345impl<'de> Deserialize<'de> for Path {
346 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
347 let text = String::deserialize(deserializer)?;
348 Self::parse(&text).map_err(serde::de::Error::custom)
349 }
350}
351
352#[cfg(feature = "schema")]
353impl schemars::JsonSchema for Path {
354 fn schema_name() -> std::borrow::Cow<'static, str> {
355 "Path".into()
356 }
357
358 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
359 schemars::json_schema!({
360 "description": "A place in the document: a root name, then `.key`, `[\"quoted key\"]` and `[index]` steps.",
361 "type": "string"
362 })
363 }
364}
365
366#[cfg(test)]
367mod tests {
368 use super::*;
369
370 #[test]
371 fn writes_and_reads_back() {
372 let path = Path::root("project")
373 .key("timeline")
374 .key("tracks")
375 .index(0)
376 .key("a key")
377 .key("q\"uote");
378 let text = path.to_string();
379 assert_eq!(text, r#"project.timeline.tracks[0]["a key"]["q\"uote"]"#);
380 assert_eq!(Path::parse(&text).unwrap(), path);
381 }
382
383 #[test]
384 fn reads_the_forms_the_engine_writes() {
385 let path = Path::parse("spec.body.children[2].path").unwrap();
386 assert_eq!(path.root_name(), "spec");
387 assert_eq!(path.segments().len(), 4);
388 let base = Path::root("project").key("clips").index(1);
389 assert_eq!(
390 base.join_text("visual.opacity").unwrap().to_string(),
391 "project.clips[1].visual.opacity"
392 );
393 assert_eq!(
394 base.join_text("masks[0].feather").unwrap().to_string(),
395 "project.clips[1].masks[0].feather"
396 );
397 assert_eq!(
398 base.join_text("[3]").unwrap().to_string(),
399 "project.clips[1][3]"
400 );
401 assert_eq!(base.join_text(".").unwrap(), base);
402 }
403
404 #[test]
405 fn refuses_malformed_paths() {
406 for bad in ["", ".a", "a..b", "a[x]", "a[1", "a[\"b]", "a]"] {
407 assert!(Path::parse(bad).is_err(), "{bad}");
408 }
409 }
410
411 #[test]
412 fn starred_replaces_indexes() {
413 let path = Path::parse("project.tracks[3].clips[12].id").unwrap();
414 assert_eq!(path.starred(), "project.tracks[*].clips[*].id");
415 }
416
417 #[test]
418 fn parent_and_prefix() {
419 let path = Path::parse("a.b[1]").unwrap();
420 assert_eq!(path.parent().unwrap().to_string(), "a.b");
421 assert!(path.starts_with(&Path::parse("a.b").unwrap()));
422 assert!(!path.starts_with(&Path::parse("x.b").unwrap()));
423 assert!(Path::root("a").parent().is_none());
424 }
425}