Debian Codegraph @

src/paths.rs

raw symbols SCIP
1 //! Facilities for working with paths within schemas or validated instances.
2 use std::{borrow::Cow, fmt, sync::Arc};
3
4 use referencing::unescape_segment;
5
6 use crate::keywords::Keyword;
7
8 /// A location segment.
9 #[derive(Clone, Debug, Eq, PartialEq)]
10 pub enum LocationSegment<'a> {
11 /// Property name within a JSON object.
12 Property(Cow<'a, str>),
13 /// JSON Schema keyword.
14 Index(usize),
15 }
16
17 impl fmt::Display for LocationSegment<'_> {
18 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19 match self {
20 LocationSegment::Property(property) => f.write_str(property),
21 LocationSegment::Index(idx) => f.write_str(itoa::Buffer::new().format(*idx)),
22 }
23 }
24 }
25
26 /// A lazily constructed location within a JSON instance.
27 ///
28 /// [`LazyLocation`] builds a path incrementally during JSON Schema validation without allocating
29 /// memory until required by storing each segment on the stack.
30 #[derive(Debug, Clone, Eq, PartialEq)]
31 pub struct LazyLocation<'a, 'b> {
32 pub(crate) segment: LocationSegment<'a>,
33 pub(crate) parent: Option<&'b LazyLocation<'b, 'a>>,
34 }
35
36 impl Default for LazyLocation<'_, '_> {
37 fn default() -> Self {
38 LazyLocation::new()
39 }
40 }
41
42 impl<'a> LazyLocation<'a, '_> {
43 /// Create a root node of a JSON pointer.
44 #[must_use]
45 pub const fn new() -> Self {
46 LazyLocation {
47 // The value does not matter, it will never be used
48 segment: LocationSegment::Index(0),
49 parent: None,
50 }
51 }
52
53 /// Push a new segment to the JSON pointer.
54 #[inline]
55 #[must_use]
56 pub fn push(&'a self, segment: impl Into<LocationSegment<'a>>) -> Self {
57 LazyLocation {
58 segment: segment.into(),
59 parent: Some(self),
60 }
61 }
62 }
63
64 impl<'a> From<&'a LazyLocation<'_, '_>> for Location {
65 fn from(value: &'a LazyLocation<'_, '_>) -> Self {
66 let mut capacity = 0;
67 let mut string_capacity = 0;
68 let mut head = value;
69
70 while let Some(next) = head.parent {
71 capacity += 1;
72 string_capacity += match &head.segment {
73 LocationSegment::Property(property) => property.len() + 1,
74 LocationSegment::Index(idx) => idx.checked_ilog10().unwrap_or(0) as usize + 2,
75 };
76 head = next;
77 }
78
79 let mut buffer = String::with_capacity(string_capacity);
80
81 let mut segments = Vec::with_capacity(capacity);
82 head = value;
83
84 if head.parent.is_some() {
85 segments.push(head.segment.clone());
86 }
87
88 while let Some(next) = head.parent {
89 head = next;
90 if head.parent.is_some() {
91 segments.push(head.segment.clone());
92 }
93 }
94
95 for segment in segments.iter().rev() {
96 buffer.push('/');
97 match segment {
98 LocationSegment::Property(property) => {
99 write_escaped_str(&mut buffer, property);
100 }
101 LocationSegment::Index(idx) => {
102 let mut itoa_buffer = itoa::Buffer::new();
103 buffer.push_str(itoa_buffer.format(*idx));
104 }
105 }
106 }
107
108 Location(Arc::from(buffer))
109 }
110 }
111
112 impl<'a> From<&'a Keyword> for LocationSegment<'a> {
113 fn from(value: &'a Keyword) -> Self {
114 match value {
115 Keyword::Builtin(k) => LocationSegment::Property(k.as_str().into()),
116 Keyword::Custom(s) => LocationSegment::Property(Cow::Borrowed(s)),
117 }
118 }
119 }
120
121 impl<'a> From<&'a str> for LocationSegment<'a> {
122 #[inline]
123 fn from(value: &'a str) -> LocationSegment<'a> {
124 LocationSegment::Property(Cow::Borrowed(value))
125 }
126 }
127
128 impl<'a> From<&'a String> for LocationSegment<'a> {
129 #[inline]
130 fn from(value: &'a String) -> LocationSegment<'a> {
131 LocationSegment::Property(Cow::Borrowed(value))
132 }
133 }
134
135 impl<'a> From<Cow<'a, str>> for LocationSegment<'a> {
136 #[inline]
137 fn from(value: Cow<'a, str>) -> LocationSegment<'a> {
138 LocationSegment::Property(value)
139 }
140 }
141
142 impl From<usize> for LocationSegment<'_> {
143 #[inline]
144 fn from(value: usize) -> Self {
145 LocationSegment::Index(value)
146 }
147 }
148
149 /// A cheap to clone JSON pointer that represents location with a JSON value.
150 #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
151 pub struct Location(Arc<str>);
152
153 impl serde::Serialize for Location {
154 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
155 where
156 S: serde::Serializer,
157 {
158 serializer.serialize_str(&self.0)
159 }
160 }
161
162 impl Location {
163 /// Create a new, empty `Location`.
164 #[must_use]
165 pub fn new() -> Self {
166 Self(Arc::from(""))
167 }
168 #[must_use]
169 pub fn join<'a>(&self, segment: impl Into<LocationSegment<'a>>) -> Self {
170 let parent = &self.0;
171 match segment.into() {
172 LocationSegment::Property(property) => {
173 let mut buffer = String::with_capacity(parent.len() + property.len() + 1);
174 buffer.push_str(parent);
175 buffer.push('/');
176 write_escaped_str(&mut buffer, &property);
177 Self(Arc::from(buffer))
178 }
179 LocationSegment::Index(idx) => {
180 let mut buffer = itoa::Buffer::new();
181 let segment = buffer.format(idx);
182 Self(Arc::from(format!("{parent}/{segment}")))
183 }
184 }
185 }
186 /// Get a clone of the inner `Arc<str>` representing the location.
187 #[must_use]
188 pub(crate) fn as_arc(&self) -> Arc<str> {
189 Arc::clone(&self.0)
190 }
191
192 /// Get a string slice representing the location.
193 #[must_use]
194 pub fn as_str(&self) -> &str {
195 &self.0
196 }
197 /// Get a byte slice representing the location.
198 #[must_use]
199 pub fn as_bytes(&self) -> &[u8] {
200 self.0.as_bytes()
201 }
202
203 #[must_use]
204 pub fn iter(&self) -> std::vec::IntoIter<LocationSegment<'_>> {
205 <&Self as IntoIterator>::into_iter(self)
206 }
207 }
208
209 pub fn write_escaped_str(buffer: &mut String, value: &str) {
210 match value.find(['~', '/']) {
211 Some(mut escape_idx) => {
212 let mut remaining = value;
213
214 // Loop through the string to replace `~` and `/`
215 loop {
216 let (before, after) = remaining.split_at(escape_idx);
217 // Copy everything before the escape char
218 buffer.push_str(before);
219
220 // Append the appropriate escape sequence
221 match after.as_bytes()[0] {
222 b'~' => buffer.push_str("~0"),
223 b'/' => buffer.push_str("~1"),
224 _ => unreachable!(),
225 }
226
227 // Move past the escaped character
228 remaining = &after[1..];
229
230 // Find the next `~` or `/` to continue escaping
231 if let Some(next_escape_idx) = remaining.find(['~', '/']) {
232 escape_idx = next_escape_idx;
233 } else {
234 // Append any remaining part of the string
235 buffer.push_str(remaining);
236 break;
237 }
238 }
239 }
240 None => {
241 // If no escape characters are found, append the segment as is
242 buffer.push_str(value);
243 }
244 }
245 }
246
247 impl Default for Location {
248 fn default() -> Self {
249 Self::new()
250 }
251 }
252
253 impl fmt::Display for Location {
254 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255 f.write_str(self.as_str())
256 }
257 }
258
259 impl<'a> IntoIterator for &'a Location {
260 type Item = LocationSegment<'a>;
261 type IntoIter = std::vec::IntoIter<LocationSegment<'a>>;
262
263 fn into_iter(self) -> Self::IntoIter {
264 self.as_str()
265 .split('/')
266 .filter(|p| !p.is_empty())
267 .map(|p| {
268 p.parse::<usize>().map_or(
269 LocationSegment::Property(unescape_segment(p)),
270 LocationSegment::Index,
271 )
272 })
273 .collect::<Vec<_>>()
274 .into_iter()
275 }
276 }
277
278 impl<'a> FromIterator<LocationSegment<'a>> for Location {
279 fn from_iter<T>(iter: T) -> Self
280 where
281 T: IntoIterator<Item = LocationSegment<'a>>,
282 {
283 fn inner<'a, 'b, 'c, I>(path_iter: &mut I, location: &'b LazyLocation<'b, 'a>) -> Location
284 where
285 I: Iterator<Item = LocationSegment<'c>>,
286 {
287 let Some(path) = path_iter.next() else {
288 return location.into();
289 };
290 let location = location.push(path);
291 inner(path_iter, &location)
292 }
293
294 let loc = LazyLocation::default();
295 inner(&mut iter.into_iter(), &loc)
296 }
297 }
298
299 #[cfg(test)]
300 mod tests {
301 use super::*;
302 use serde_json::json;
303 use test_case::test_case;
304
305 #[test]
306 fn test_location_default() {
307 let loc = Location::default();
308 assert_eq!(loc.as_str(), "");
309 }
310
311 #[test]
312 fn test_location_new() {
313 let loc = Location::new();
314 assert_eq!(loc.as_str(), "");
315 }
316
317 #[test]
318 fn test_location_join_property() {
319 let loc = Location::new();
320 let loc = loc.join("property");
321 assert_eq!(loc.as_str(), "/property");
322 }
323
324 #[test]
325 fn test_location_join_index() {
326 let loc = Location::new();
327 let loc = loc.join(0);
328 assert_eq!(loc.as_str(), "/0");
329 }
330
331 #[test]
332 fn test_location_join_multiple() {
333 let loc = Location::new();
334 let loc = loc.join("property").join(0);
335 assert_eq!(loc.as_str(), "/property/0");
336 }
337
338 #[test]
339 fn test_as_bytes() {
340 let loc = Location::new().join("test");
341 assert_eq!(loc.as_bytes(), b"/test");
342 }
343
344 #[test]
345 fn test_display_trait() {
346 let loc = Location::new().join("property");
347 assert_eq!(format!("{loc}"), "/property");
348 }
349
350 #[test_case("tilde~character", "/tilde~0character"; "escapes tilde")]
351 #[test_case("slash/character", "/slash~1character"; "escapes slash")]
352 #[test_case("combo~and/slash", "/combo~0and~1slash"; "escapes tilde and slash combined")]
353 #[test_case("multiple~/escapes~", "/multiple~0~1escapes~0"; "multiple escapes")]
354 #[test_case("first/segment", "/first~1segment"; "escapes slash in nested segment")]
355 fn test_location_escaping(segment: &str, expected: &str) {
356 let loc = Location::new().join(segment);
357 assert_eq!(loc.as_str(), expected);
358 }
359
360 #[test_case("/a/b/c", &[LocationSegment::from("a"), LocationSegment::from("b"), LocationSegment::from("c")]; "location with properties")]
361 #[test_case("/1/2/3", &[LocationSegment::Index(1), LocationSegment::Index(2), LocationSegment::Index(3)]; "location with indices")]
362 #[test_case("/a/1/b/2", &[
363 LocationSegment::from("a"),
364 LocationSegment::Index(1),
365 LocationSegment::from("b"),
366 LocationSegment::Index(2)
367 ]; "mixed properties and indices")]
368 fn test_into_iter(location: &str, expected_segments: &[LocationSegment]) {
369 let loc = Location(Arc::from(location.to_string()));
370 assert_eq!(loc.into_iter().collect::<Vec<_>>(), expected_segments);
371 }
372
373 #[test_case(vec![LocationSegment::from("a"), LocationSegment::from("b")], "/a/b"; "properties only")]
374 #[test_case(vec![LocationSegment::Index(1), LocationSegment::Index(2)], "/1/2"; "indices only")]
375 #[test_case(vec![LocationSegment::from("a"), LocationSegment::Index(1)], "/a/1"; "mixed segments")]
376 fn test_from_iter(segments: Vec<LocationSegment>, expected: &str) {
377 assert_eq!(Location::from_iter(segments).as_str(), expected);
378 }
379
380 #[test]
381 fn test_roundtrip_join_iter_rebuild_equals() {
382 let loc = Location::new().join("a/b").join(2).join("x~y");
383
384 let segments: Vec<_> = loc.into_iter().collect();
385
386 let rebuilt = segments
387 .into_iter()
388 .fold(Location::new(), |acc, seg| match seg {
389 LocationSegment::Property(p) => acc.join(p),
390 LocationSegment::Index(i) => acc.join(i),
391 });
392
393 assert_eq!(loc, rebuilt);
394 }
395
396 #[test]
397 fn test_validate_error_instance_path_traverses_instance() {
398 let schema = json!({
399 "type": "object",
400 "properties": {
401 "table-node": {
402 "type": "array",
403 "items": {
404 "type": "object",
405 "properties": { "~": { "type": "string", "minLength": 1 } },
406 "required": ["~"],
407 }
408 }
409 },
410 "$schema": "https://json-schema.org/draft/2020-12/schema",
411 });
412 let instance = json!({
413 "table-node": [
414 { "~": "" },
415 { "other-value": "" },
416 ],
417 });
418
419 let error = crate::validate(&schema, &instance).expect_err("Should fail");
420
421 // Traverse instance using the `instance_path`` segments
422 let mut current = &instance;
423 for segment in error.instance_path() {
424 match segment {
425 LocationSegment::Property(property) => {
426 current = &current[property.as_ref()];
427 }
428 LocationSegment::Index(idx) => {
429 current = &current[idx];
430 }
431 }
432 }
433 assert_eq!(
434 current,
435 instance
436 .pointer("/table-node/0/~0")
437 .expect("Pointer is valid")
438 );
439 }
440 }