1use std::fmt;
21
22use serde::{Deserialize, Serialize};
23
24#[derive(Debug, thiserror::Error, PartialEq, Eq)]
25pub enum SlotPathError {
26 #[error("path must start with `$`")]
27 MissingRoot,
28
29 #[error("path must address at least one field, e.g. `$.token`")]
30 Empty,
31
32 #[error("empty field name — `..` and a trailing `.` are not valid")]
33 EmptyName,
34
35 #[error("unterminated `[` — expected a decimal index like `[0]`")]
36 UnterminatedIndex,
37
38 #[error("`[{0}]` is not a decimal index; wildcards and filters are not supported")]
39 NonNumericIndex(String),
40
41 #[error("unexpected `{0}` — expected `.` or `[`")]
42 UnexpectedChar(char),
43}
44
45#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
46pub enum SlotSegment {
47 Field(String),
48 Index(usize),
49}
50
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53pub struct SlotPath {
54 segments: Vec<SlotSegment>,
55 source: String,
56}
57
58impl SlotPath {
59 pub fn parse(input: &str) -> Result<Self, SlotPathError> {
60 let mut chars = input.chars().peekable();
61 if chars.next() != Some('$') {
62 return Err(SlotPathError::MissingRoot);
63 }
64
65 let mut segments = Vec::new();
66 while let Some(&c) = chars.peek() {
67 match c {
68 '.' => {
69 chars.next();
70 let mut name = String::new();
71 while let Some(&c) = chars.peek() {
72 if c == '.' || c == '[' {
73 break;
74 }
75 name.push(c);
76 chars.next();
77 }
78 if name.is_empty() {
79 return Err(SlotPathError::EmptyName);
80 }
81 segments.push(SlotSegment::Field(name));
82 }
83 '[' => {
84 chars.next();
85 let mut raw = String::new();
86 let mut closed = false;
87 for c in chars.by_ref() {
88 if c == ']' {
89 closed = true;
90 break;
91 }
92 raw.push(c);
93 }
94 if !closed {
95 return Err(SlotPathError::UnterminatedIndex);
96 }
97 let index = raw
98 .parse::<usize>()
99 .map_err(|_| SlotPathError::NonNumericIndex(raw))?;
100 segments.push(SlotSegment::Index(index));
101 }
102 other => return Err(SlotPathError::UnexpectedChar(other)),
103 }
104 }
105
106 if segments.is_empty() {
107 return Err(SlotPathError::Empty);
108 }
109 Ok(Self {
110 segments,
111 source: input.to_string(),
112 })
113 }
114
115 pub fn segments(&self) -> &[SlotSegment] {
116 &self.segments
117 }
118
119 pub fn as_str(&self) -> &str {
120 &self.source
121 }
122}
123
124impl fmt::Display for SlotPath {
125 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126 f.write_str(&self.source)
127 }
128}
129
130#[cfg(test)]
131mod tests {
132 use super::*;
133
134 #[test]
135 fn parses_field_and_index_segments() {
136 let path = SlotPath::parse("$.items[0].secret").unwrap();
137 assert_eq!(
138 path.segments(),
139 &[
140 SlotSegment::Field("items".into()),
141 SlotSegment::Index(0),
142 SlotSegment::Field("secret".into()),
143 ]
144 );
145 assert_eq!(path.as_str(), "$.items[0].secret");
146 }
147
148 #[test]
149 fn parses_the_documented_example() {
150 assert_eq!(
151 SlotPath::parse("$.data.token").unwrap().segments(),
152 &[
153 SlotSegment::Field("data".into()),
154 SlotSegment::Field("token".into())
155 ]
156 );
157 }
158
159 #[test]
162 fn rejects_jsonpath_syntax_it_does_not_implement() {
163 for input in ["$..token", "$.items[*]", "$.items[?(@.x)]", "$.a[-1]"] {
164 assert!(
165 SlotPath::parse(input).is_err(),
166 "{input} parsed but is not supported"
167 );
168 }
169 }
170
171 #[test]
172 fn rejects_structurally_broken_paths() {
173 assert_eq!(
174 SlotPath::parse("data.token"),
175 Err(SlotPathError::MissingRoot)
176 );
177 assert_eq!(SlotPath::parse("$"), Err(SlotPathError::Empty));
178 assert_eq!(SlotPath::parse("$.a."), Err(SlotPathError::EmptyName));
179 assert_eq!(SlotPath::parse("$..a"), Err(SlotPathError::EmptyName));
180 assert_eq!(
181 SlotPath::parse("$.a[0"),
182 Err(SlotPathError::UnterminatedIndex)
183 );
184 assert_eq!(
185 SlotPath::parse("$a"),
186 Err(SlotPathError::UnexpectedChar('a'))
187 );
188 }
189
190 #[test]
191 fn field_names_may_contain_characters_that_need_no_escaping() {
192 let path = SlotPath::parse("$.access-token").unwrap();
193 assert_eq!(
194 path.segments(),
195 &[SlotSegment::Field("access-token".into())]
196 );
197 }
198}