air_interpreter_value/value/index.rs
1/*
2 * Copyright 2024 Fluence Labs Limited
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/*
18 * This file is based on serde_json crate by Erick Tryzelaar and David Tolnay
19 * licensed under conditions of MIT License and Apache License, Version 2.0.
20 */
21
22use super::JValue;
23use core::fmt::{self, Display};
24use core::ops;
25use std::string::String;
26
27/// A type that can be used to index into a `air_interpreter_value::JValue`.
28///
29/// The [`get`] and [`get_mut`] methods of `JValue` accept any type that
30/// implements `Index`, as does the [square-bracket indexing operator]. This
31/// trait is implemented for strings which are used as the index into a JSON
32/// map, and for `usize` which is used as the index into a JSON array.
33///
34/// [`get`]: ../enum.JValue.html#method.get
35/// [`get_mut`]: ../enum.JValue.html#method.get_mut
36/// [square-bracket indexing operator]: ../enum.JValue.html#impl-Index%3CI%3E
37///
38/// This trait is sealed and cannot be implemented for types outside of
39/// `air_interpreter_value`.
40pub trait Index: private::Sealed {
41 /// Return None if the key is not already in the array or object.
42 #[doc(hidden)]
43 fn index_into<'v>(&self, v: &'v JValue) -> Option<&'v JValue>;
44}
45
46impl Index for usize {
47 fn index_into<'v>(&self, v: &'v JValue) -> Option<&'v JValue> {
48 match v {
49 JValue::Array(vec) => vec.get(*self),
50 _ => None,
51 }
52 }
53}
54
55impl Index for str {
56 fn index_into<'v>(&self, v: &'v JValue) -> Option<&'v JValue> {
57 match v {
58 JValue::Object(map) => map.get(self),
59 _ => None,
60 }
61 }
62}
63
64impl Index for String {
65 fn index_into<'v>(&self, v: &'v JValue) -> Option<&'v JValue> {
66 self[..].index_into(v)
67 }
68}
69
70impl<T> Index for &T
71where
72 T: ?Sized + Index,
73{
74 fn index_into<'v>(&self, v: &'v JValue) -> Option<&'v JValue> {
75 (**self).index_into(v)
76 }
77}
78
79// Prevent users from implementing the Index trait.
80mod private {
81 pub trait Sealed {}
82 impl Sealed for usize {}
83 impl Sealed for str {}
84 impl Sealed for std::string::String {}
85 impl<'a, T> Sealed for &'a T where T: ?Sized + Sealed {}
86}
87
88/// Used in panic messages.
89struct Type<'a>(&'a JValue);
90
91impl<'a> Display for Type<'a> {
92 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
93 match *self.0 {
94 JValue::Null => formatter.write_str("null"),
95 JValue::Bool(_) => formatter.write_str("boolean"),
96 JValue::Number(_) => formatter.write_str("number"),
97 JValue::String(_) => formatter.write_str("string"),
98 JValue::Array(_) => formatter.write_str("array"),
99 JValue::Object(_) => formatter.write_str("object"),
100 }
101 }
102}
103
104// The usual semantics of Index is to panic on invalid indexing.
105//
106// That said, the usual semantics are for things like Vec and BTreeMap which
107// have different use cases than JValue. If you are working with a Vec, you know
108// that you are working with a Vec and you can get the len of the Vec and make
109// sure your indices are within bounds. The JValue use cases are more
110// loosey-goosey. You got some JSON from an endpoint and you want to pull values
111// out of it. Outside of this Index impl, you already have the option of using
112// value.as_array() and working with the Vec directly, or matching on
113// JValue::Array and getting the Vec directly. The Index impl means you can skip
114// that and index directly into the thing using a concise syntax. You don't have
115// to check the type, you don't have to check the len, it is all about what you
116// expect the JValue to look like.
117//
118// Basically the use cases that would be well served by panicking here are
119// better served by using one of the other approaches: get and get_mut,
120// as_array, or match. The value of this impl is that it adds a way of working
121// with JValue that is not well served by the existing approaches: concise and
122// careless and sometimes that is exactly what you want.
123impl<I> ops::Index<I> for JValue
124where
125 I: Index,
126{
127 type Output = JValue;
128
129 /// Index into a `air_interpreter_value::JValue` using the syntax `value[0]` or
130 /// `value["k"]`.
131 ///
132 /// Returns `JValue::Null` if the type of `self` does not match the type of
133 /// the index, for example if the index is a string and `self` is an array
134 /// or a number. Also returns `JValue::Null` if the given key does not exist
135 /// in the map or the given index is not within the bounds of the array.
136 ///
137 /// For retrieving deeply nested values, you should have a look at the
138 /// `JValue::pointer` method.
139 fn index(&self, index: I) -> &JValue {
140 const NULL: JValue = JValue::Null;
141 index.index_into(self).unwrap_or(&NULL)
142 }
143}