WasmEngine/patch/0002-add-another_json_minimal-to-vendor.patch

1872 lines
65 KiB
Diff
Raw Normal View History

From 40ca80de7dd4b07b7748fafe82c869863ebd2552 Mon Sep 17 00:00:00 2001
From: build <build@obs.com>
Date: Tue, 9 Aug 2022 19:36:16 +0800
Subject: [PATCH] add another_json_minimal to vendor
---
.../another_json_minimal/.cargo-checksum.json | 1 +
vendor/another_json_minimal/Cargo.toml | 25 +
vendor/another_json_minimal/LICENSE.md | 19 +
vendor/another_json_minimal/README.md | 316 +++++++
vendor/another_json_minimal/src/lib.rs | 790 ++++++++++++++++++
vendor/another_json_minimal/src/tests.rs | 658 +++++++++++++++
6 files changed, 1809 insertions(+)
create mode 100644 vendor/another_json_minimal/.cargo-checksum.json
create mode 100644 vendor/another_json_minimal/Cargo.toml
create mode 100644 vendor/another_json_minimal/LICENSE.md
create mode 100644 vendor/another_json_minimal/README.md
create mode 100644 vendor/another_json_minimal/src/lib.rs
create mode 100644 vendor/another_json_minimal/src/tests.rs
diff --git a/vendor/another_json_minimal/.cargo-checksum.json b/vendor/another_json_minimal/.cargo-checksum.json
new file mode 100644
index 00000000..eb4596a4
--- /dev/null
+++ b/vendor/another_json_minimal/.cargo-checksum.json
@@ -0,0 +1 @@
+{"files":{"Cargo.toml":"5976a21419a8e5226318259a855ca3f520f9480511b4af6a152f4fb4850fa480","LICENSE.md":"35e1404ccc3a758c529c821ca1c4df4e6a810227d6f28c6951d168a4dad6d485","README.md":"edb5cadb71dac49f1b66bcbf5ed8c18b06a2e7ef7bd70aae7775e3f89eaef678","src/lib.rs":"170f6a19395b229fb60049f136655318e6897cdb58e59f42a2a7ea99fd254714","src/tests.rs":"8b45652fdee66d58b849b596663f43657c6cf58f87b1e29dac0f4267d6266b1d"},"package":"77ba8341e1396c8a379f62de1b47f31256f2fe0846f5f95e9c60014d2102d9bd"}
\ No newline at end of file
diff --git a/vendor/another_json_minimal/Cargo.toml b/vendor/another_json_minimal/Cargo.toml
new file mode 100644
index 00000000..61e86752
--- /dev/null
+++ b/vendor/another_json_minimal/Cargo.toml
@@ -0,0 +1,25 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies.
+#
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+edition = "2021"
+name = "another_json_minimal"
+version = "0.0.2"
+authors = ["36den", "meilier"]
+description = "A minimal json crate."
+readme = "README.md"
+keywords = ["json", "minimal"]
+categories = ["encoding"]
+license = "MIT OR Apache-2.0"
+repository = "https://github.com/meilier/json_minimal-rust"
+resolver = "2"
+
+[dependencies]
diff --git a/vendor/another_json_minimal/LICENSE.md b/vendor/another_json_minimal/LICENSE.md
new file mode 100644
index 00000000..5147935e
--- /dev/null
+++ b/vendor/another_json_minimal/LICENSE.md
@@ -0,0 +1,19 @@
+# APACHE
+
+Copyright 2020 36den
+
+Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
+
+`http://www.apache.org/licenses/LICENSE-2.0`
+
+Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
+
+# MIT
+
+Copyright 2020 36den
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
diff --git a/vendor/another_json_minimal/README.md b/vendor/another_json_minimal/README.md
new file mode 100644
index 00000000..f5869899
--- /dev/null
+++ b/vendor/another_json_minimal/README.md
@@ -0,0 +1,316 @@
+# json_minimal
+
+A minimal json crate conforming to https://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf .
+
+## Tutorial (creating jsons)
+
+In order to create a valid (i.e. generally accepted) json you should always start with:
+```rust
+ use json_minimal::*;
+
+ let mut json = Json::new();
+ // which is equivalent to
+ let mut json = Json::JSON(Vec::new());
+ // ...
+```
+
+To add an object, simply do this:
+```rust
+ // ...
+ let greeting =
+ Json::OBJECT {
+ name: String::from("Greeting"),
+
+ value: Box::new(
+ Json::STRING( String::from("Hello, world!") )
+ )
+ }
+ ;
+
+ json.add(greeting);
+ // ...
+```
+or alternatively:
+```rust
+ // ...
+ json.add(
+ Json::OBJECT {
+ name: String::from("Greeting"),
+
+ value: Box::new(
+ Json::STRING( String::from("Hello, world!") )
+ )
+ }
+ );
+ // ...
+```
+
+As you can see, whilst the crate is minimal (in my opinion) it may not be the quickest to work with. This becomes clearer when adding an array to an object:
+```rust
+ // ...
+
+ let mut days_in_the_week =
+ Json::OBJECT {
+ name: String::from("Days of the week"),
+
+ value: Box::new(
+ Json::JSON(Vec::new())
+ )
+ }
+ ;
+
+ let mut days = Json::ARRAY(Vec::new());
+
+ days
+ .add(
+ Json::STRING( String::from("Monday") )
+ )
+ .add(
+ Json::STRING( String::from("Tuesday") )
+ )
+ .add(
+ Json::STRING( String::from("Wednesday") )
+ )
+ .add(
+ Json::STRING( String::from("Thursday") )
+ )
+ .add(
+ Json::STRING( String::from("Friday") )
+ )
+ .add(
+ Json::STRING( String::from("Saturday") )
+ )
+ .add(
+ Json::STRING( String::from("Sunday") )
+ )
+ ;
+
+ days_in_the_week
+ .add(
+ Json::OBJECT {
+ name: String::from("Total number of days"),
+
+ value: Box::new(
+ Json::NUMBER(7.0) // Accepts `f64`
+ )
+ }
+ )
+ .add(
+ Json::OBJECT {
+ name: String::from("They are called"),
+
+ value: Box::new(
+ days
+ )
+ }
+ )
+ ;
+
+ json.add(days_in_the_week);
+ // ...
+```
+
+In conclusion:
+```rust
+ // ...
+
+ let mut conclusion =
+ Json::OBJECT {
+ name: String::from("Conclusion"),
+
+ value: Box::new(
+ Json::JSON(Vec::new())
+ )
+ }
+ ;
+
+ conclusion
+ .add(
+ Json::OBJECT {
+ name: String::from("Minimal in my opinion"),
+
+ value: Box::new(
+ Json::BOOL(true)
+ )
+ }
+ )
+ .add(
+ Json::OBJECT {
+ name: String::from("How much I care about your opinion"),
+
+ value: Box::new(
+ Json::NULL
+ )
+ }
+ )
+ .add(
+ Json::OBJECT {
+ name: String::from("Comment"),
+
+ value: Box::new(
+ Json::STRING( String::from(";)") )
+ )
+ }
+ )
+ ;
+
+ json.add(conclusion);
+ // ...
+```
+
+Calling:
+```rust
+ // ...
+ let resulting_json = json.print();
+```
+will result in a `String` containing:
+`{"Greeting":"Hello, world!","Days of the week":{"Total number of days":7,"They are called":["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]},"Conclusion":{"Minimal in my opinion":true,"How much I care about your opinion":null,"Comment":";)"}}`
+
+If you would like the json string in a different format you can easily make your own 'print' function.
+
+## Tutorial (parsing and working with jsons)
+
+Parsing a json value from bytes is even more minimal - at the cost of being more cumbersome. Let's see how we can parse the json we generated above:
+```rust
+ use json_minimal::*;
+
+ let json = match Json::parse(b"{\"Greeting\":\"Hello, world!\",\"Days of the week\":{\"Total number of days\":7,\"They are called\":[\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\",\"Saturday\",\"Sunday\"]},\"Conclusion\":{\"Minimal in my opinion\":true,\"How much I care about your opinion\":null,\"Comment\":\";)\"}}") {
+ Ok(json) => {
+ json
+ },
+ Err( (position,message) ) => {
+ panic!("`{}` at position `{}`!!!");
+ }
+ }
+ // ...
+```
+
+Let's first talk about what information is given for a parsing error. As you might expect it is minimal. `position` above is the position were everything went wrong and the `message` will be something like`"Error parsing array."` if, for example, a closing `]` is missing somewhere. Continuing where we left off:
+```rust
+ // ...
+ match json.get("Greeting") {
+ Some(json) => {
+ match json {
+ Json::OBJECT { name: _, value } => {
+ match value.unbox() {
+ Json::STRING(val) => {
+ assert_eq!("Hello, world!",val);
+ },
+ json => {
+ panic!("Expected Json::STRING but found {:?}",json);
+ }
+ }
+ },
+ json => {
+ panic!("Expected Json::JSON but found {:?}!!!",json)
+ }
+ }
+ },
+ None => {
+ panic!("Couln't find Greeting. How rude!");
+ }
+ }
+ // ...
+```
+Unfortunately all of this was necessary because, even though we were able to confirm that `"Greeting"` exists, we had no way of knowing what it really is. It's not over:
+```rust
+ // ...
+ match json.get("Days of the week") { // Hint: You can also use `get_mut` to aid in editing/creating jsons...
+ Some(json) => {
+ match json {
+ Json::OBJECT { name: _, value } => {
+ match value.unbox() {
+ Json::JSON(values) => {
+ assert_eq!(values.len(),2);
+
+ match &values[0] {
+ Json::OBJECT { name, value: _ } => {
+ assert_eq!("Total number of days",name);
+ },
+ json => {
+ panic!("Expected Json::OBJECT but found {:?}!!!",json);
+ }
+ }
+
+ match &values[1] {
+ Json::OBJECT { name, value: _ } => {
+ assert_eq!("They are called",name);
+ },
+ json => {
+ panic!("Expected Json::OBJECT but found {:?}!!!",json);
+ }
+ }
+
+ },
+ json => {
+ panic!("Expected Json::JSON but found {:?}!!!",json);
+ }
+ }
+ },
+ json => {
+ panic!("Expected Json::OBJECT but found {:?}!!!",json);
+ }
+ }
+ },
+ None => {
+ panic!("Days of the week not found!");
+ }
+ }
+ // You get the idea.
+```
+The function `Json::parse(...)` can also parse 'standalone values'. Example:
+
+```rust
+ match Json::parse("\"What's up?\"") {
+ Ok(json) => {
+ match json {
+ Json::STRING(val) => {
+ assert_eq!("What's up?",val);
+ },
+ json => {
+ panic!("Expected Json::STRING but found {:?}!!!",json);
+ }
+ }
+ },
+ Err( (position,message) ) => {
+ panic!("`{}` at position `{}`.");
+ }
+ }
+
+ // Another example:
+
+ match Json::parse("[1,2,3,\"four\"]") {
+ Ok(json) => {
+ match json {
+ Json::ARRAY(val) => {
+ assert_eq!(val.len(),4);
+ },
+ json => {
+ panic!("Expected Json::ARRAY but found {:?}!!!",json);
+ }
+ }
+ },
+ Err( (position,message) ) => {
+ panic!("`{}` at position `{}`.");
+ }
+ }
+```
+## Changes & Improvements
+
+* Lonami (github) has made improvements:
+ 1. `json_minimal` can now parse non-ASCII strings and escape sequences. (I overlooked this, I admit.)
+ 2. The code is cleaner thanks to the question-mark operator and using rustfmt.
+ 3. Some parsing stuff that didn't work now works.
+
+ A thousand thanks to Lonami !!!
+
+* `json_minimal` can now also parse 'pretty' json like this (as long as only `\r`, `\n`, `\t` and whitespace were used for formatting):
+```
+{
+ "Array": [ "Hello" , "World" , "!" ]
+}
+```
+This should also have worked from the start but I did not include because it of my aversion to energy inefficiency (although it is, perhaps, unfounded).
+
+---
+Please let me know if something doesn't work. I can't promise i'll react immediately, though.
\ No newline at end of file
diff --git a/vendor/another_json_minimal/src/lib.rs b/vendor/another_json_minimal/src/lib.rs
new file mode 100644
index 00000000..0aad96a3
--- /dev/null
+++ b/vendor/another_json_minimal/src/lib.rs
@@ -0,0 +1,790 @@
+//Copyright 2020 36den
+//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+#[derive(Debug)]
+pub enum Json {
+ OBJECT { name: String, value: Box<Json> },
+ JSON(Vec<Json>),
+ ARRAY(Vec<Json>),
+ STRING(String),
+ NUMBER(f64),
+ BOOL(bool),
+ NULL,
+}
+
+impl Json {
+ /// Construct a new `Json::JSON`
+ /// ## Example
+ /// ```
+ /// use json_minimal::*;
+ ///
+ /// let mut json = Json::new();
+ /// ```
+ pub fn new() -> Json {
+ Json::JSON(Vec::new())
+ }
+
+ /// Add any `Json` variant to a `Json` variant of type `Json::JSON`, `Json::ARRAY`
+ /// or a `Json::OBJECT` (holding a `Json::JSON`,`Json::ARRAY`,`Json::OBJECT` (holding a `Json::JSON`,`Json::`...)).
+ /// ## Panics!
+ /// Will panic if the conditions stated above are not met OR if an attempt is made to add a `Json::JSON` to a `Json::JSON`
+ /// without wrapping it in a `Json::OBJECT` first.
+ /// ## Example
+ /// ```
+ /// use json_minimal::*;
+ ///
+ /// let mut json = Json::new();
+ ///
+ /// json
+ /// .add(
+ /// Json::OBJECT {
+ /// name: String::from("Greeting"),
+ ///
+ /// value: Box::new(
+ /// Json::STRING( String::from("Hello, world!") )
+ /// )
+ /// }
+ /// )
+ /// ;
+ /// ```
+ /// See the <a href="https://github.com/36den/json_minimal-rs/">tutorial</a> on github for more.
+ pub fn add(&mut self, value: Json) -> &mut Json {
+ match self {
+ Json::JSON(values) => match value {
+ Json::OBJECT { name, value } => {
+ values.push(Json::OBJECT { name, value });
+ }
+ Json::JSON(_) => {
+ panic!("A `Json::JSON` may not be added to a `Json::JSON` if it is not within a `Json::OBJECT`.");
+ }
+ Json::ARRAY(vals) => {
+ values.push(Json::ARRAY(vals));
+ }
+ Json::STRING(val) => {
+ values.push(Json::STRING(val));
+ }
+ Json::NUMBER(val) => {
+ values.push(Json::NUMBER(val));
+ }
+ Json::BOOL(val) => {
+ values.push(Json::BOOL(val));
+ }
+ Json::NULL => {
+ values.push(Json::NULL);
+ }
+ },
+ Json::OBJECT {
+ name: _,
+ value: obj_val,
+ } => match obj_val.unbox_mut() {
+ Json::JSON(values) => match value {
+ Json::OBJECT { name, value } => {
+ values.push(Json::OBJECT { name, value });
+ }
+ Json::JSON(_) => {
+ panic!("A `Json::JSON` may not be added to a `Json::JSON` if it is not within a `Json::OBJECT`.");
+ }
+ Json::ARRAY(vals) => {
+ values.push(Json::ARRAY(vals));
+ }
+ Json::STRING(val) => {
+ values.push(Json::STRING(val));
+ }
+ Json::NUMBER(val) => {
+ values.push(Json::NUMBER(val));
+ }
+ Json::BOOL(val) => {
+ values.push(Json::BOOL(val));
+ }
+ Json::NULL => {
+ values.push(Json::NULL);
+ }
+ },
+ Json::ARRAY(values) => match value {
+ Json::OBJECT { name, value } => {
+ values.push(Json::OBJECT { name, value });
+ }
+ Json::JSON(vals) => {
+ values.push(Json::JSON(vals));
+ }
+ Json::ARRAY(vals) => {
+ values.push(Json::ARRAY(vals));
+ }
+ Json::STRING(val) => {
+ values.push(Json::STRING(val));
+ }
+ Json::NUMBER(val) => {
+ values.push(Json::NUMBER(val));
+ }
+ Json::BOOL(val) => {
+ values.push(Json::BOOL(val));
+ }
+ Json::NULL => {
+ values.push(Json::NULL);
+ }
+ },
+ json => {
+ panic!("The function `add(`&mut self`,`name: String`,`value: Json`)` may only be called on a `Json::JSON`, `Json::ARRAY` or `Json::OBJECT` holding a `Json::JSON` or `Json::ARRAY`. It was called on: {:?}",json);
+ }
+ },
+ Json::ARRAY(values) => match value {
+ Json::OBJECT { name, value } => {
+ values.push(Json::OBJECT { name, value });
+ }
+ Json::JSON(vals) => {
+ values.push(Json::JSON(vals));
+ }
+ Json::ARRAY(vals) => {
+ values.push(Json::ARRAY(vals));
+ }
+ Json::STRING(val) => {
+ values.push(Json::STRING(val));
+ }
+ Json::NUMBER(val) => {
+ values.push(Json::NUMBER(val));
+ }
+ Json::BOOL(val) => {
+ values.push(Json::BOOL(val));
+ }
+ Json::NULL => {
+ values.push(Json::NULL);
+ }
+ },
+ json => {
+ panic!("The function `add(`&mut self`,`name: String`,`value: Json`)` may only be called on a `Json::JSON`, `Json::ARRAY` or `Json::OBJECT` holding a `Json::JSON` or `Json::ARRAY`. It was called on: {:?}",json);
+ }
+ }
+
+ self
+ }
+
+ /// Get the `Json` with the requested name if it exists.
+ /// ## Panics
+ /// This function will panic if called on a `Json` variant other than `Json::JSON` or `Json::OBJECT`,
+ /// as only these two variants may hold `Json::OBJECT` (which has a `name` field).
+ /// ## Example
+ /// ```
+ /// use json_minimal::*;
+ ///
+ /// let mut json = Json::new();
+ ///
+ /// json
+ /// .add(
+ /// Json::OBJECT {
+ /// name: String::from("Greeting"),
+ ///
+ /// value: Box::new(
+ /// Json::STRING( String::from("Hello, world!") )
+ /// )
+ /// }
+ /// )
+ /// ;
+ ///
+ /// match json.get("Greeting") {
+ /// Some(json) => {
+ /// match json {
+ /// Json::OBJECT { name, value } => {
+ /// match value.unbox() { // See `unbox()` below
+ /// Json::STRING(val) => {
+ /// assert_eq!("Hello, world!",val);
+ /// },
+ /// _ => {
+ /// panic!("I expected this to be a `Json::STRING`!!!");
+ /// }
+ /// }
+ /// },
+ /// _ => {
+ /// panic!("This shouldn't happen!!!");
+ /// }
+ /// }
+ /// },
+ /// None => {
+ /// panic!("Not found!!!");
+ /// }
+ /// }
+ /// ```
+ pub fn get(&self, search: &str) -> Option<&Json> {
+ match self {
+ Json::JSON(values) => {
+ for n in 0..values.len() {
+ match &values[n] {
+ Json::OBJECT { name, value } => {
+ if name == search {
+ match value.unbox() {
+ Json::STRING(_) => {
+ return Some(value.unbox());
+ }
+ _ => {
+ return Some(&values[n]);
+ }
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+
+ return None;
+ }
+ Json::OBJECT { name: _, value } => match value.unbox() {
+ Json::STRING(_) => {
+ return Some(value.unbox());
+ }
+ Json::JSON(values) => {
+ for n in 0..values.len() {
+ match &values[n] {
+ Json::OBJECT { name, value: _ } => {
+ if name == search {
+ return Some(&values[n]);
+ }
+ }
+ _ => {}
+ }
+ }
+
+ return None;
+ }
+ json => {
+ panic!("The function `get(`&self`,`search: &str`)` may only be called on a `Json::JSON` or a `Json::OBJECT` holding a `Json::JSON`. I was called on: {:?}",json);
+ }
+ },
+ json => {
+ panic!("The function `get(`&self`,`search: &str`)` may only be called on a `Json::JSON`. I was called on: {:?}",json);
+ }
+ }
+ }
+
+ /// Same as `get` above, but the references are mutable. Use `unbox_mut()` (see below) with this one.
+ /// ## Panics
+ /// This function will panic if called on a `Json` variant other than `Json::JSON` or `Json::OBJECT`,
+ /// as only these two variants may hold `Json::OBJECT` which has a `name` field.
+ pub fn get_mut(&mut self, search: &str) -> Option<&mut Json> {
+ match self {
+ Json::JSON(values) => {
+ for n in 0..values.len() {
+ match &values[n] {
+ Json::OBJECT { name, value: _ } => {
+ if name == search {
+ return Some(&mut values[n]);
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+ Json::OBJECT { name: _, value } => match value.unbox_mut() {
+ Json::JSON(values) => {
+ for n in 0..values.len() {
+ match &values[n] {
+ Json::OBJECT { name, value: _ } => {
+ if name == search {
+ return Some(&mut values[n]);
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+ json => {
+ panic!("The function `get_mut(`&self`,`search: &str`)` may only be called on a `Json::JSON` or a `Json::OBJECT` holding a `Json::JSON`. I was called on: {:?}",json);
+ }
+ },
+ json => {
+ panic!("The function `get_mut(`&self`,`search: &str`)` may only be called on a `Json::JSON` or a `Json::OBJECT` holding a `Json::JSON`. I was called on: {:?}",json);
+ }
+ }
+
+ None
+ }
+
+ /// Enables matching the contents of a `Box`.
+ pub fn unbox(&self) -> &Json {
+ self
+ }
+
+ /// Idem.
+ pub fn unbox_mut(&mut self) -> &mut Json {
+ self
+ }
+
+ /// Returns a `String` of the form: `{"Json":"Value",...}` but can also be called on 'standalone objects'
+ /// which could result in `"Object":{"Stuff":...}` or `"Json":true`.
+ pub fn print(&self) -> String {
+ let mut result = String::new();
+
+ match self {
+ Json::OBJECT { name, value } => {
+ result.push_str(&format!("\"{}\":\"{}\"", name, value.print()));
+ }
+ Json::JSON(values) => {
+ result.push('{');
+
+ for n in 0..values.len() {
+ result.push_str(&values[n].print());
+ result.push(',');
+ }
+
+ result.pop();
+
+ result.push('}');
+ }
+ Json::ARRAY(values) => {
+ result.push('[');
+
+ for n in 0..values.len() {
+ result.push_str(&values[n].print());
+ result.push(',');
+ }
+
+ result.pop();
+
+ result.push(']');
+ }
+ Json::STRING(val) => {
+ result.push_str(&format!("{}", val));
+ }
+ Json::NUMBER(val) => {
+ result.push_str(&format!("{}", val));
+ }
+ Json::BOOL(val) => {
+ if *val {
+ result.push_str("true");
+ } else {
+ result.push_str("false")
+ }
+ }
+ Json::NULL => {
+ result.push_str("null");
+ }
+ }
+
+ result
+ }
+
+ /// Parses the given bytes if a json structure is found. It even works with `\"Hello\":\"World\"`
+ /// (doesn't have to be like `{...}`), i.e. it can return any of the variants in the `Json` enum.
+ /// The error is returned in the form `(last position, what went wrong)`. Unfortunately the error
+ /// description are minimal (basically "Error parsing ...type...").
+ /// ## Example
+ /// ```
+ /// use json_minimal::*;
+ ///
+ /// match Json::parse(b"{\"Greeting\":\"Hello, world!\"}") {
+ /// Ok(json) => {
+ ///
+ /// match json.get("Greeting") {
+ /// Some(json) => {
+ /// match json {
+ /// Json::OBJECT { name, value } => {
+ /// match value.unbox() {
+ /// Json::STRING(val) => {
+ /// assert_eq!(val,"Hello, world!");
+ /// },
+ /// json => {
+ /// panic!("Expected Json::STRING but found {:?}!!!",json);
+ /// }
+ /// }
+ /// }
+ /// json => {
+ /// panic!("Expected Json::OBJECT but found {:?}!!!",json);
+ /// }
+ /// }
+ /// },
+ /// None => {
+ /// panic!("Greeting was not found!!!");
+ /// }
+ /// }
+ /// },
+ /// Err( (pos,msg) ) => {
+ /// panic!("`{}` at position `{}`!!!",msg,pos);
+ /// }
+ /// }
+ /// ```
+ /// See the <a href="https://github.com/36den/json_minimal-rs/">tutorial</a> on github for more.
+ pub fn parse(input: &[u8]) -> Result<Json, (usize, &'static str)> {
+ let mut incr: usize = 0;
+
+ match input[incr] as char {
+ '{' => Self::parse_json(input, &mut incr),
+ '\"' => Self::parse_string(input, &mut incr),
+ '[' => Self::parse_array(input, &mut incr),
+ 't' | 'f' => Self::parse_bool(input, &mut incr),
+ 'n' => Self::parse_null(input, &mut incr),
+ '0'..='9' => Self::parse_number(input, &mut incr),
+ _ => Err((incr, "Not a valid json format")),
+ }
+ }
+
+ // This must exclusively be used by `parse_string` to make any sense.
+ fn parse_object(
+ input: &[u8],
+ incr: &mut usize,
+ name: String,
+ ) -> Result<Json, (usize, &'static str)> {
+ // if input[*incr] as char != ':' {
+ // return Err((*incr, "Error parsing object."));
+ // }
+
+ *incr += 1;
+
+ if *incr >= input.len() {
+ return Err((*incr, "Error parsing object."));
+ }
+
+ loop {
+ match input[*incr] as char {
+ '\r' | '\n' | '\t' | ' ' => {
+ *incr += 1;
+
+ if *incr >= input.len() {
+ return Err((*incr, "Error parsing object."));
+ }
+ }
+ _ => {
+ break;
+ }
+ }
+ }
+
+ let value = match input[*incr] as char {
+ '{' => Self::parse_json(input, incr)?,
+ '[' => Self::parse_array(input, incr)?,
+ '\"' => Self::parse_string(input, incr)?,
+ 't' | 'f' => Self::parse_bool(input, incr)?,
+ 'n' => Self::parse_null(input, incr)?,
+ '0'..='9' => Self::parse_number(input, incr)?,
+ _ => {
+ return Err((*incr, "Error parsing object."));
+ }
+ };
+
+ Ok(Json::OBJECT {
+ name,
+
+ value: Box::new(value),
+ })
+ }
+
+ // Parse if you thik it's something like `{...}`
+ fn parse_json(input: &[u8], incr: &mut usize) -> Result<Json, (usize, &'static str)> {
+ let mut result: Vec<Json> = Vec::new();
+
+ // if input[*incr] as char != '{' {
+ // return Err((*incr, "Error parsing json."));
+ // }
+
+ *incr += 1;
+
+ if *incr >= input.len() {
+ return Err((*incr, "Error parsing json."));
+ }
+
+ loop {
+ let json = match input[*incr] as char {
+ ',' => {
+ *incr += 1;
+ continue;
+ }
+ '\"' => Self::parse_string(input, incr)?,
+ '[' => Self::parse_array(input, incr)?,
+ 't' | 'f' => Self::parse_bool(input, incr)?,
+ 'n' => Self::parse_null(input, incr)?,
+ '0'..='9' => Self::parse_number(input, incr)?,
+ '}' => {
+ *incr += 1;
+
+ return Ok(Json::JSON(result));
+ }
+ '{' => Self::parse_json(input, incr)?,
+ '\r' | '\n' | '\t' | ' ' => {
+ *incr += 1;
+
+ if *incr >= input.len() {
+ return Err((*incr, "Error parsing json."));
+ }
+
+ continue;
+ }
+ _ => {
+ return Err((*incr, "Error parsing json."));
+ }
+ };
+
+ result.push(json);
+ }
+ }
+
+ // Parse a &str if you're sure it resembles `[...`
+ fn parse_array(input: &[u8], incr: &mut usize) -> Result<Json, (usize, &'static str)> {
+ let mut result: Vec<Json> = Vec::new();
+
+ // if input[*incr] as char != '[' {
+ // return Err((*incr, "Error parsing array."));
+ // }
+
+ *incr += 1;
+
+ if *incr >= input.len() {
+ return Err((*incr, "Error parsing array."));
+ }
+
+ loop {
+ let json = match input[*incr] as char {
+ ',' => {
+ *incr += 1;
+ continue;
+ }
+ '\"' => Self::parse_string(input, incr)?,
+ '[' => Self::parse_array(input, incr)?,
+ '{' => Self::parse_json(input, incr)?,
+ 't' | 'f' => Self::parse_bool(input, incr)?,
+ 'n' => Self::parse_null(input, incr)?,
+ '0'..='9' => Self::parse_number(input, incr)?,
+ ']' => {
+ *incr += 1;
+
+ return Ok(Json::ARRAY(result));
+ }
+ '\r' | '\n' | '\t' | ' ' => {
+ *incr += 1;
+
+ if *incr >= input.len() {
+ return Err((*incr, "Error parsing array."));
+ }
+
+ continue;
+ }
+ _ => {
+ return Err((*incr, "Error parsing array."));
+ }
+ };
+
+ result.push(json);
+ }
+ }
+
+ // Parse a &str if you know that it corresponds to/starts with a json String.
+ fn parse_string(input: &[u8], incr: &mut usize) -> Result<Json, (usize, &'static str)> {
+ let mut result: Vec<u8> = Vec::new();
+
+ // if input[*incr] as char != '\"' {
+ // return Err((*incr, "Error parsing string."));
+ // }
+
+ *incr += 1;
+
+ if *incr >= input.len() {
+ return Err((*incr, "Error parsing string."));
+ }
+
+ loop {
+ match input[*incr] {
+ b'\"' => {
+ *incr += 1;
+
+ let result = String::from_utf8(result)
+ .map_err(|_| (*incr, "Error parsing non-utf8 string."))?;
+
+ if *incr < input.len() {
+ if input[*incr] as char == ':' {
+ return Self::parse_object(input, incr, result);
+ } else {
+ return Ok(Json::STRING(result));
+ }
+ } else {
+ return Ok(Json::STRING(result));
+ }
+ }
+ b'\\' => {
+ Self::parse_string_escape_sequence(input, incr, &mut result)?;
+ }
+ c => {
+ result.push(c);
+
+ *incr += 1;
+
+ if *incr >= input.len() {
+ return Err((*incr, "Error parsing string."));
+ }
+ }
+ }
+ }
+ }
+
+ // Parse an escape sequence inside a string
+ fn parse_string_escape_sequence(
+ input: &[u8],
+ incr: &mut usize,
+ result: &mut Vec<u8>,
+ ) -> Result<(), (usize, &'static str)> {
+ // if input[*incr] as char != '\\' {
+ // return Err((*incr, "Error parsing string escape sequence."));
+ // }
+
+ *incr += 1;
+
+ if *incr >= input.len() {
+ return Err((*incr, "Error parsing string escape sequence."));
+ }
+
+ match input[*incr] as char {
+ '\"' | '\\' | '/' => {
+ result.push(input[*incr]);
+ }
+ 'b' => {
+ result.push(b'\x08');
+ }
+ 'f' => {
+ result.push(b'\x0c');
+ }
+ 'n' => {
+ result.push(b'\n');
+ }
+ 'r' => {
+ result.push(b'\r');
+ }
+ 't' => {
+ result.push(b'\t');
+ }
+ 'u' => {
+ const BAD_UNICODE: &str = "Error parsing unicode string escape sequence.";
+
+ if *incr + 4 >= input.len() {
+ return Err((*incr, BAD_UNICODE));
+ }
+
+ let hex = (&input[*incr + 1..*incr + 5]).to_vec();
+ let hex = String::from_utf8(hex).map_err(|_| (*incr, BAD_UNICODE))?;
+ let value = u16::from_str_radix(&hex, 16).map_err(|_| (*incr, BAD_UNICODE))?;
+ let value = std::char::from_u32(value as u32).ok_or((*incr, BAD_UNICODE))?;
+
+ let mut buffer = [0; 4];
+ result.extend(value.encode_utf8(&mut buffer).as_bytes());
+ *incr += 4;
+ }
+ _ => {
+ return Err((*incr, "Error parsing invalid string escape sequence."));
+ }
+ }
+
+ *incr += 1;
+
+ if *incr >= input.len() {
+ return Err((*incr, "Error parsing string escape sequence."));
+ }
+
+ Ok(())
+ }
+
+ fn parse_number(input: &[u8], incr: &mut usize) -> Result<Json, (usize, &'static str)> {
+ let mut result = String::new();
+
+ loop {
+ match input[*incr] as char {
+ ',' | ']' | '}' | '\r' | '\n' | '\t' | ' ' => {
+ break;
+ }
+ c => {
+ result.push(c);
+
+ *incr += 1;
+
+ if *incr >= input.len() {
+ match result.parse::<f64>() {
+ Ok(num) => {
+ return Ok(Json::NUMBER(num));
+ }
+ Err(_) => {
+ return Err((*incr, "Error parsing number."));
+ }
+ }
+ }
+ }
+ }
+ }
+
+ match result.parse::<f64>() {
+ Ok(num) => {
+ return Ok(Json::NUMBER(num));
+ }
+ Err(_) => {
+ return Err((*incr, "Error parsing number."));
+ }
+ }
+ }
+
+ fn parse_bool(input: &[u8], incr: &mut usize) -> Result<Json, (usize, &'static str)> {
+ let mut result = String::new();
+
+ loop {
+ match input[*incr] as char {
+ ',' | ']' | '}' | '\r' | '\n' | '\t' | ' ' => {
+ break;
+ }
+ c => {
+ result.push(c);
+
+ *incr += 1;
+
+ if *incr >= input.len() {
+ if result == "true" {
+ return Ok(Json::BOOL(true));
+ }
+
+ if result == "false" {
+ return Ok(Json::BOOL(false));
+ }
+
+ return Err((*incr, "Error parsing bool."));
+ }
+ }
+ }
+ }
+
+ if result == "true" {
+ return Ok(Json::BOOL(true));
+ }
+
+ if result == "false" {
+ return Ok(Json::BOOL(false));
+ }
+
+ return Err((*incr, "Error parsing bool."));
+ }
+
+ fn parse_null(input: &[u8], incr: &mut usize) -> Result<Json, (usize, &'static str)> {
+ let mut result = String::new();
+
+ loop {
+ match input[*incr] as char {
+ ',' | ']' | '}' | '\r' | '\n' | '\t' | ' ' => {
+ break;
+ }
+ c => {
+ result.push(c);
+
+ *incr += 1;
+
+ if *incr >= input.len() {
+ if result == "null" {
+ return Ok(Json::NULL);
+ } else {
+ return Err((*incr, "Error parsing null."));
+ }
+ }
+ }
+ }
+ }
+
+ if result == "null" {
+ return Ok(Json::NULL);
+ } else {
+ return Err((*incr, "Error parsing null."));
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/vendor/another_json_minimal/src/tests.rs b/vendor/another_json_minimal/src/tests.rs
new file mode 100644
index 00000000..3b351c1d
--- /dev/null
+++ b/vendor/another_json_minimal/src/tests.rs
@@ -0,0 +1,658 @@
+//Copyright 2020 36den
+//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+use super::*;
+
+#[test]
+fn test_make_json() {
+ let mut json = Json::new();
+
+ let greeting = Json::OBJECT {
+ name: String::from("Greeting"),
+
+ value: Box::new(Json::STRING(String::from("Hello, world!"))),
+ };
+
+ json.add(greeting);
+
+ let mut days_in_the_week = Json::OBJECT {
+ name: String::from("Days in the week"),
+
+ value: Box::new(Json::JSON(Vec::new())),
+ };
+
+ let mut days = Json::ARRAY(Vec::new());
+
+ days.add(Json::STRING(String::from("Monday")))
+ .add(Json::STRING(String::from("Tuesday")))
+ .add(Json::STRING(String::from("Wednesday")))
+ .add(Json::STRING(String::from("Thursday")))
+ .add(Json::STRING(String::from("Friday")))
+ .add(Json::STRING(String::from("Saturday")))
+ .add(Json::STRING(String::from("Sunday")));
+
+ days_in_the_week
+ .add(Json::OBJECT {
+ name: String::from("Total number of days"),
+
+ value: Box::new(Json::NUMBER(7.0)),
+ })
+ .add(Json::OBJECT {
+ name: String::from("They are called"),
+
+ value: Box::new(days),
+ });
+
+ json.add(days_in_the_week);
+
+ let mut conclusion = Json::OBJECT {
+ name: String::from("Conclusion"),
+
+ value: Box::new(Json::JSON(Vec::new())),
+ };
+
+ conclusion
+ .add(Json::OBJECT {
+ name: String::from("Minimal in my opinion"),
+
+ value: Box::new(Json::BOOL(true)),
+ })
+ .add(Json::OBJECT {
+ name: String::from("How much I care about your opinion"),
+
+ value: Box::new(Json::NULL),
+ })
+ .add(Json::OBJECT {
+ name: String::from("Comment"),
+
+ value: Box::new(Json::STRING(String::from(";)"))),
+ });
+
+ json.add(conclusion);
+
+ assert_eq!(
+ "{\"Greeting\":\"Hello, world!\",\"Days in the week\":{\"Total number of days\":7,\"They are called\":[\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\",\"Saturday\",\"Sunday\"]},\"Conclusion\":{\"Minimal in my opinion\":true,\"How much I care about your opinion\":null,\"Comment\":\";)\"}}",
+ &json.print()
+ )
+}
+
+#[test]
+fn test_get_mut() {
+ let mut json = Json::new();
+
+ json.add(Json::OBJECT {
+ name: String::from("Greeting"),
+
+ value: Box::new(Json::STRING(String::from("Hello, world!"))),
+ });
+
+ match json.get_mut("Greeting") {
+ Some(json) => match json {
+ Json::OBJECT { name: _, value } => match value.unbox_mut() {
+ Json::STRING(val) => {
+ assert_eq!("Hello, world!", val);
+
+ val.push_str(" How are you?");
+
+ assert_eq!("Hello, world! How are you?", val);
+ }
+ _ => {
+ panic!("Expected `Json::STRING`!!!");
+ }
+ },
+ _ => {
+ panic!("Expected `Json::OBJECT`!!!");
+ }
+ },
+ None => {
+ panic!("Not found!!!");
+ }
+ }
+}
+
+#[test]
+fn test_parse_number() {
+ let mut incr: usize = 0;
+
+ match Json::parse_number(b"36.36", &mut incr) {
+ Ok(json) => match json {
+ Json::NUMBER(val) => {
+ assert_eq!(val, 36.36);
+ }
+ json => {
+ panic!("Expected Json::NUMBER but found {:?}", json);
+ }
+ },
+ Err(e) => {
+ parse_error(e);
+ }
+ }
+}
+
+#[test]
+fn test_parse_bool() {
+ let mut incr: usize = 0;
+
+ match Json::parse_bool(b"true", &mut incr) {
+ Ok(json) => match json {
+ Json::BOOL(val) => {
+ assert_eq!(val, true);
+ }
+ json => {
+ panic!("Expected Json::BOOL but found {:?}", json);
+ }
+ },
+ Err(e) => {
+ parse_error(e);
+ }
+ }
+
+ incr = 0;
+
+ match Json::parse_bool(b"false", &mut incr) {
+ Ok(json) => match json {
+ Json::BOOL(val) => {
+ assert_eq!(val, false);
+ }
+ json => {
+ panic!("Expected Json::BOOL but found {:?}", json);
+ }
+ },
+ Err(e) => {
+ parse_error(e);
+ }
+ }
+}
+
+#[test]
+fn test_parse_null() {
+ let mut incr: usize = 0;
+
+ match Json::parse_null(b"null", &mut incr) {
+ Ok(json) => match json {
+ Json::NULL => {}
+ json => {
+ panic!("Expected Json::NULL but found {:?}", json);
+ }
+ },
+ Err(e) => {
+ parse_error(e);
+ }
+ }
+}
+
+#[test]
+fn test_parse_array() {
+ let mut incr: usize = 0;
+
+ match Json::parse_array(
+ b"[1,\"two\",true,[\"array\",[\"another one\",[\"another one\",1.5]]]]",
+ &mut incr,
+ ) {
+ Ok(json) => match json {
+ Json::ARRAY(vals) => {
+ assert_eq!(vals.len(), 4);
+ }
+ json => {
+ panic!("Expected Json::ARRAY but found {:?}", json);
+ }
+ },
+ Err(e) => {
+ parse_error(e);
+ }
+ }
+}
+
+#[test]
+fn test_parse_json() {
+ let mut incr: usize = 0;
+
+ match Json::parse_json(b"{\"on\",\"off\"}", &mut incr) {
+ Ok(json) => match json {
+ Json::JSON(vals) => {
+ assert_eq!(vals.len(), 2);
+ }
+ json => {
+ panic!("Expected Json::ARRAY but found {:?}", json);
+ }
+ },
+ Err(e) => {
+ parse_error(e);
+ }
+ }
+}
+
+#[test]
+fn test_parse_json_2() {
+ let mut incr: usize = 0;
+
+ match Json::parse_json(
+ b"{\"on\",\"off\",\"OBJECT\":{\"ARRAY\":[\"on\",\"off\"]},\"on or off?\"}",
+ &mut incr,
+ ) {
+ Ok(json) => match json {
+ Json::JSON(vals) => {
+ assert_eq!(vals.len(), 4);
+ }
+ json => {
+ panic!("Expected Json::ARRAY but found {:?}", json);
+ }
+ },
+ Err(e) => {
+ parse_error(e);
+ }
+ }
+}
+
+#[test]
+fn test_parse_object() {
+ let mut incr: usize = 0;
+
+ match Json::parse_string(b"\"String\":\"Value\"", &mut incr) {
+ Ok(json) => match json {
+ Json::OBJECT { name, value } => {
+ assert_eq!(name, "String");
+
+ match value.unbox() {
+ Json::STRING(val) => {
+ assert_eq!(val, "Value");
+ }
+ json => {
+ panic!("Expected Json::STRING but found {:?}", json);
+ }
+ }
+ }
+ json => {
+ panic!("Expected Json::OBJECT but found {:?}", json);
+ }
+ },
+ Err(e) => {
+ parse_error(e);
+ }
+ }
+}
+
+#[test]
+fn test_parse() {
+ match Json::parse(b"{\"Greeting\":\"Hello, world!\",\"Days in the week\":{\"Total number of days\":7,\"They are called\":[\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\",\"Saturday\",\"Sunday\"]},\"Minimal in my opinion\":true,\"How much I care about your opinion\":null}") {
+ Ok(json) => {
+ match json {
+ Json::JSON(values) => {
+ assert_eq!(values.len(),4);
+
+ match &values[0] {
+ Json::OBJECT { name, value } => {
+ assert_eq!("Greeting",name);
+
+ match value.unbox() {
+ Json::STRING(val) => {
+ assert_eq!("Hello, world!",val);
+ },
+ json => {
+ panic!("Expected Json::STRING but found {:?}",json);
+ }
+ }
+ },
+ json => {
+ panic!("Expected Json::OBJECT but found {:?}",json);
+ }
+ }
+
+ match &values[1] {
+ Json::OBJECT { name, value } => {
+ assert_eq!("Days in the week",name);
+
+ match value.unbox() {
+ Json::JSON(values) => {
+ assert_eq!(values.len(),2);
+
+ match &values[0] {
+ Json::OBJECT { name, value } => {
+ assert_eq!("Total number of days",name);
+
+ match value.unbox() {
+ Json::NUMBER(num) => {
+ assert_eq!(*num,7.0);
+ },
+ json => {
+ panic!("Expected Json::NUMBER but found {:?}",json);
+ }
+ }
+ },
+ json => {
+ panic!("Expected Json::OBJECT but found {:?}",json);
+ }
+ }
+
+ match &values[1] {
+ Json::OBJECT { name, value } => {
+ assert_eq!("They are called",name);
+
+ match value.unbox() {
+ Json::ARRAY(vals) => {
+ assert_eq!(vals.len(),7);
+
+ for n in 0..7 {
+ match &vals[n] {
+ Json::STRING(val) => {
+ match val.as_bytes() {
+ b"Monday" => {
+
+ },
+ b"Tuesday" => {
+
+ },
+ b"Wednesday" => {
+
+ },
+ b"Thursday" => {
+
+ },
+ b"Friday" => {
+
+ },
+ b"Saturday" => {
+
+ },
+ b"Sunday" => {
+
+ },
+ d => {
+ panic!("\"{:?}\" is not a day of the week!!",d);
+ }
+ }
+ },
+ json => {
+ panic!("Expected Json::STRING but found {:?}",json);
+ }
+ }
+ }
+ },
+ json => {
+ panic!("Expected Json::ARRAY but found {:?}",json);
+ }
+ }
+ },
+ json => {
+ panic!("Expected Json::OBJECT but found {:?}",json);
+ }
+ }
+ },
+ json => {
+ panic!("Expected Json::JSON but found {:?}",json);
+ }
+ }
+ },
+ json => {
+ panic!("Expected Json::OBJECT but found {:?}",json);
+ }
+ }
+ },
+ json => {
+ panic!("Expected Json::JSON but found {:?}",json);
+ }
+ }
+ },
+ Err(e) => {
+ parse_error(e);
+ }
+ }
+}
+
+#[test]
+fn test_parse_2() {
+ #[allow(unused_assignments)]
+
+ let json = match Json::parse(b"{\"Greeting\":\"Hello, world!\",\"Days of the week\":{\"Total number of days\":7,\"They are called\":[\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\",\"Saturday\",\"Sunday\"]},\"Conclusion\":{\"Minimal in my opinion\":true,\"How much I care about your opinion\":null,\"Comment\":\";)\"}}") {
+ Ok(json) => {
+ json
+ },
+ Err( (position,message) ) => {
+ panic!("`{}` at position `{}`!!!",message,position);
+ }
+ };
+
+ match json.get("Greeting") {
+ Some(json) => match json {
+ Json::OBJECT { name: _, value } => match value.unbox() {
+ Json::STRING(val) => {
+ assert_eq!("Hello, world!", val);
+ }
+ json => {
+ panic!("Expected Json::STRING but found {:?}", json);
+ }
+ },
+ json => panic!("Expected Json::JSON but found {:?}!!!", json),
+ },
+ None => {
+ panic!("Couln't find Greeting. How rude!");
+ }
+ }
+
+ match json.get("Days of the week") {
+ // Hint: You can also use `get_mut` to aid in editing/creating jsons...
+ Some(json) => match json {
+ Json::OBJECT { name: _, value } => match value.unbox() {
+ Json::JSON(values) => {
+ assert_eq!(values.len(), 2);
+
+ match &values[0] {
+ Json::OBJECT { name, value: _ } => {
+ assert_eq!("Total number of days", name);
+ }
+ json => {
+ panic!("Expected Json::OBJECT but found {:?}!!!", json);
+ }
+ }
+
+ match &values[1] {
+ Json::OBJECT { name, value: _ } => {
+ assert_eq!("They are called", name);
+ }
+ json => {
+ panic!("Expected Json::OBJECT but found {:?}!!!", json);
+ }
+ }
+ }
+ json => {
+ panic!("Expected Json::JSON but found {:?}!!!", json);
+ }
+ },
+ json => {
+ panic!("Expected Json::OBJECT but found {:?}!!!", json);
+ }
+ },
+ None => {
+ panic!("Days of the week not found!");
+ }
+ }
+}
+
+#[test]
+fn parse_strange() {
+ let json = match Json::parse(b"[0,{\"hello\":\"world\",\"what's\":\"up?\"}]") {
+ Ok(json) => json,
+ Err((pos, msg)) => {
+ panic!("`{}` at position {}", msg, pos);
+ }
+ };
+
+ match json {
+ Json::ARRAY(vals) => {
+ assert_eq!(vals.len(), 2);
+
+ match &vals[0] {
+ Json::NUMBER(n) => {
+ assert_eq!(*n, 0.0);
+ }
+ json => {
+ panic!("Expected Json::NUMBER but found {:?}!!!", json);
+ }
+ }
+
+ match &vals[1] {
+ Json::JSON(vals) => {
+ assert_eq!(2, vals.len());
+
+ match &vals[0] {
+ Json::OBJECT { name, value: _ } => {
+ assert_eq!("hello", name);
+ }
+ json => {
+ panic!("Expected Json::ARRAY but found {:?}!!!", json);
+ }
+ }
+
+ match &vals[1] {
+ Json::OBJECT { name, value: _ } => {
+ assert_eq!("what's", name);
+ }
+ json => {
+ panic!("Expected Json::ARRAY but found {:?}!!!", json);
+ }
+ }
+ }
+ json => {
+ panic!("Expected Json::JSON but found {:?}!!!", json);
+ }
+ }
+ }
+ json => {
+ panic!("Expected Json::ARRAY but found {:?}!!!", json);
+ }
+ }
+}
+
+#[test]
+fn parse_escape_sequence() {
+ let json = match Json::parse(br#""a \" \/ \b \f \n \r \t \u2764 z""#) {
+ Ok(json) => json,
+ Err((pos, msg)) => {
+ panic!("`{}` at position {}", msg, pos);
+ }
+ };
+
+ match json {
+ Json::STRING(string) => {
+ assert_eq!(string, "a \" / \u{8} \u{c} \n \r \t ❤ z");
+ }
+ json => {
+ panic!("Expected Json::STRING but found {:?}!!!", json);
+ }
+ }
+}
+
+#[test]
+fn parse_escape_sequence_in_array() {
+ let json = match Json::parse(br#"["\"foo"]"#) {
+ Ok(json) => json,
+ Err((pos, msg)) => {
+ panic!("`{}` at position {}", msg, pos);
+ }
+ };
+
+ match json {
+ Json::ARRAY(vals) => {
+ assert_eq!(vals.len(), 1);
+
+ match &vals[0] {
+ Json::STRING(n) => {
+ assert_eq!(*n, "\"foo");
+ }
+ json => {
+ panic!("Expected Json::STRING but found {:?}!!!", json);
+ }
+ }
+ }
+ json => {
+ panic!("Expected Json::ARRAY but found {:?}!!!", json);
+ }
+ }
+}
+
+#[test]
+fn parse_non_ascii() {
+ let json = match Json::parse(r#""a ❤ z""#.as_bytes()) {
+ Ok(json) => json,
+ Err((pos, msg)) => {
+ panic!("`{}` at position {}", msg, pos);
+ }
+ };
+
+ match json {
+ Json::STRING(string) => {
+ assert_eq!(string, "a ❤ z");
+ }
+ json => {
+ panic!("Expected Json::STRING but found {:?}!!!", json);
+ }
+ }
+}
+
+#[test]
+fn parse_pretty() {
+ let json = match Json::parse(b"{\r\n\t\"Array\": [\r\n\t\t\"First\" ,\r\n\r\n\t\t2 ,\r\n\r\n\t\t[\"Three\"] ,\r\n\r\n\t\t3.6\r\n\t],\r\n\t{\r\n\r\n\t\t\"Sub-Object\": \"Hello, world!\"\r\n\t}\r\n}") {
+ Ok(json) => json,
+ Err((pos, msg)) => {
+ panic!("`{}` at position {}", msg, pos);
+ }
+ };
+
+ match json {
+ Json::JSON(values) => {
+
+ match values[0].unbox() {
+ Json::OBJECT { name, value } => {
+ assert_eq!(name,"Array");
+
+ match value.unbox() {
+ Json::ARRAY(values) => {
+ assert_eq!(values.len(),4);
+ },
+ json => {
+ panic!("Expected Json::ARRAY but found {:?}!!!", json);
+ }
+ }
+ },
+ json => {
+ panic!("Expected Json::OBJECT but found {:?}!!!", json);
+ }
+ }
+
+ match values[1].unbox() {
+ Json::JSON(values) => {
+
+ match values[0].unbox() {
+ Json::OBJECT { name, value } => {
+ assert_eq!(name,"Sub-Object");
+
+ match value.unbox() {
+ Json::STRING(value) => {
+ assert_eq!(value,"Hello, world!");
+ },
+ json => {
+ panic!("Expected Json::STRING but found {:?}!!!", json);
+ }
+ }
+ },
+ json => {
+ panic!("Expected Json::OBJECT but found {:?}!!!", json);
+ }
+ }
+
+ },
+ json => {
+ panic!("Expected Json::Json but found {:?}!!!", json);
+ }
+ }
+ },
+ json => {
+ panic!("Expected Json::JSON but found {:?}!!!", json);
+ }
+ }
+}
+
+fn parse_error((pos, msg): (usize, &str)) {
+ panic!("`{}` at position `{}`!!!", msg, pos);
+}
--
2.27.0