Debian Codegraph @

src/resource.rs

raw symbols SCIP
1 use std::{
2 borrow::Cow,
3 sync::atomic::{AtomicPtr, Ordering},
4 };
5
6 use serde_json::Value;
7
8 use crate::{Anchor, Draft, Error, Resolved, Resolver, Segments};
9
10 pub(crate) trait JsonSchemaResource {
11 fn contents(&self) -> &Value;
12 fn draft(&self) -> Draft;
13 fn id(&self) -> Option<&str> {
14 self.draft()
15 .id_of(self.contents())
16 .map(|id| id.trim_end_matches('#'))
17 }
18 }
19
20 /// An owned document with a concrete interpretation under a JSON Schema specification.
21 #[derive(Debug, Clone, PartialEq, Eq)]
22 pub struct Resource {
23 contents: Value,
24 draft: Draft,
25 }
26
27 impl Resource {
28 pub(crate) fn new(contents: Value, draft: Draft) -> Self {
29 Self { contents, draft }
30 }
31 pub(crate) fn into_inner(self) -> (Draft, Value) {
32 (self.draft, self.contents)
33 }
34 /// Resource contents.
35 #[must_use]
36 pub fn contents(&self) -> &Value {
37 &self.contents
38 }
39 /// JSON Schema draft under which this contents is interpreted.
40 #[must_use]
41 pub fn draft(&self) -> Draft {
42 self.draft
43 }
44 /// Create a resource with automatically detecting specification which applies to the contents.
45 ///
46 /// Unknown `$schema` values are treated as `Draft::Unknown`.
47 #[must_use]
48 pub fn from_contents(contents: Value) -> Resource {
49 Draft::default().detect(&contents).create_resource(contents)
50 }
51 }
52
53 /// A borrowed document with a concrete interpretation under a JSON Schema specification.
54 #[derive(Debug, Clone, Copy)]
55 pub struct ResourceRef<'a> {
56 contents: &'a Value,
57 draft: Draft,
58 }
59
60 impl<'a> ResourceRef<'a> {
61 #[must_use]
62 pub fn new(contents: &'a Value, draft: Draft) -> Self {
63 Self { contents, draft }
64 }
65 #[must_use]
66 pub fn contents(&self) -> &'a Value {
67 self.contents
68 }
69 #[must_use]
70 pub fn draft(&self) -> Draft {
71 self.draft
72 }
73
74 /// Create a resource-ref with automatically detecting specification which applies to the contents.
75 ///
76 /// Unknown `$schema` values are treated as `Draft::Unknown`.
77 #[must_use]
78 pub fn from_contents(contents: &'a Value) -> Self {
79 let draft = Draft::default().detect(contents);
80 Self::new(contents, draft)
81 }
82
83 #[must_use]
84 pub fn id(&self) -> Option<&str> {
85 JsonSchemaResource::id(self)
86 }
87 }
88
89 impl JsonSchemaResource for ResourceRef<'_> {
90 fn contents(&self) -> &Value {
91 self.contents
92 }
93
94 fn draft(&self) -> Draft {
95 self.draft
96 }
97 }
98
99 /// A pointer to a pinned resource.
100 pub(crate) struct InnerResourcePtr {
101 contents: AtomicPtr<Value>,
102 draft: Draft,
103 }
104
105 impl Clone for InnerResourcePtr {
106 fn clone(&self) -> Self {
107 Self {
108 contents: AtomicPtr::new(self.contents.load(Ordering::Relaxed)),
109 draft: self.draft,
110 }
111 }
112 }
113
114 impl std::fmt::Debug for InnerResourcePtr {
115 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116 f.debug_struct("InnerResourcePtr")
117 .field("contents", self.contents())
118 .field("draft", &self.draft)
119 .finish()
120 }
121 }
122
123 impl InnerResourcePtr {
124 pub(crate) fn new(contents: *const Value, draft: Draft) -> Self {
125 Self {
126 contents: AtomicPtr::new(contents.cast_mut()),
127 draft,
128 }
129 }
130
131 #[allow(unsafe_code)]
132 pub(crate) fn contents(&self) -> &Value {
133 // SAFETY: The pointer is valid as long as the registry exists
134 unsafe { &*self.contents.load(Ordering::Relaxed) }
135 }
136
137 #[inline]
138 pub(crate) fn draft(&self) -> Draft {
139 self.draft
140 }
141
142 pub(crate) fn anchors(&self) -> impl Iterator<Item = Anchor> + '_ {
143 self.draft().anchors(self.contents())
144 }
145
146 pub(crate) fn pointer<'r>(
147 &'r self,
148 pointer: &str,
149 mut resolver: Resolver<'r>,
150 ) -> Result<Resolved<'r>, Error> {
151 // INVARIANT: Pointer always starts with `/`
152 let mut contents = self.contents();
153 let mut segments = Segments::new();
154 let original_pointer = pointer;
155 let pointer = percent_encoding::percent_decode_str(&pointer[1..])
156 .decode_utf8()
157 .map_err(|err| Error::invalid_percent_encoding(original_pointer, err))?;
158 for segment in pointer.split('/') {
159 if let Some(array) = contents.as_array() {
160 let idx = segment
161 .parse::<usize>()
162 .map_err(|err| Error::invalid_array_index(original_pointer, segment, err))?;
163 if let Some(next) = array.get(idx) {
164 contents = next;
165 } else {
166 return Err(Error::pointer_to_nowhere(original_pointer));
167 }
168 segments.push(idx);
169 } else {
170 let segment = unescape_segment(segment);
171 if let Some(next) = contents.get(segment.as_ref()) {
172 contents = next;
173 } else {
174 return Err(Error::pointer_to_nowhere(original_pointer));
175 }
176 segments.push(segment);
177 }
178 let last = &resolver;
179 let new_resolver = self.draft().maybe_in_subresource(
180 &segments,
181 &resolver,
182 &InnerResourcePtr::new(contents, self.draft()),
183 )?;
184 if new_resolver != *last {
185 segments = Segments::new();
186 }
187 resolver = new_resolver;
188 }
189 Ok(Resolved::new(contents, resolver, self.draft()))
190 }
191 }
192
193 impl JsonSchemaResource for InnerResourcePtr {
194 fn contents(&self) -> &Value {
195 self.contents()
196 }
197
198 fn draft(&self) -> Draft {
199 self.draft
200 }
201 }
202
203 /// Unescape JSON Pointer path segments by converting `~1` to `/` and `~0` to `~`.
204 #[must_use]
205 pub fn unescape_segment(mut segment: &str) -> Cow<'_, str> {
206 // Naively, checking for `~` and then replacing implies two passes
207 // over the input buffer. First, search in the first `contains('~')` call
208 // and then replacing `~1` & `~0` at once in a single pass.
209 //
210 // This implementation is ~3x faster than the naive one.
211 //
212 // **NOTE**: Heavily inspired by the implementation in `boon`:
213 // `https://github.com/santhosh-tekuri/boon/blob/fb09df2db19be75c32c0970b4bdedf1655f5f943/src/util.rs#L31`
214 let Some(mut tilde_idx) = segment.find('~') else {
215 return Cow::Borrowed(segment);
216 };
217
218 let mut buffer = String::with_capacity(segment.len());
219 loop {
220 let (before, after) = segment.split_at(tilde_idx);
221 buffer.push_str(before);
222 segment = &after[1..];
223 let next_char_size = match segment.chars().next() {
224 Some('1') => {
225 buffer.push('/');
226 1
227 }
228 Some('0') => {
229 buffer.push('~');
230 1
231 }
232 Some(next) => {
233 buffer.push('~');
234 buffer.push(next);
235 next.len_utf8()
236 }
237 None => {
238 buffer.push('~');
239 break;
240 }
241 };
242 segment = &segment[next_char_size..];
243 let Some(next_tilde_idx) = segment.find('~') else {
244 buffer.push_str(segment);
245 break;
246 };
247 tilde_idx = next_tilde_idx;
248 }
249 Cow::Owned(buffer)
250 }
251
252 #[cfg(test)]
253 mod tests {
254 use std::{error::Error, sync::Arc};
255
256 use crate::{resource::InnerResourcePtr, Draft, Registry};
257
258 use super::unescape_segment;
259 use serde_json::json;
260 use test_case::test_case;
261
262 #[test_case("abc")]
263 #[test_case("a~0b")]
264 #[test_case("a~1b")]
265 #[test_case("~01")]
266 #[test_case("~10")]
267 #[test_case("a~0~1b")]
268 #[test_case("~"; "single tilde")]
269 #[test_case("~~"; "double tilde")]
270 #[test_case("~~~~~"; "many tildas")]
271 #[test_case("~2")]
272 #[test_case("a~c")]
273 #[test_case("~0~1~")]
274 #[test_case("")]
275 #[test_case("a/d")]
276 #[test_case("a~01b")]
277 #[test_case("🌟~0🌠~1🌡️"; "Emojis with escapes")]
278 #[test_case("~🌟"; "Tilde followed by emoji")]
279 #[test_case("Café~0~1"; "Accented characters with escapes")]
280 #[test_case("~é"; "Tilde followed by accented character")]
281 #[test_case("αβγ"; "Greek")]
282 #[test_case("~αβγ"; "Tilde followed by Greek")]
283 #[test_case("∀∂∈ℝ∧∪≡∞"; "Mathematical symbols")]
284 #[test_case("~∀∂∈ℝ∧∪≡∞"; "Tilde followed by mathematical symbols")]
285 #[test_case("¡¢£¤¥¦§¨©"; "Special characters")]
286 #[test_case("~¡¢£¤¥¦§¨©"; "Tilde followed by special characters")]
287 #[test_case("\u{10FFFF}"; "Highest valid Unicode code point")]
288 #[test_case("~\u{10FFFF}"; "Tilde followed by highest valid Unicode code point")]
289 fn test_unescape_segment_equivalence(input: &str) {
290 let unescaped = unescape_segment(input);
291 let double_replaced = input.replace("~1", "/").replace("~0", "~");
292 assert_eq!(unescaped, double_replaced, "Failed for: {input}");
293 }
294
295 fn create_test_registry() -> Registry {
296 let schema = Draft::Draft202012.create_resource(json!({
297 "type": "object",
298 "properties": {
299 "foo": { "type": "string" },
300 "bar": { "type": "array", "items": [{"type": "number"}, {"type": "boolean"}] }
301 }
302 }));
303 Registry::try_new("http://example.com", schema).expect("Invalid resources")
304 }
305
306 #[test]
307 fn test_empty_ref() {
308 let schema = Draft::Draft202012.create_resource(json!({
309 "type": "object",
310 "properties": {
311 "foo": { "type": "string" }
312 }
313 }));
314 let registry =
315 Registry::try_new("http://example.com", schema.clone()).expect("Invalid resources");
316 let resolver = registry
317 .try_resolver("http://example.com")
318 .expect("Invalid base URI");
319
320 let resolved = resolver.lookup("#").expect("Lookup failed");
321 assert_eq!(resolved.contents(), schema.contents());
322 }
323
324 #[test]
325 fn test_inner_resource_ptr_debug() {
326 let value = Arc::pin(json!({
327 "foo": "bar",
328 "number": 42
329 }));
330
331 let ptr = InnerResourcePtr::new(std::ptr::addr_of!(*value), Draft::Draft202012);
332
333 let expected = format!(
334 "InnerResourcePtr {{ contents: {:?}, draft: Draft202012 }}",
335 *value
336 );
337 assert_eq!(format!("{ptr:?}"), expected);
338 }
339
340 #[test]
341 fn test_percent_encoded_non_utf8() {
342 let registry = create_test_registry();
343 let resolver = registry
344 .try_resolver("http://example.com")
345 .expect("Invalid base URI");
346
347 let result = resolver.lookup("#/%FF");
348 let error = result.expect_err("Should fail");
349 assert_eq!(
350 error.to_string(),
351 "Invalid percent encoding in pointer '/%FF': the decoded bytes do not represent valid UTF-8"
352 );
353 assert!(error.source().is_some());
354 }
355
356 #[test]
357 fn test_array_index_as_string() {
358 let registry = create_test_registry();
359 let resolver = registry
360 .try_resolver("http://example.com")
361 .expect("Invalid base URI");
362
363 let result = resolver.lookup("#/properties/bar/items/one");
364 let error = result.expect_err("Should fail");
365 assert_eq!(
366 error.to_string(),
367 "Failed to parse array index 'one' in pointer '/properties/bar/items/one'"
368 );
369 assert!(error.source().is_some());
370 }
371
372 #[test]
373 fn test_array_index_out_of_bounds() {
374 let registry = create_test_registry();
375 let resolver = registry
376 .try_resolver("http://example.com")
377 .expect("Invalid base URI");
378
379 let result = resolver.lookup("#/properties/bar/items/2");
380 assert_eq!(
381 result.expect_err("Should fail").to_string(),
382 "Pointer '/properties/bar/items/2' does not exist"
383 );
384 }
385
386 #[test]
387 fn test_unknown_property() {
388 let registry = create_test_registry();
389 let resolver = registry
390 .try_resolver("http://example.com")
391 .expect("Invalid base URI");
392
393 let result = resolver.lookup("#/properties/baz");
394 assert_eq!(
395 result.expect_err("Should fail").to_string(),
396 "Pointer '/properties/baz' does not exist"
397 );
398 }
399 }