1use std::fmt;
4
5#[derive(Debug, Clone, PartialEq, Eq)]
7pub(crate) enum Part {
8 Field(String),
10 Index(usize),
12}
13
14#[derive(Debug, Clone, Default, PartialEq, Eq)]
16pub struct Path {
17 steps: Vec<Part>,
18}
19
20impl Path {
21 pub fn new() -> Self {
23 Self::default()
24 }
25
26 pub fn field(&self, name: &str) -> Self {
28 self.step(Part::Field(name.to_owned()))
29 }
30
31 pub fn index(&self, index: usize) -> Self {
33 self.step(Part::Index(index))
34 }
35
36 fn step(&self, part: Part) -> Self {
37 let mut steps = self.steps.clone();
38 steps.push(part);
39 Self { steps }
40 }
41
42 pub(crate) fn is_root(&self) -> bool {
44 self.steps.is_empty()
45 }
46}
47
48impl fmt::Display for Path {
49 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50 for (position, part) in self.steps.iter().enumerate() {
51 match part {
52 Part::Field(name) if plain_key(name) => {
53 if position > 0 {
54 f.write_str(".")?;
55 }
56 f.write_str(name)?;
57 }
58 Part::Field(name) => write!(f, "[{name:?}]")?,
59 Part::Index(index) => write!(f, "[{index}]")?,
60 }
61 }
62 Ok(())
63 }
64}
65
66fn plain_key(name: &str) -> bool {
68 !name.is_empty()
69 && !name.contains(['.', '[', ']', '"', '\''])
70 && !name.chars().any(char::is_whitespace)
71}