jellyschema/validator/
path.rs

1use std::fmt;
2
3#[derive(Debug, Clone)]
4pub enum Component {
5    Property(String),
6    Index(usize),
7}
8
9#[derive(Debug, Clone)]
10pub struct PathBuf {
11    components: Vec<Component>,
12}
13
14impl PathBuf {
15    pub fn new() -> PathBuf {
16        PathBuf { components: vec![] }
17    }
18
19    pub fn push_index(&mut self, index: usize) {
20        self.components.push(Component::Index(index));
21    }
22
23    pub fn push_property<S>(&mut self, property: S)
24    where
25        S: Into<String>,
26    {
27        self.components.push(Component::Property(property.into()))
28    }
29}
30
31impl fmt::Display for PathBuf {
32    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
33        for (idx, component) in self.components.iter().enumerate() {
34            match component {
35                Component::Property(s) if idx > 0 => write!(f, ".{}", s)?,
36                Component::Property(s) => write!(f, "{}", s)?,
37                Component::Index(idx) => write!(f, "[{}]", idx)?,
38            }
39        }
40        Ok(())
41    }
42}
43
44#[cfg(test)]
45mod tests {
46    use super::*;
47
48    #[test]
49    fn empty_buf() {
50        assert_eq!(&PathBuf::new().to_string(), "");
51    }
52}