gltf_json/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 gltf_json::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 gltf_json::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 gltf_json::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 gltf_json::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 /// Provides a string value for a JSON path.
74 ///
75 /// # Examples
76 ///
77 /// Basic usage
78 ///
79 /// ```rust
80 /// # use gltf_json::Path;
81 /// let path = Path::new().field("foo").index(0).value_str("baz");
82 /// assert_eq!("foo[0] = \"baz\"", path.as_str());
83 /// ```
84 pub fn value_str(&self, value: &str) -> Self {
85 Path(format!("{} = \"{}\"", self.0, value))
86 }
87
88 /// Returns a view into the internal representation.
89 pub fn as_str(&self) -> &str {
90 &self.0
91 }
92}
93
94impl fmt::Display for Path {
95 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
96 write!(f, "{}", self.0)
97 }
98}