shine_gltf/
path.rs

1use std::fmt;
2
3/// An immutable JSON source path.
4#[derive(Default, Clone, Debug, PartialEq)]
5pub struct Path(pub String);
6
7impl Path {
8    /// Creates an empty JSON source path.
9    ///
10    /// # Examples
11    ///
12    /// Basic usage
13    ///
14    /// ```rust
15    /// # use shine_gltf::Path;
16    /// let path = Path::new();
17    /// assert_eq!("", path.as_str());
18    /// ```
19    pub fn new() -> Self {
20        Path(String::new())
21    }
22
23    /// Returns a new path ending with the given field.
24    ///
25    /// # Examples
26    ///
27    /// Basic usage
28    ///
29    /// ```rust
30    /// # use shine_gltf::Path;
31    /// let path = Path::new().field("foo");
32    /// assert_eq!("foo", path.as_str());
33    /// assert_eq!("foo.bar", path.field("bar").as_str());
34    /// ```
35    pub fn field(&self, name: &str) -> Self {
36        if self.0.is_empty() {
37            Path(name.to_string())
38        } else {
39            Path(format!("{}.{}", self.0, name))
40        }
41    }
42
43    /// Returns a new path ending with the given array index.
44    ///
45    /// # Examples
46    ///
47    /// Basic usage
48    ///
49    /// ```rust
50    /// # use shine_gltf::Path;
51    /// let path = Path::new().field("foo");
52    /// assert_eq!("foo[123]", path.index(123).as_str());
53    /// ```
54    pub fn index(&self, index: usize) -> Self {
55        Path(format!("{}[{}]", self.0, index))
56    }
57
58    /// Returns a new path ending with the given object key.
59    ///
60    /// # Examples
61    ///
62    /// Basic usage
63    ///
64    /// ```rust
65    /// # use shine_gltf::Path;
66    /// let path = Path::new().field("foo");
67    /// assert_eq!("foo[\"bar\"]", path.key("bar").as_str());
68    /// ```
69    pub fn key(&self, key: &str) -> Self {
70        Path(format!("{}[\"{}\"]", self.0, key))
71    }
72
73    /// Returns a view into the internal representation.
74    pub fn as_str(&self) -> &str {
75        &self.0
76    }
77}
78
79impl fmt::Display for Path {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        write!(f, "{}", self.0)
82    }
83}