1 // Copyright (c) 2023 Huawei Device Co., Ltd.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 //     http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 mod array;
15 mod index;
16 mod number;
17 mod object;
18 
19 pub use array::Array;
20 pub use index::Index;
21 pub use number::Number;
22 pub use object::Object;
23 
24 use crate::{start_parsing, CompactEncoder, Error, FormattedEncoder};
25 use core::fmt::{Debug, Display, Formatter};
26 use core::str::FromStr;
27 #[cfg(feature = "c_adapter")]
28 use std::ffi::CString;
29 use std::io::{Read, Write};
30 
31 #[cfg(feature = "c_adapter")]
32 pub type JsonString = CString;
33 #[cfg(not(feature = "c_adapter"))]
34 pub type JsonString = String;
35 
36 use crate::deserializer::Deserializer;
37 #[cfg(not(feature = "c_adapter"))]
38 use std::fs::File;
39 #[cfg(not(feature = "c_adapter"))]
40 use std::path::Path;
41 
42 /// There are 6 types of values that appear in Json text:
43 ///
44 /// 1.Null: Null tupe
45 ///
46 /// 2.Boolean: Boolean type
47 ///
48 /// 3.Number: Numerical type
49 ///
50 /// 4.String: String type
51 ///
52 /// 5.Array: Array type
53 ///
54 /// 6.Object: Object type
55 ///
56 /// RFC 7159 3. Values say
57 /// “A Json value must be an object, an array, a number, a string, or a text string of false, null, or true.”
58 ///
59 /// # features
60 /// Uses"c_adatper" feature:
61 /// In order to adapt the C encapsulation layer interface, the structure changes the
62 /// underlying implementation of String, and uses CString to get the char* pointer easily.
63 // TODO: Enhance the encapsulation of JsonValue, makes users can't use enum directly.
64 #[derive(Clone)]
65 pub enum JsonValue {
66     /// Null type
67     Null,
68 
69     /// Boolean type
70     Boolean(bool),
71 
72     /// Numerical type
73     Number(Number),
74 
75     /// String type
76     String(JsonString),
77 
78     /// Array type
79     Array(Array),
80 
81     /// Object type
82     Object(Object),
83 }
84 
85 /// JsonValue print method 1, prints the content directly (without extra double quotes).
86 ///
87 /// # Examples
88 /// ```
89 /// use ylong_json::JsonValue;
90 ///
91 /// let value: JsonValue = "hello".into();
92 /// let string = format!("{value}");
93 /// assert_eq!(string, "\"hello\"");
94 /// ```
95 impl Display for JsonValue {
fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result96     fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
97         match self {
98             Self::Null => write!(f, "null"),
99             Self::Boolean(b) => write!(f, "{b}"),
100             Self::Number(n) => Display::fmt(n, f),
101             // The Debug output is the same for CString and String.
102             Self::String(s) => write!(f, "{s:?}"),
103             Self::Array(a) => Display::fmt(a, f),
104             Self::Object(o) => Display::fmt(o, f),
105         }
106     }
107 }
108 
109 impl Debug for JsonValue {
fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result110     fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
111         Display::fmt(self, f)
112     }
113 }
114 
115 impl JsonValue {
116     /// Creates an instance of JsonValue for Null type.
117     ///
118     /// # Examples
119     /// ```
120     /// use ylong_json::JsonValue;
121     ///
122     /// let value = JsonValue::new_null();
123     /// assert_eq!(value, JsonValue::Null);
124     /// ```
new_null() -> Self125     pub fn new_null() -> Self {
126         Self::Null
127     }
128 
129     /// Creates an instance of JsonValue for Boolean type.
130     ///
131     /// # Examples
132     /// ```
133     /// use ylong_json::JsonValue;
134     ///
135     /// let value = JsonValue::new_boolean(true);
136     /// assert_eq!(value, JsonValue::Boolean(true));
137     /// ```
new_boolean(boolean: bool) -> Self138     pub fn new_boolean(boolean: bool) -> Self {
139         Self::Boolean(boolean)
140     }
141 
142     /// Creates an instance of JsonValue for Numerical type.
143     ///
144     /// # Examples
145     /// ```
146     /// use ylong_json::JsonValue;
147     ///
148     /// let value = JsonValue::new_number(0.0.into());
149     /// assert_eq!(value, JsonValue::Number(0.0.into()));
150     /// ```
new_number(number: Number) -> Self151     pub fn new_number(number: Number) -> Self {
152         Self::Number(number)
153     }
154 
155     /// Creates an instance of JsonValue for String type.
156     ///
157     /// # Examples
158     /// ```not run
159     /// use ylong_json::JsonValue;
160     ///
161     /// let value = JsonValue::new_string("Hello World");
162     /// // When open "c_adapter" feature, the internal value is String.
163     /// assert_eq!(value, JsonValue::String(String::from("Hello World")));
164     ///
165     /// // When opening "c_adapter" feature, the internal value is CString.
166     /// // assert_eq!(value, JsonValue::String(CString::new("Hello World")));
167     /// ```
new_string(str: &str) -> Self168     pub fn new_string(str: &str) -> Self {
169         // The underlying implementation of String here is CString.
170         #[cfg(feature = "c_adapter")]
171         let result = Self::String(JsonString::new(str).unwrap());
172 
173         #[cfg(not(feature = "c_adapter"))]
174         let result = Self::String(JsonString::from(str));
175 
176         result
177     }
178 
179     /// Creates an instance of JsonValue for Array type.
180     ///
181     /// # Examples
182     /// ```
183     /// use ylong_json::{JsonValue, Array};
184     ///
185     /// let value = JsonValue::new_array(Array::new());
186     /// assert_eq!(value, JsonValue::Array(Array::new()));
187     /// ```
new_array(array: Array) -> Self188     pub fn new_array(array: Array) -> Self {
189         Self::Array(array)
190     }
191 
192     /// Creates an instance of JsonValue for Object type.
193     ///
194     /// # Examples
195     /// ```
196     /// use ylong_json::{JsonValue, Object};
197     ///
198     /// let value = JsonValue::new_object(Object::new());
199     /// assert_eq!(value, JsonValue::Object(Object::new()));
200     /// ```
new_object(object: Object) -> Self201     pub fn new_object(object: Object) -> Self {
202         Self::Object(object)
203     }
204 
205     /// Determines whether JsonValue is Null type. Returns true if yes, false if no.
206     ///
207     /// # Examples
208     /// ```
209     /// use ylong_json::JsonValue;
210     ///
211     /// let null_value = JsonValue::new_null();
212     /// assert_eq!(null_value.is_null(), true);
213     ///
214     /// let other_value = JsonValue::new_number(0.0.into());
215     /// assert_eq!(other_value.is_null(), false);
216     /// ```
is_null(&self) -> bool217     pub fn is_null(&self) -> bool {
218         matches!(*self, Self::Null)
219     }
220 
221     /// Determines whether JsonValue is Boolean type. Returns true if yes, false if no.
222     ///
223     /// # Examples
224     /// ```
225     /// use ylong_json::JsonValue;
226     ///
227     /// let boolean_value = JsonValue::new_boolean(true);
228     /// assert_eq!(boolean_value.is_boolean(), true);
229     ///
230     /// let other_value = JsonValue::new_null();
231     /// assert_eq!(other_value.is_boolean(), false);
232     /// ```
is_boolean(&self) -> bool233     pub fn is_boolean(&self) -> bool {
234         matches!(*self, Self::Boolean(_))
235     }
236 
237     /// Determines whether JsonValue is true. Returns true if yes, false if no.
238     ///
239     /// # Examples
240     /// ```
241     /// use ylong_json::JsonValue;
242     ///
243     /// let true_value = JsonValue::new_boolean(true);
244     /// assert_eq!(true_value.is_true(), true);
245     ///
246     /// let other_value = JsonValue::new_boolean(false);
247     /// assert_eq!(other_value.is_true(), false);
248     /// ```
is_true(&self) -> bool249     pub fn is_true(&self) -> bool {
250         match *self {
251             Self::Boolean(x) => x,
252             _ => false,
253         }
254     }
255 
256     /// Determines whether JsonValue is false. Returns true if yes, false if no.
257     ///
258     /// # Examples
259     /// ```
260     /// use ylong_json::JsonValue;
261     ///
262     /// let false_value = JsonValue::new_boolean(false);
263     /// assert_eq!(false_value.is_false(), true);
264     ///
265     /// let other_value = JsonValue::new_boolean(true);
266     /// assert_eq!(other_value.is_false(), false);
267     /// ```
is_false(&self) -> bool268     pub fn is_false(&self) -> bool {
269         match *self {
270             Self::Boolean(x) => !x,
271             _ => false,
272         }
273     }
274 
275     /// Determines whether JsonValue is Numerical type. Returns true if yes, false if no.
276     ///
277     /// # Examples
278     /// ```
279     /// use ylong_json::JsonValue;
280     ///
281     /// let number_value = JsonValue::new_number(0.0.into());
282     /// assert_eq!(number_value.is_number(), true);
283     ///
284     /// let other_value = JsonValue::new_null();
285     /// assert_eq!(other_value.is_number(), false);
286     /// ```
is_number(&self) -> bool287     pub fn is_number(&self) -> bool {
288         matches!(*self, Self::Number(_))
289     }
290 
291     /// Determines whether JsonValue is String type. Returns true if yes, false if no.
292     ///
293     /// # Examples
294     /// ```
295     /// use ylong_json::JsonValue;
296     ///
297     /// let string_value = JsonValue::new_string("Hello World");
298     /// assert_eq!(string_value.is_string(), true);
299     ///
300     /// let other_value = JsonValue::new_null();
301     /// assert_eq!(other_value.is_string(), false);
302     /// ```
is_string(&self) -> bool303     pub fn is_string(&self) -> bool {
304         matches!(*self, Self::String(_))
305     }
306 
307     /// Determines whether JsonValue is Array type. Returns true if yes, false if no.
308     ///
309     /// # Examples
310     /// ```
311     /// use ylong_json::{JsonValue, Array};
312     ///
313     /// let array_value = JsonValue::new_array(Array::new());
314     /// assert_eq!(array_value.is_array(), true);
315     ///
316     /// let other_value = JsonValue::new_null();
317     /// assert_eq!(other_value.is_array(), false);
318     /// ```
is_array(&self) -> bool319     pub fn is_array(&self) -> bool {
320         matches!(*self, Self::Array(_))
321     }
322 
323     /// Determines whether JsonValue is Object type. Returns true if yes, false if no.
324     ///
325     /// # Examples
326     /// ```
327     /// use ylong_json::{JsonValue, Object};
328     ///
329     /// let object_value = JsonValue::new_object(Object::new());
330     /// assert_eq!(object_value.is_object(), true);
331     ///
332     /// let other_value = JsonValue::new_null();
333     /// assert_eq!(other_value.is_object(), false);
334     /// ```
is_object(&self) -> bool335     pub fn is_object(&self) -> bool {
336         matches!(*self, Self::Object(_))
337     }
338 
339     /// Trys to convert JsonValue to a common reference of Boolean type. Conversion failure will return Error.
340     ///
341     /// # Examples
342     /// ```
343     /// use ylong_json::{JsonValue, Error};
344     ///
345     /// let boolean_value = JsonValue::new_boolean(true);
346     /// assert_eq!(boolean_value.try_as_boolean().unwrap(), &true);
347     ///
348     /// let other_value = JsonValue::new_null();
349     /// assert!(other_value.try_as_boolean().is_err());
350     /// ```
try_as_boolean(&self) -> Result<&bool, Error>351     pub fn try_as_boolean(&self) -> Result<&bool, Error> {
352         match self {
353             Self::Boolean(boolean) => Ok(boolean),
354             _ => Err(Error::TypeTransform),
355         }
356     }
357 
358     /// Trys to convert JsonValue to a common reference of Numerical type. Conversion failure will return Error.
359     ///
360     /// # Examples
361     /// ```
362     /// use ylong_json::{JsonValue, Number, Error};
363     ///
364     /// let number_value = JsonValue::new_number(0.0.into());
365     /// assert_eq!(number_value.try_as_number().unwrap(), &Number::from(0.0));
366     ///
367     /// let other_value = JsonValue::new_null();
368     /// assert!(other_value.try_as_number().is_err());
369     /// ```
try_as_number(&self) -> Result<&Number, Error>370     pub fn try_as_number(&self) -> Result<&Number, Error> {
371         match self {
372             Self::Number(number) => Ok(number),
373             _ => Err(Error::TypeTransform),
374         }
375     }
376 
377     /// Trys to convert JsonValue to a common reference of String type. Conversion failure will return Error.
378     ///
379     /// # Examples
380     /// ```no_run
381     /// #[cfg(feature = "c_adapter")]
382     /// use std::ffi::CString;
383     /// use ylong_json::{JsonValue, Error};
384     ///
385     /// let string_value = JsonValue::new_string("Hello World");
386     /// #[cfg(feature = "c_adapter")]
387     /// assert_eq!(string_value.try_as_string().unwrap(), &CString::new("Hello World").unwrap());
388     /// #[cfg(not(feature = "c_adapter"))]
389     /// assert_eq!(string_value.try_as_string().unwrap(), &String::from("Hello World"));
390     /// // When opening "c_adapter" feature, the underlying implementation is CString.
391     /// //assert_eq!(string_value.try_as_string().unwrap(), &CString::new("Hello World").unwrap());
392     ///
393     /// let other_value = JsonValue::new_null();
394     /// assert!(other_value.try_as_string().is_err());
395     /// ```
try_as_string(&self) -> Result<&JsonString, Error>396     pub fn try_as_string(&self) -> Result<&JsonString, Error> {
397         match self {
398             Self::String(string) => Ok(string),
399             _ => Err(Error::TypeTransform),
400         }
401     }
402 
403     /// Trys to convert JsonValue to a common reference of Array type. Conversion failure will return Error.
404     ///
405     /// # Examples
406     /// ```
407     /// use ylong_json::{JsonValue, Array, Error};
408     ///
409     /// let array_value = JsonValue::new_array(Array::new());
410     /// assert_eq!(array_value.try_as_array().unwrap(), &Array::new());
411     ///
412     /// let other_value = JsonValue::new_null();
413     /// assert!(other_value.try_as_array().is_err());
414     /// ```
try_as_array(&self) -> Result<&Array, Error>415     pub fn try_as_array(&self) -> Result<&Array, Error> {
416         match self {
417             Self::Array(array) => Ok(array),
418             _ => Err(Error::TypeTransform),
419         }
420     }
421 
422     /// Trys to convert JsonValue to a common reference of Object type. Conversion failure will return Error.
423     ///
424     /// # Examples
425     /// ```
426     /// use ylong_json::{JsonValue, Object, Error};
427     ///
428     /// let array_value = JsonValue::new_object(Object::new());
429     /// assert_eq!(array_value.try_as_object().unwrap(), &Object::new());
430     ///
431     /// let other_value = JsonValue::new_null();
432     /// assert!(other_value.try_as_object().is_err());
433     /// ```
try_as_object(&self) -> Result<&Object, Error>434     pub fn try_as_object(&self) -> Result<&Object, Error> {
435         match self {
436             Self::Object(object) => Ok(object),
437             _ => Err(Error::TypeTransform),
438         }
439     }
440 
441     /// Trys to convert JsonValue to a mutable reference of Boolean type. Conversion failure will return Error.
442     ///
443     /// # Examples
444     /// ```
445     /// use ylong_json::{JsonValue, Error};
446     ///
447     /// let mut boolean_value = JsonValue::new_boolean(true);
448     /// assert_eq!(boolean_value.try_as_mut_boolean().unwrap(), &mut true);
449     ///
450     /// let mut other_value = JsonValue::new_null();
451     /// assert!(other_value.try_as_mut_boolean().is_err());
452     /// ```
try_as_mut_boolean(&mut self) -> Result<&mut bool, Error>453     pub fn try_as_mut_boolean(&mut self) -> Result<&mut bool, Error> {
454         match self {
455             Self::Boolean(boolean) => Ok(boolean),
456             _ => Err(Error::TypeTransform),
457         }
458     }
459 
460     /// Trys to convert JsonValue to a mutable reference of Numerical type. Conversion failure will return Error.
461     ///
462     /// # Examples
463     /// ```
464     /// use ylong_json::{JsonValue, Number, Error};
465     ///
466     /// let mut number_value = JsonValue::new_number(0.0.into());
467     /// assert_eq!(number_value.try_as_mut_number().unwrap(), &mut Number::from(0.0));
468     ///
469     /// let mut other_value = JsonValue::new_null();
470     /// assert!(other_value.try_as_mut_number().is_err());
471     /// ```
try_as_mut_number(&mut self) -> Result<&mut Number, Error>472     pub fn try_as_mut_number(&mut self) -> Result<&mut Number, Error> {
473         match self {
474             Self::Number(number) => Ok(number),
475             _ => Err(Error::TypeTransform),
476         }
477     }
478 
479     /// Trys to convert JsonValue to a mutable reference of String type. Conversion failure will return Error.
480     ///
481     /// # Examples
482     /// ```no_run
483     /// #[cfg(feature = "c_adapter")]
484     /// use std::ffi::CString;
485     /// use ylong_json::{JsonValue, Error};
486     ///
487     /// let mut string_value = JsonValue::new_string("Hello World");
488     /// #[cfg(feature = "c_adapter")]
489     /// assert_eq!(string_value.try_as_mut_string().unwrap(), &mut CString::new("Hello World").unwrap());
490     /// #[cfg(not(feature = "c_adapter"))]
491     /// assert_eq!(string_value.try_as_mut_string().unwrap(), &mut String::from("Hello World"));
492     /// // When opening "c_adapter" feature, the underlying implementation is CString.
493     /// //assert_eq!(string_value.try_as_mut_string().unwrap(), &mut CString::new("Hello World").unwrap());
494     ///
495     /// let mut other_value = JsonValue::new_null();
496     /// assert!(other_value.try_as_mut_string().is_err());
497     /// ```
try_as_mut_string(&mut self) -> Result<&mut JsonString, Error>498     pub fn try_as_mut_string(&mut self) -> Result<&mut JsonString, Error> {
499         match self {
500             Self::String(string) => Ok(string),
501             _ => Err(Error::TypeTransform),
502         }
503     }
504 
505     /// Trys to convert JsonValue to a mutable reference of Array type. Conversion failure will return Error.
506     ///
507     /// # Examples
508     /// ```
509     /// use ylong_json::{JsonValue, Error, Array};
510     ///
511     /// let mut array_value = JsonValue::new_array(Array::new());
512     /// assert_eq!(array_value.try_as_mut_array().unwrap(), &mut Array::new());
513     ///
514     /// let mut other_value = JsonValue::new_null();
515     /// assert!(other_value.try_as_mut_array().is_err());
516     /// ```
try_as_mut_array(&mut self) -> Result<&mut Array, Error>517     pub fn try_as_mut_array(&mut self) -> Result<&mut Array, Error> {
518         match self {
519             Self::Array(array) => Ok(array),
520             _ => Err(Error::TypeTransform),
521         }
522     }
523 
524     /// Trys to convert JsonValue to a mutable reference of Object type. Conversion failure will return Error.
525     ///
526     /// # Examples
527     /// ```
528     /// use ylong_json::{JsonValue, Error, Object};
529     ///
530     /// let mut object_value = JsonValue::new_object(Object::new());
531     /// assert_eq!(object_value.try_as_mut_object().unwrap(), &mut Object::new());
532     ///
533     /// let mut other_value = JsonValue::new_null();
534     /// assert!(other_value.try_as_mut_object().is_err());
535     /// ```
try_as_mut_object(&mut self) -> Result<&mut Object, Error>536     pub fn try_as_mut_object(&mut self) -> Result<&mut Object, Error> {
537         match self {
538             Self::Object(object) => Ok(object),
539             _ => Err(Error::TypeTransform),
540         }
541     }
542 
543     /// Trys to convert JsonValue to Boolean type. This method transfers ownership.
544     /// Conversion failure will return Error.
545     ///
546     /// # Examples
547     /// ```
548     /// use ylong_json::{JsonValue, Error};
549     ///
550     /// let boolean_value = JsonValue::new_boolean(true);
551     /// assert_eq!(boolean_value.try_into_boolean().unwrap(), true);
552     ///
553     /// let other_value = JsonValue::new_null();
554     /// assert!(other_value.try_into_boolean().is_err());
555     /// ```
try_into_boolean(self) -> Result<bool, Error>556     pub fn try_into_boolean(self) -> Result<bool, Error> {
557         match self {
558             Self::Boolean(boolean) => Ok(boolean),
559             _ => Err(Error::TypeTransform),
560         }
561     }
562 
563     /// Trys to convert JsonValue to Numerical type. This method transfers ownership.
564     /// Conversion failure will return Error.
565     ///
566     /// The value will be output as f64. If you want to output other types, use 'as' to convert.
567     ///
568     /// # Examples
569     /// ```
570     /// use ylong_json::{JsonValue, Number, Error};
571     ///
572     /// let number_value = JsonValue::new_number(0.0.into());
573     /// assert_eq!(number_value.try_into_number().unwrap(), Number::from(0.0));
574     ///
575     /// let other_value = JsonValue::new_null();
576     /// assert!(other_value.try_into_number().is_err());
577     /// ```
try_into_number(self) -> Result<Number, Error>578     pub fn try_into_number(self) -> Result<Number, Error> {
579         match self {
580             Self::Number(number) => Ok(number),
581             _ => Err(Error::TypeTransform),
582         }
583     }
584 
585     /// Trys to convert JsonValue to String type. This method transfers ownership.
586     /// Conversion failure will return Error.
587     ///
588     /// # Examples
589     /// ```no_run
590     /// #[cfg(feature = "c_adapter")]
591     /// use std::ffi::CString;
592     /// use ylong_json::{JsonValue, Error};
593     ///
594     /// let string_value = JsonValue::new_string("Hello World");
595     /// #[cfg(feature = "c_adapter")]
596     /// assert_eq!(string_value.try_into_string().unwrap(), CString::new("Hello World").unwrap());
597     /// #[cfg(not(feature = "c_adapter"))]
598     /// assert_eq!(string_value.try_into_string().unwrap(), String::from("Hello World"));
599     /// // When opening "c_adapter" feature, the underlying implementation is CString.
600     /// //assert_eq!(string_value.try_into_string().unwrap(), CString::new("Hello World").unwrap());
601     ///
602     /// let other_value = JsonValue::new_null();
603     /// assert!(other_value.try_into_string().is_err());
604     /// ```
try_into_string(self) -> Result<JsonString, Error>605     pub fn try_into_string(self) -> Result<JsonString, Error> {
606         match self {
607             Self::String(string) => Ok(string),
608             _ => Err(Error::TypeTransform),
609         }
610     }
611 
612     /// Trys to convert JsonValue to Array type. This method transfers ownership.
613     /// Conversion failure will return Error.
614     ///
615     /// # Examples
616     /// ```
617     /// use ylong_json::{JsonValue, Error, Array};
618     ///
619     /// let array_value = JsonValue::new_array(Array::new());
620     /// assert_eq!(array_value.try_into_array().unwrap(), Array::new());
621     ///
622     /// let other_value = JsonValue::new_null();
623     /// assert!(other_value.try_into_array().is_err());
624     /// ```
try_into_array(self) -> Result<Array, Error>625     pub fn try_into_array(self) -> Result<Array, Error> {
626         match self {
627             Self::Array(array) => Ok(array),
628             _ => Err(Error::TypeTransform),
629         }
630     }
631 
632     /// Trys to convert JsonValue to Object type. This method transfers ownership.
633     /// Conversion failure will return Error.
634     ///
635     /// # Examples
636     /// ```
637     /// use ylong_json::{JsonValue, Error, Object};
638     ///
639     /// let object_value = JsonValue::new_object(Object::new());
640     /// assert_eq!(object_value.try_into_object().unwrap(), Object::new());
641     ///
642     /// let other_value = JsonValue::new_null();
643     /// assert!(other_value.try_into_object().is_err());
644     /// ```
try_into_object(self) -> Result<Object, Error>645     pub fn try_into_object(self) -> Result<Object, Error> {
646         match self {
647             Self::Object(object) => Ok(object),
648             _ => Err(Error::TypeTransform),
649         }
650     }
651 
652     /// Trys to remove a member form an Object or Array. If the member is found by Index,
653     /// gets value of the member from the Object or Array.
654     ///
655     /// # Examples
656     /// ```
657     /// use ylong_json::{Object, JsonValue};
658     ///
659     /// let mut object = Object::new();
660     /// object.insert(String::from("key"), "value".into());
661     ///
662     /// let mut value: JsonValue = object.into();
663     /// assert_eq!(value["key"], "value".into());
664     ///
665     /// value.remove("key");
666     /// assert_eq!(value["key"], JsonValue::Null);
667     /// ```
remove<I: index::Index>(&mut self, index: I) -> Option<JsonValue>668     pub fn remove<I: index::Index>(&mut self, index: I) -> Option<JsonValue> {
669         index.index_remove(self)
670     }
671 
672     /// Reads the contents from the file and Trys to deserialize to a JsonValue instance.
673     ///
674     /// # Examples
675     /// ```not run
676     /// use ylong_json::JsonValue;
677     ///
678     /// let value = JsonValue::from_file("./json.txt").unwrap();
679     /// ```
680     #[cfg(not(feature = "c_adapter"))]
from_file<P: AsRef<Path>>(path: P) -> Result<Self, Error>681     pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
682         let mut file = File::open(path.as_ref())?;
683         Self::from_reader(&mut file)
684     }
685 
686     /// Gets the text from an object that implements the Read trait provided
687     /// by the standard library and Trys to deserialize it into a JsonValue instance.
688     ///
689     /// # Examples
690     /// ```not run
691     /// use ylong_json::JsonValue;
692     /// use std::fs::File;
693     ///
694     /// let mut file = File::open("./json.txt").unwrap();
695     /// let value = JsonValue::from_reader(&mut file).unwrap();
696     /// ```
from_reader<R: Read>(input: R) -> Result<Self, Error>697     pub fn from_reader<R: Read>(input: R) -> Result<Self, Error> {
698         let mut deserializer = Deserializer::new_from_io(input);
699         start_parsing(&mut deserializer)
700     }
701 
702     /// Reads the text from a type that can be converted to [u8] and Trys to deserialize it to a Json instance.
703     ///
704     /// # Examples
705     /// ```
706     /// use ylong_json::JsonValue;
707     ///
708     /// let text = r#"
709     /// {
710     ///     "key": "value"
711     /// }
712     /// "#;
713     /// let value = JsonValue::from_text(text.as_bytes()).unwrap();
714     ///
715     /// assert_eq!(value["key"], "value".into());
716     /// ```
from_text<T: AsRef<[u8]>>(text: T) -> Result<Self, Error>717     pub fn from_text<T: AsRef<[u8]>>(text: T) -> Result<Self, Error> {
718         let mut deserializer = Deserializer::new_from_slice(text.as_ref());
719         start_parsing(&mut deserializer)
720     }
721 
722     /// Serializes the JsonValue instance to a formatted string with additional whitespace characters.
723     ///
724     /// # Examples
725     /// ```
726     /// use ylong_json::JsonValue;
727     ///
728     /// let text = r#"{
729     ///     "key": "value"
730     /// }
731     /// "#;
732     /// let value = JsonValue::from_text(text.as_bytes()).unwrap();
733     /// let string = value.to_formatted_string().unwrap();
734     /// assert_eq!(string, text);
735     /// ```
to_formatted_string(&self) -> Result<std::string::String, Error>736     pub fn to_formatted_string(&self) -> Result<std::string::String, Error> {
737         let mut vec = Vec::new();
738         self.formatted_encode(&mut vec)?;
739         Ok(unsafe { std::string::String::from_utf8_unchecked(vec) })
740     }
741 
742     /// Serializes the JsonValue instance to a one-line string with no additional whitespace.
743     ///
744     /// # Examples
745     /// ```
746     /// use ylong_json::JsonValue;
747     ///
748     /// let text = r#"{"key":"value"}"#;
749     /// let value = JsonValue::from_text(text.as_bytes()).unwrap();
750     /// let string = value.to_compact_string().unwrap();
751     /// assert_eq!(string, text);
752     /// ```
to_compact_string(&self) -> Result<std::string::String, Error>753     pub fn to_compact_string(&self) -> Result<std::string::String, Error> {
754         let mut vec = Vec::new();
755         self.compact_encode(&mut vec)?;
756         Ok(unsafe { std::string::String::from_utf8_unchecked(vec) })
757     }
758 
759     /// Serializes the JsonValue instance to a formatted string with additional whitespace characters.
760     /// And outputs to the specified location as a stream of bytes.
761     ///
762     /// # Examples
763     /// ```
764     /// use ylong_json::JsonValue;
765     ///
766     /// let text = r#"{
767     ///     "key": "value"
768     /// }
769     /// "#;
770     /// let value = JsonValue::from_text(text.as_bytes()).unwrap();
771     /// let mut vec = Vec::new();
772     /// value.formatted_encode(&mut vec).unwrap();
773     /// assert_eq!(vec, text.as_bytes());
774     /// ```
formatted_encode<W: Write>(&self, output: &mut W) -> Result<(), Error>775     pub fn formatted_encode<W: Write>(&self, output: &mut W) -> Result<(), Error> {
776         let mut encoder = FormattedEncoder::new(output);
777         encoder.encode(self)
778     }
779 
780     /// Serializes the JsonValue instance to a one-line string with no additional whitespace.
781     /// And outputs to the specified location as a stream of bytes.
782     ///
783     /// # Examples
784     /// ```
785     /// use ylong_json::JsonValue;
786     ///
787     /// let text = r#"{"key":"value"}"#;
788     /// let value = JsonValue::from_text(text.as_bytes()).unwrap();
789     /// let mut vec = Vec::new();
790     /// value.compact_encode(&mut vec).unwrap();
791     /// assert_eq!(vec, text.as_bytes());
792     /// ```
compact_encode<W: Write>(&self, output: &mut W) -> Result<(), Error>793     pub fn compact_encode<W: Write>(&self, output: &mut W) -> Result<(), Error> {
794         let mut encoder = CompactEncoder::new(output);
795         encoder.encode(self)
796     }
797 }
798 
799 impl FromStr for JsonValue {
800     type Err = Error;
801 
802     /// Generates an instance of JsonValue from &str.
803     ///
804     /// # Examples
805     /// ```
806     /// use core::str::FromStr;
807     /// use ylong_json::JsonValue;
808     ///
809     /// let text = r#"
810     /// {
811     ///     "key": "value"
812     /// }
813     /// "#;
814     /// let value = JsonValue::from_str(text).unwrap();
815     ///
816     /// assert_eq!(value["key"], "value".into());
817     /// ```
from_str(s: &str) -> Result<Self, Self::Err>818     fn from_str(s: &str) -> Result<Self, Self::Err> {
819         Self::from_text(s)
820     }
821 }
822 
823 impl PartialEq for JsonValue {
824     /// Determines whether two Jsonvalues are equal.
825     /// Only the same type can be compared; different types simply return false.
826     ///
827     /// If types are the same, false is returned only if the internal variables are exactly equal.
828     /// For example, when comparing arrays, two Arrays are considered equal
829     /// only if all their JsonValues have the same position and value.
830     /// When comparing objects, two Objects are considered equal
831     /// only if all of their key/value pairs match one another.
832     ///
833     /// # Examples
834     /// ```
835     /// use ylong_json::{JsonValue, Array, Object};
836     ///
837     /// assert_eq!(JsonValue::new_null(), JsonValue::new_null());
838     /// assert_eq!(JsonValue::new_boolean(true), JsonValue::new_boolean(true));
839     /// assert_eq!(JsonValue::new_number(0.0.into()), JsonValue::new_number(0.0.into()));
840     /// assert_eq!(JsonValue::new_string(""), JsonValue::new_string(""));
841     /// assert_eq!(JsonValue::new_array(Array::new()), JsonValue::new_array(Array::new()));
842     /// assert_eq!(JsonValue::new_object(Object::new()), JsonValue::new_object(Object::new()));
843     ///
844     /// assert_ne!(JsonValue::new_null(), JsonValue::new_number(0.0.into()));
845     /// assert_ne!(JsonValue::new_boolean(true), JsonValue::new_boolean(false));
846     ///
847     /// let mut array1 = Array::new();
848     /// array1.push(JsonValue::new_null());
849     ///
850     /// let mut array2 = Array::new();
851     /// array2.push(JsonValue::new_number(0.0.into()));
852     /// assert_ne!(JsonValue::new_array(array1), JsonValue::new_array(array2));
853     ///
854     /// let mut object1 = Object::new();
855     /// object1.insert(String::from("Key"), JsonValue::new_null());
856     ///
857     /// let mut object2 = Object::new();
858     /// object2.insert(String::from("Key"), JsonValue::new_number(0.0.into()));
859     /// assert_ne!(JsonValue::new_object(object1), JsonValue::new_object(object2));
860     /// ```
eq(&self, other: &Self) -> bool861     fn eq(&self, other: &Self) -> bool {
862         match (self, other) {
863             (JsonValue::Null, JsonValue::Null) => true,
864             (JsonValue::Boolean(a), JsonValue::Boolean(b)) => a == b,
865             (JsonValue::Number(a), JsonValue::Number(b)) => a == b,
866             (JsonValue::String(a), JsonValue::String(b)) => a == b,
867             (JsonValue::Array(a), JsonValue::Array(b)) => a == b,
868             (JsonValue::Object(a), JsonValue::Object(b)) => a == b,
869             _ => false,
870         }
871     }
872 }
873 
874 impl<I: index::Index> core::ops::Index<I> for JsonValue {
875     type Output = JsonValue;
876 
index(&self, index: I) -> &Self::Output877     fn index(&self, index: I) -> &Self::Output {
878         index.index_into(self)
879     }
880 }
881 
882 impl<I: index::Index> core::ops::IndexMut<I> for JsonValue {
index_mut(&mut self, index: I) -> &mut Self::Output883     fn index_mut(&mut self, index: I) -> &mut Self::Output {
884         index.index_into_mut(self)
885     }
886 }
887 
888 impl From<&str> for JsonValue {
889     /// Converts from &str to JsonValue.
890     ///
891     /// # Examples
892     /// ```
893     /// use ylong_json::JsonValue;
894     ///
895     /// let value: JsonValue = "Hello World".into();
896     /// ```
from(t: &str) -> Self897     fn from(t: &str) -> Self {
898         #[cfg(feature = "c_adapter")]
899         let result = Self::String(JsonString::new(t).unwrap());
900 
901         #[cfg(not(feature = "c_adapter"))]
902         let result = Self::String(String::from(t));
903         result
904     }
905 }
906 
907 impl From<JsonString> for JsonValue {
908     /// Converts from String to JsonValue.
909     ///
910     /// # Examples
911     /// ```not run
912     /// use ylong_json::JsonValue;
913     ///
914     /// // Unused "c_adapter" feature.
915     /// let value: JsonValue = String::from("Hello World").into();
916     /// // Uses "c_adapter" feature.
917     /// // let value: JsonValue = CString::new("Hello World").into();
918     /// ```
from(t: JsonString) -> Self919     fn from(t: JsonString) -> Self {
920         Self::String(t)
921     }
922 }
923 
924 macro_rules! json_value_from_type {
925     ($type: tt, $func: expr) => {
926         impl From<$type> for JsonValue {
927             #[doc = concat!("从 ", stringify!($type), " 转换为 JsonValue。")]
928             ///
929             /// # Examples
930             /// ```
931             /// use ylong_json::*;
932             ///
933             #[doc = concat!("let value: JsonValue = ", stringify!($type), "::default().into();")]
934             /// ```
935             fn from(t: $type) -> Self {
936                 $func(t.into())
937             }
938         }
939 
940         impl From<&$type> for JsonValue {
941             #[doc = concat!("从 &", stringify!($type), " 转换为 JsonValue。")]
942             ///
943             /// # Examples
944             /// ```
945             /// use ylong_json::*;
946             ///
947             #[doc = concat!("let value: JsonValue = ", stringify!($type), "::default().into();")]
948             /// ```
949             fn from(t: &$type) -> Self {
950                 $func(t.clone().into())
951             }
952         }
953 
954         impl From<&mut $type> for JsonValue {
955             #[doc = concat!("从 &mut", stringify!($type), " 转换为 JsonValue。")]
956             ///
957             /// # Examples
958             /// ```
959             /// use ylong_json::*;
960             ///
961             #[doc = concat!("let value: JsonValue = ", stringify!($type), "::default().into();")]
962             /// ```
963             fn from(t: &mut $type) -> Self {
964                 $func(t.clone().into())
965             }
966         }
967     };
968 }
969 
970 macro_rules! number_value_from_type {
971     ($($type: tt),* $(,)?) => {
972         $(
973             impl From<$type> for JsonValue {
974                 #[doc = concat!("从 ", stringify!($type), " 转换为 JsonValue。")]
975                 ///
976                 /// # Examples
977                 /// ```
978                 /// use ylong_json::JsonValue;
979                 ///
980                 /// // Due to the conversion to f64, there may be a loss of accuracy.
981                 #[doc = concat!("let value: JsonValue = ", stringify!($type), "::MAX.into();")]
982                 /// ```
983                 fn from(t: $type) -> Self {
984                     Self::Number(Number::from(t))
985                 }
986             }
987         )*
988     }
989 }
990 
991 json_value_from_type!(bool, JsonValue::new_boolean);
992 json_value_from_type!(Array, JsonValue::new_array);
993 json_value_from_type!(Object, JsonValue::new_object);
994 
995 number_value_from_type!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize, f32, f64);
996 
997 #[cfg(test)]
998 mod ut_json_value {
999     use super::{array::Array, object::Object, JsonValue};
1000     use std::io::{ErrorKind, Read, Result};
1001     use std::str::FromStr;
1002 
1003     /// UT test for `JsonValue::fmt`.
1004     ///
1005     /// # Title
1006     /// ut_json_value_fmt
1007     ///
1008     /// # Brief
1009     /// 1. Creates some `JsonValue`s.
1010     /// 2. Calls `Display::fmt` and `Debug::fmt`.
1011     /// 3. Checks if the test results are correct.
1012     #[test]
ut_json_value_fmt()1013     fn ut_json_value_fmt() {
1014         let value = JsonValue::new_null();
1015         assert_eq!(format!("{value}"), "null");
1016         assert_eq!(format!("{value:?}"), "null");
1017 
1018         let value = JsonValue::new_boolean(false);
1019         assert_eq!(format!("{value}"), "false");
1020         assert_eq!(format!("{value:?}"), "false");
1021 
1022         let value = JsonValue::new_number(12.34.into());
1023         assert_eq!(format!("{value}"), "12.34");
1024         assert_eq!(format!("{value:?}"), "12.34");
1025 
1026         let value = JsonValue::new_string("Hello");
1027         assert_eq!(format!("{value}"), "\"Hello\"");
1028         assert_eq!(format!("{value:?}"), "\"Hello\"");
1029 
1030         let value = JsonValue::new_array(array!(false, JsonValue::Null, 12.34));
1031         assert_eq!(format!("{value}"), "[false,null,12.34]");
1032         assert_eq!(format!("{value}"), "[false,null,12.34]");
1033 
1034         let object = object!("null" => JsonValue::Null);
1035         let value = JsonValue::new_object(object);
1036         assert_eq!(format!("{value}"), "{\"null\":null}");
1037         assert_eq!(format!("{value}"), "{\"null\":null}");
1038     }
1039 
1040     /// UT test for `JsonValue::clone`.
1041     ///
1042     /// # Title
1043     /// ut_json_value_fmt
1044     ///
1045     /// # Brief
1046     /// 1. Creates some `JsonValue`s.
1047     /// 2. Calls `JsonValue::clone`.
1048     /// 3. Checks if the test results are correct.
1049     #[test]
ut_json_value_clone()1050     fn ut_json_value_clone() {
1051         let value1 = JsonValue::new_null();
1052         assert_eq!(value1, value1.clone());
1053     }
1054 
1055     /// UT test for `JsonValue::is_null`.
1056     ///
1057     /// # Title
1058     /// ut_json_value_is_null
1059     ///
1060     /// # Brief
1061     /// 1. Creates some `JsonValue`s.
1062     /// 2. Calls `JsonValue::is_null`.
1063     /// 3. Checks if the test results are correct.
1064     #[test]
ut_json_value_is_null()1065     fn ut_json_value_is_null() {
1066         assert!(JsonValue::new_null().is_null());
1067         assert!(!JsonValue::new_boolean(true).is_null());
1068         assert!(!JsonValue::new_boolean(false).is_null());
1069         assert!(!JsonValue::new_number(12.34.into()).is_null());
1070         assert!(!JsonValue::new_string("hello").is_null());
1071         assert!(!JsonValue::new_array(Array::new()).is_null());
1072         assert!(!JsonValue::new_object(Object::new()).is_null());
1073     }
1074 
1075     /// UT test for `JsonValue::is_true`.
1076     ///
1077     /// # Title
1078     /// ut_json_value_is_true
1079     ///
1080     /// # Brief
1081     /// 1. Creates some `JsonValue`s.
1082     /// 2. Calls `JsonValue::is_true`.
1083     /// 3. Checks if the test results are correct.
1084     #[test]
ut_json_value_is_true()1085     fn ut_json_value_is_true() {
1086         assert!(!JsonValue::new_null().is_true());
1087         assert!(JsonValue::new_boolean(true).is_true());
1088         assert!(!JsonValue::new_boolean(false).is_true());
1089         assert!(!JsonValue::new_number(12.34.into()).is_true());
1090         assert!(!JsonValue::new_string("hello").is_true());
1091         assert!(!JsonValue::new_array(Array::new()).is_true());
1092         assert!(!JsonValue::new_object(Object::new()).is_true());
1093     }
1094 
1095     /// UT test for `JsonValue::is_false`.
1096     ///
1097     /// # Title
1098     /// ut_json_value_is_false
1099     ///
1100     /// # Brief
1101     /// 1. Creates some `JsonValue`s.
1102     /// 2. Calls `JsonValue::is_false`.
1103     /// 3. Checks if the test results are correct.
1104     #[test]
ut_json_value_is_false()1105     fn ut_json_value_is_false() {
1106         assert!(!JsonValue::new_null().is_false());
1107         assert!(!JsonValue::new_boolean(true).is_false());
1108         assert!(JsonValue::new_boolean(false).is_false());
1109         assert!(!JsonValue::new_number(12.34.into()).is_false());
1110         assert!(!JsonValue::new_string("hello").is_false());
1111         assert!(!JsonValue::new_array(Array::new()).is_false());
1112         assert!(!JsonValue::new_object(Object::new()).is_false());
1113     }
1114 
1115     /// UT test for `JsonValue::is_boolean`.
1116     ///
1117     /// # Title
1118     /// ut_json_value_is_false
1119     ///
1120     /// # Brief
1121     /// 1. Creates some `JsonValue`s.
1122     /// 2. Calls `JsonValue::is_boolean`.
1123     /// 3. Checks if the test results are correct.
1124     #[test]
ut_json_value_is_boolean()1125     fn ut_json_value_is_boolean() {
1126         assert!(!JsonValue::new_null().is_boolean());
1127         assert!(JsonValue::new_boolean(true).is_boolean());
1128         assert!(JsonValue::new_boolean(false).is_boolean());
1129         assert!(!JsonValue::new_number(12.34.into()).is_boolean());
1130         assert!(!JsonValue::new_string("hello").is_boolean());
1131         assert!(!JsonValue::new_array(Array::new()).is_boolean());
1132         assert!(!JsonValue::new_object(Object::new()).is_boolean());
1133     }
1134 
1135     /// UT test for `JsonValue::is_number`.
1136     ///
1137     /// # Title
1138     /// ut_json_value_is_number
1139     ///
1140     /// # Brief
1141     /// 1. Creates some `JsonValue`s.
1142     /// 2. Calls `JsonValue::is_number`.
1143     /// 3. Checks if the test results are correct.
1144     #[test]
ut_json_value_is_number()1145     fn ut_json_value_is_number() {
1146         assert!(!JsonValue::new_null().is_number());
1147         assert!(!JsonValue::new_boolean(true).is_number());
1148         assert!(!JsonValue::new_boolean(false).is_number());
1149         assert!(JsonValue::new_number(12.34.into()).is_number());
1150         assert!(!JsonValue::new_string("hello").is_number());
1151         assert!(!JsonValue::new_array(Array::new()).is_number());
1152         assert!(!JsonValue::new_object(Object::new()).is_number());
1153     }
1154 
1155     /// UT test for `JsonValue::is_string`.
1156     ///
1157     /// # Title
1158     /// ut_json_value_is_string
1159     ///
1160     /// # Brief
1161     /// 1. Creates some `JsonValue`s.
1162     /// 2. Calls `JsonValue::is_string`.
1163     /// 3. Checks if the test results are correct.
1164     #[test]
ut_json_value_is_string()1165     fn ut_json_value_is_string() {
1166         assert!(!JsonValue::new_null().is_string());
1167         assert!(!JsonValue::new_boolean(true).is_string());
1168         assert!(!JsonValue::new_boolean(false).is_string());
1169         assert!(!JsonValue::new_number(12.34.into()).is_string());
1170         assert!(JsonValue::new_string("hello").is_string());
1171         assert!(!JsonValue::new_array(Array::new()).is_string());
1172         assert!(!JsonValue::new_object(Object::new()).is_string());
1173     }
1174 
1175     /// UT test for `JsonValue::is_array`.
1176     ///
1177     /// # Title
1178     /// ut_json_value_is_array
1179     ///
1180     /// # Brief
1181     /// 1. Creates some `JsonValue`s.
1182     /// 2. Calls `JsonValue::is_array`.
1183     /// 3. Checks if the test results are correct.
1184     #[test]
ut_json_value_is_array()1185     fn ut_json_value_is_array() {
1186         assert!(!JsonValue::new_null().is_array());
1187         assert!(!JsonValue::new_boolean(true).is_array());
1188         assert!(!JsonValue::new_boolean(false).is_array());
1189         assert!(!JsonValue::new_number(12.34.into()).is_array());
1190         assert!(!JsonValue::new_string("hello").is_array());
1191         assert!(JsonValue::new_array(Array::new()).is_array());
1192         assert!(!JsonValue::new_object(Object::new()).is_array());
1193     }
1194 
1195     /// UT test for `JsonValue::is_object`.
1196     ///
1197     /// # Title
1198     /// ut_json_value_is_object
1199     ///
1200     /// # Brief
1201     /// 1. Creates some `JsonValue`s.
1202     /// 2. Calls `JsonValue::is_object`.
1203     /// 3. Checks if the test results are correct.
1204     #[test]
ut_json_value_is_object()1205     fn ut_json_value_is_object() {
1206         assert!(!JsonValue::new_null().is_object());
1207         assert!(!JsonValue::new_boolean(true).is_object());
1208         assert!(!JsonValue::new_boolean(false).is_object());
1209         assert!(!JsonValue::new_number(12.34.into()).is_object());
1210         assert!(!JsonValue::new_string("hello").is_object());
1211         assert!(!JsonValue::new_array(Array::new()).is_object());
1212         assert!(JsonValue::new_object(Object::new()).is_object());
1213     }
1214 
1215     /// UT test for `JsonValue::try_as_boolean`.
1216     ///
1217     /// # Title
1218     /// ut_json_value_try_as_boolean
1219     ///
1220     /// # Brief
1221     /// 1. Creates some `JsonValue`s.
1222     /// 2. Calls `JsonValue::try_as_boolean`.
1223     /// 3. Checks if the test results are correct.
1224     #[test]
ut_json_value_try_as_boolean()1225     fn ut_json_value_try_as_boolean() {
1226         assert!(JsonValue::new_null().try_as_boolean().is_err());
1227         assert!(JsonValue::new_boolean(true).try_as_boolean().is_ok());
1228         assert!(JsonValue::new_boolean(false).try_as_boolean().is_ok());
1229         assert!(JsonValue::new_number(12.34.into())
1230             .try_as_boolean()
1231             .is_err());
1232         assert!(JsonValue::new_string("hello").try_as_boolean().is_err());
1233         assert!(JsonValue::new_array(Array::new()).try_as_boolean().is_err());
1234         assert!(JsonValue::new_object(Object::new())
1235             .try_as_boolean()
1236             .is_err());
1237     }
1238 
1239     /// UT test for `JsonValue::try_as_number`.
1240     ///
1241     /// # Title
1242     /// ut_json_value_try_as_number
1243     ///
1244     /// # Brief
1245     /// 1. Creates some `JsonValue`s.
1246     /// 2. Calls `JsonValue::try_as_number`.
1247     /// 3. Checks if the test results are correct.
1248     #[test]
ut_json_value_try_as_number()1249     fn ut_json_value_try_as_number() {
1250         assert!(JsonValue::new_null().try_as_number().is_err());
1251         assert!(JsonValue::new_boolean(true).try_as_number().is_err());
1252         assert!(JsonValue::new_boolean(false).try_as_number().is_err());
1253         assert!(JsonValue::new_number(12.34.into()).try_as_number().is_ok());
1254         assert!(JsonValue::new_string("hello").try_as_number().is_err());
1255         assert!(JsonValue::new_array(Array::new()).try_as_number().is_err());
1256         assert!(JsonValue::new_object(Object::new())
1257             .try_as_number()
1258             .is_err());
1259     }
1260 
1261     /// UT test for `JsonValue::try_as_string`.
1262     ///
1263     /// # Title
1264     /// ut_json_value_try_as_string
1265     ///
1266     /// # Brief
1267     /// 1. Creates some `JsonValue`s.
1268     /// 2. Calls `JsonValue::try_as_string`.
1269     /// 3. Checks if the test results are correct.
1270     #[test]
ut_json_value_try_as_string()1271     fn ut_json_value_try_as_string() {
1272         assert!(JsonValue::new_null().try_as_string().is_err());
1273         assert!(JsonValue::new_boolean(true).try_as_string().is_err());
1274         assert!(JsonValue::new_boolean(false).try_as_string().is_err());
1275         assert!(JsonValue::new_number(12.34.into()).try_as_string().is_err());
1276         assert!(JsonValue::new_string("hello").try_as_string().is_ok());
1277         assert!(JsonValue::new_array(Array::new()).try_as_string().is_err());
1278         assert!(JsonValue::new_object(Object::new())
1279             .try_as_string()
1280             .is_err());
1281     }
1282 
1283     /// UT test for `JsonValue::try_as_array`.
1284     ///
1285     /// # Title
1286     /// ut_json_value_try_as_array
1287     ///
1288     /// # Brief
1289     /// 1. Creates some `JsonValue`s.
1290     /// 2. Calls `JsonValue::try_as_array`.
1291     /// 3. Checks if the test results are correct.
1292     #[test]
ut_json_value_try_as_array()1293     fn ut_json_value_try_as_array() {
1294         assert!(JsonValue::new_null().try_as_array().is_err());
1295         assert!(JsonValue::new_boolean(true).try_as_array().is_err());
1296         assert!(JsonValue::new_boolean(false).try_as_array().is_err());
1297         assert!(JsonValue::new_number(12.34.into()).try_as_array().is_err());
1298         assert!(JsonValue::new_string("hello").try_as_array().is_err());
1299         assert!(JsonValue::new_array(Array::new()).try_as_array().is_ok());
1300         assert!(JsonValue::new_object(Object::new()).try_as_array().is_err());
1301     }
1302 
1303     /// UT test for `JsonValue::try_as_object`.
1304     ///
1305     /// # Title
1306     /// ut_json_value_try_as_object
1307     ///
1308     /// # Brief
1309     /// 1. Creates some `JsonValue`s.
1310     /// 2. Calls `JsonValue::try_as_object`.
1311     /// 3. Checks if the test results are correct.
1312     #[test]
ut_json_value_try_as_object()1313     fn ut_json_value_try_as_object() {
1314         assert!(JsonValue::new_null().try_as_object().is_err());
1315         assert!(JsonValue::new_boolean(true).try_as_object().is_err());
1316         assert!(JsonValue::new_boolean(false).try_as_object().is_err());
1317         assert!(JsonValue::new_number(12.34.into()).try_as_object().is_err());
1318         assert!(JsonValue::new_string("hello").try_as_object().is_err());
1319         assert!(JsonValue::new_array(Array::new()).try_as_object().is_err());
1320         assert!(JsonValue::new_object(Object::new()).try_as_object().is_ok());
1321     }
1322 
1323     /// UT test for `JsonValue::try_as_mut_boolean`.
1324     ///
1325     /// # Title
1326     /// ut_json_value_try_as_mut_boolean
1327     ///
1328     /// # Brief
1329     /// 1. Creates some `JsonValue`s.
1330     /// 2. Calls `JsonValue::try_as_mut_boolean`.
1331     /// 3. Checks if the test results are correct.
1332     #[test]
ut_json_value_try_as_mut_boolean()1333     fn ut_json_value_try_as_mut_boolean() {
1334         assert!(JsonValue::new_null().try_as_mut_boolean().is_err());
1335         assert!(JsonValue::new_boolean(true).try_as_mut_boolean().is_ok());
1336         assert!(JsonValue::new_boolean(false).try_as_mut_boolean().is_ok());
1337         assert!(JsonValue::new_number(12.34.into())
1338             .try_as_mut_boolean()
1339             .is_err());
1340         assert!(JsonValue::new_string("hello").try_as_mut_boolean().is_err());
1341         assert!(JsonValue::new_array(Array::new())
1342             .try_as_mut_boolean()
1343             .is_err());
1344         assert!(JsonValue::new_object(Object::new())
1345             .try_as_mut_boolean()
1346             .is_err());
1347     }
1348 
1349     /// UT test for `JsonValue::try_as_mut_number`.
1350     ///
1351     /// # Title
1352     /// ut_json_value_try_as_mut_number
1353     ///
1354     /// # Brief
1355     /// 1. Creates some `JsonValue`s.
1356     /// 2. Calls `JsonValue::try_as_mut_number`.
1357     /// 3. Checks if the test results are correct.
1358     #[test]
ut_json_value_try_as_mut_number()1359     fn ut_json_value_try_as_mut_number() {
1360         assert!(JsonValue::new_null().try_as_mut_number().is_err());
1361         assert!(JsonValue::new_boolean(true).try_as_mut_number().is_err());
1362         assert!(JsonValue::new_boolean(false).try_as_mut_number().is_err());
1363         assert!(JsonValue::new_number(12.34.into())
1364             .try_as_mut_number()
1365             .is_ok());
1366         assert!(JsonValue::new_string("hello").try_as_mut_number().is_err());
1367         assert!(JsonValue::new_array(Array::new())
1368             .try_as_mut_number()
1369             .is_err());
1370         assert!(JsonValue::new_object(Object::new())
1371             .try_as_mut_number()
1372             .is_err());
1373     }
1374 
1375     /// UT test for `JsonValue::try_as_mut_string`.
1376     ///
1377     /// # Title
1378     /// ut_json_value_try_as_mut_string
1379     ///
1380     /// # Brief
1381     /// 1. Creates some `JsonValue`s.
1382     /// 2. Calls `JsonValue::try_as_mut_string`.
1383     /// 3. Checks if the test results are correct.
1384     #[test]
ut_json_value_try_as_mut_string()1385     fn ut_json_value_try_as_mut_string() {
1386         assert!(JsonValue::new_null().try_as_mut_string().is_err());
1387         assert!(JsonValue::new_boolean(true).try_as_mut_string().is_err());
1388         assert!(JsonValue::new_boolean(false).try_as_mut_string().is_err());
1389         assert!(JsonValue::new_number(12.34.into())
1390             .try_as_mut_string()
1391             .is_err());
1392         assert!(JsonValue::new_string("hello").try_as_mut_string().is_ok());
1393         assert!(JsonValue::new_array(Array::new())
1394             .try_as_mut_string()
1395             .is_err());
1396         assert!(JsonValue::new_object(Object::new())
1397             .try_as_mut_string()
1398             .is_err());
1399     }
1400 
1401     /// UT test for `JsonValue::try_as_mut_array`.
1402     ///
1403     /// # Title
1404     /// ut_json_value_try_as_mut_array
1405     ///
1406     /// # Brief
1407     /// 1. Creates some `JsonValue`s.
1408     /// 2. Calls `JsonValue::try_as_mut_array`.
1409     /// 3. Checks if the test results are correct.
1410     #[test]
ut_json_value_try_as_mut_array()1411     fn ut_json_value_try_as_mut_array() {
1412         assert!(JsonValue::new_null().try_as_mut_array().is_err());
1413         assert!(JsonValue::new_boolean(true).try_as_mut_array().is_err());
1414         assert!(JsonValue::new_boolean(false).try_as_mut_array().is_err());
1415         assert!(JsonValue::new_number(12.34.into())
1416             .try_as_mut_array()
1417             .is_err());
1418         assert!(JsonValue::new_string("hello").try_as_mut_array().is_err());
1419         assert!(JsonValue::new_array(Array::new())
1420             .try_as_mut_array()
1421             .is_ok());
1422         assert!(JsonValue::new_object(Object::new())
1423             .try_as_mut_array()
1424             .is_err());
1425     }
1426 
1427     /// UT test for `JsonValue::try_as_mut_object`.
1428     ///
1429     /// # Title
1430     /// ut_json_value_try_as_mut_object
1431     ///
1432     /// # Brief
1433     /// 1. Creates some `JsonValue`s.
1434     /// 2. Calls `JsonValue::try_as_mut_object`.
1435     /// 3. Checks if the test results are correct.
1436     #[test]
ut_json_value_try_as_mut_object()1437     fn ut_json_value_try_as_mut_object() {
1438         assert!(JsonValue::new_null().try_as_mut_object().is_err());
1439         assert!(JsonValue::new_boolean(true).try_as_mut_object().is_err());
1440         assert!(JsonValue::new_boolean(false).try_as_mut_object().is_err());
1441         assert!(JsonValue::new_number(12.34.into())
1442             .try_as_mut_object()
1443             .is_err());
1444         assert!(JsonValue::new_string("hello").try_as_mut_object().is_err());
1445         assert!(JsonValue::new_array(Array::new())
1446             .try_as_mut_object()
1447             .is_err());
1448         assert!(JsonValue::new_object(Object::new())
1449             .try_as_mut_object()
1450             .is_ok());
1451     }
1452 
1453     /// UT test for `JsonValue::try_into_boolean`.
1454     ///
1455     /// # Title
1456     /// ut_json_value_try_into_boolean
1457     ///
1458     /// # Brief
1459     /// 1. Creates some `JsonValue`s.
1460     /// 2. Calls `JsonValue::try_into_boolean`.
1461     /// 3. Checks if the test results are correct.
1462     #[test]
ut_json_value_try_into_boolean()1463     fn ut_json_value_try_into_boolean() {
1464         assert!(JsonValue::new_null().try_into_boolean().is_err());
1465         assert!(JsonValue::new_boolean(true).try_into_boolean().is_ok());
1466         assert!(JsonValue::new_boolean(false).try_into_boolean().is_ok());
1467         assert!(JsonValue::new_number(12.34.into())
1468             .try_into_boolean()
1469             .is_err());
1470         assert!(JsonValue::new_string("hello").try_into_boolean().is_err());
1471         assert!(JsonValue::new_array(Array::new())
1472             .try_into_boolean()
1473             .is_err());
1474         assert!(JsonValue::new_object(Object::new())
1475             .try_into_boolean()
1476             .is_err());
1477     }
1478 
1479     /// UT test for `JsonValue::try_into_number`.
1480     ///
1481     /// # Title
1482     /// ut_json_value_try_into_number
1483     ///
1484     /// # Brief
1485     /// 1. Creates some `JsonValue`s.
1486     /// 2. Calls `JsonValue::try_into_number`.
1487     /// 3. Checks if the test results are correct.
1488     #[test]
ut_json_value_try_into_number()1489     fn ut_json_value_try_into_number() {
1490         assert!(JsonValue::new_null().try_into_number().is_err());
1491         assert!(JsonValue::new_boolean(true).try_into_number().is_err());
1492         assert!(JsonValue::new_boolean(false).try_into_number().is_err());
1493         assert!(JsonValue::new_number(12.34.into())
1494             .try_into_number()
1495             .is_ok());
1496         assert!(JsonValue::new_string("hello").try_into_number().is_err());
1497         assert!(JsonValue::new_array(Array::new())
1498             .try_into_number()
1499             .is_err());
1500         assert!(JsonValue::new_object(Object::new())
1501             .try_into_number()
1502             .is_err());
1503     }
1504 
1505     /// UT test for `JsonValue::try_into_string`.
1506     ///
1507     /// # Title
1508     /// ut_json_value_try_into_string
1509     ///
1510     /// # Brief
1511     /// 1. Creates some `JsonValue`s.
1512     /// 2. Calls `JsonValue::try_into_string`.
1513     /// 3. Checks if the test results are correct.
1514     #[test]
ut_json_value_try_into_string()1515     fn ut_json_value_try_into_string() {
1516         assert!(JsonValue::new_null().try_into_string().is_err());
1517         assert!(JsonValue::new_boolean(true).try_into_string().is_err());
1518         assert!(JsonValue::new_boolean(false).try_into_string().is_err());
1519         assert!(JsonValue::new_number(12.34.into())
1520             .try_into_string()
1521             .is_err());
1522         assert!(JsonValue::new_string("hello").try_into_string().is_ok());
1523         assert!(JsonValue::new_array(Array::new())
1524             .try_into_string()
1525             .is_err());
1526         assert!(JsonValue::new_object(Object::new())
1527             .try_into_string()
1528             .is_err());
1529     }
1530 
1531     /// UT test for `JsonValue::try_into_array`.
1532     ///
1533     /// # Title
1534     /// ut_json_value_try_into_array
1535     ///
1536     /// # Brief
1537     /// 1. Creates some `JsonValue`s.
1538     /// 2. Calls `JsonValue::try_into_array`.
1539     /// 3. Checks if the test results are correct.
1540     #[test]
ut_json_value_try_into_array()1541     fn ut_json_value_try_into_array() {
1542         assert!(JsonValue::new_null().try_into_array().is_err());
1543         assert!(JsonValue::new_boolean(true).try_into_array().is_err());
1544         assert!(JsonValue::new_boolean(false).try_into_array().is_err());
1545         assert!(JsonValue::new_number(12.34.into())
1546             .try_into_array()
1547             .is_err());
1548         assert!(JsonValue::new_string("hello").try_into_array().is_err());
1549         assert!(JsonValue::new_array(Array::new()).try_into_array().is_ok());
1550         assert!(JsonValue::new_object(Object::new())
1551             .try_into_array()
1552             .is_err());
1553     }
1554 
1555     /// UT test for `JsonValue::try_into_object`.
1556     ///
1557     /// # Title
1558     /// ut_json_value_try_into_object
1559     ///
1560     /// # Brief
1561     /// 1. Creates some `JsonValue`s.
1562     /// 2. Calls `JsonValue::try_into_object`.
1563     /// 3. Checks if the test results are correct.
1564     #[test]
ut_json_value_try_into_object()1565     fn ut_json_value_try_into_object() {
1566         assert!(JsonValue::new_null().try_into_object().is_err());
1567         assert!(JsonValue::new_boolean(true).try_into_object().is_err());
1568         assert!(JsonValue::new_boolean(false).try_into_object().is_err());
1569         assert!(JsonValue::new_number(12.34.into())
1570             .try_into_object()
1571             .is_err());
1572         assert!(JsonValue::new_string("hello").try_into_object().is_err());
1573         assert!(JsonValue::new_array(Array::new())
1574             .try_into_object()
1575             .is_err());
1576         assert!(JsonValue::new_object(Object::new())
1577             .try_into_object()
1578             .is_ok());
1579     }
1580 
1581     /// UT test for `JsonValue::to_formatted_string`.
1582     ///
1583     /// # Title
1584     /// ut_json_value_to_formatted_string
1585     ///
1586     /// # Brief
1587     /// 1. Creates some `JsonValue`s.
1588     /// 2. Calls `JsonValue::to_formatted_string`.
1589     /// 3. Checks if the test results are correct.
1590     #[test]
ut_json_value_to_formatted_string()1591     fn ut_json_value_to_formatted_string() {
1592         assert_eq!(
1593             JsonValue::new_null().to_formatted_string().unwrap(),
1594             "null\n"
1595         );
1596     }
1597 
1598     /// UT test for `JsonValue::to_compact_string`.
1599     ///
1600     /// # Title
1601     /// ut_json_value_to_compact_string
1602     ///
1603     /// # Brief
1604     /// 1. Creates some `JsonValue`s.
1605     /// 2. Calls `JsonValue::to_compact_string`.
1606     /// 3. Checks if the test results are correct.
1607     #[test]
ut_json_value_to_compact_string()1608     fn ut_json_value_to_compact_string() {
1609         assert_eq!(JsonValue::new_null().to_compact_string().unwrap(), "null");
1610     }
1611 
1612     /// UT test for `JsonValue::from_str`.
1613     ///
1614     /// # Title
1615     /// ut_json_value_from_str
1616     ///
1617     /// # Brief
1618     /// 1. Calls `JsonValue::from_str` to create a `JsonValue`.
1619     /// 2. Checks if the test results are correct.
1620     #[test]
ut_json_value_from_str()1621     fn ut_json_value_from_str() {
1622         assert_eq!(JsonValue::from_str("null").unwrap(), JsonValue::new_null());
1623     }
1624 
1625     /// UT test for `JsonValue::eq`.
1626     ///
1627     /// # Title
1628     /// ut_json_value_eq
1629     ///
1630     /// # Brief
1631     /// 1. Creates some `JsonValue`s.
1632     /// 2. Calls `JsonValue::eq`.
1633     /// 3. Checks if the test results are correct.
1634     #[test]
ut_json_value_eq()1635     fn ut_json_value_eq() {
1636         assert_eq!(JsonValue::new_null(), JsonValue::new_null());
1637         assert_eq!(JsonValue::new_boolean(true), JsonValue::new_boolean(true));
1638         assert_eq!(
1639             JsonValue::new_number(1.into()),
1640             JsonValue::new_number(1.into())
1641         );
1642         assert_eq!(
1643             JsonValue::new_string("string"),
1644             JsonValue::new_string("string")
1645         );
1646         assert_eq!(
1647             JsonValue::new_array(Array::new()),
1648             JsonValue::new_array(Array::new())
1649         );
1650         assert_eq!(
1651             JsonValue::new_object(Object::new()),
1652             JsonValue::new_object(Object::new())
1653         );
1654         assert_ne!(JsonValue::new_null(), JsonValue::new_boolean(true));
1655     }
1656 
1657     /// UT test for `JsonValue::from`.
1658     ///
1659     /// # Title
1660     /// ut_json_value_from
1661     ///
1662     /// # Brief
1663     /// 1. Calls `JsonValue::from` to create `JsonValue`s.
1664     /// 2. Checks if the test results are correct.
1665     #[test]
ut_json_value_from()1666     fn ut_json_value_from() {
1667         assert_eq!(JsonValue::from(true), JsonValue::new_boolean(true));
1668         assert_eq!(JsonValue::from(false), JsonValue::new_boolean(false));
1669         assert_eq!(
1670             JsonValue::from(Array::new()),
1671             JsonValue::new_array(Array::new())
1672         );
1673         assert_eq!(
1674             JsonValue::from(Object::new()),
1675             JsonValue::new_object(Object::new())
1676         );
1677 
1678         assert_eq!(JsonValue::from(&true), JsonValue::new_boolean(true));
1679         assert_eq!(JsonValue::from(&false), JsonValue::new_boolean(false));
1680         assert_eq!(
1681             JsonValue::from(&Array::new()),
1682             JsonValue::new_array(Array::new())
1683         );
1684         assert_eq!(
1685             JsonValue::from(&Object::new()),
1686             JsonValue::new_object(Object::new())
1687         );
1688 
1689         assert_eq!(JsonValue::from(&mut true), JsonValue::new_boolean(true));
1690         assert_eq!(JsonValue::from(&mut false), JsonValue::new_boolean(false));
1691         assert_eq!(
1692             JsonValue::from(&mut Array::new()),
1693             JsonValue::new_array(Array::new())
1694         );
1695         assert_eq!(
1696             JsonValue::from(&mut Object::new()),
1697             JsonValue::new_object(Object::new())
1698         );
1699 
1700         #[cfg(not(feature = "c_adapter"))]
1701         assert_eq!(JsonValue::from(String::new()), JsonValue::new_string(""));
1702 
1703         #[cfg(feature = "c_adapter")]
1704         {
1705             use std::ffi::CString;
1706             assert_eq!(
1707                 JsonValue::from(CString::new("").unwrap()),
1708                 JsonValue::new_string("")
1709             );
1710         }
1711     }
1712 
1713     /// UT test for `JsonValue::remove`.
1714     ///
1715     /// # Title
1716     /// ut_json_value_remove
1717     ///
1718     /// # Brief
1719     /// 1. Creates some `JsonValue`.
1720     /// 2. Calls `JsonValue::remove` on them.
1721     /// 3. Checks if the test results are correct.
1722     #[test]
ut_json_value_remove()1723     fn ut_json_value_remove() {
1724         let mut object = JsonValue::new_object(
1725             object!("key1" => "value1"; "key2" => "value2"; "key3" => "value3"),
1726         );
1727         assert_eq!(object["key1"], JsonValue::new_string("value1"));
1728         assert_eq!(object["key2"], JsonValue::new_string("value2"));
1729         assert_eq!(object["key3"], JsonValue::new_string("value3"));
1730 
1731         object.remove("key2");
1732         assert_eq!(object["key1"], JsonValue::new_string("value1"));
1733         assert_eq!(object["key2"], JsonValue::new_null());
1734         assert_eq!(object["key3"], JsonValue::new_string("value3"));
1735 
1736         let mut array = JsonValue::new_array(array!(false, JsonValue::new_null(), 12.34));
1737         assert_eq!(array[0], JsonValue::new_boolean(false));
1738         assert_eq!(array[1], JsonValue::new_null());
1739         assert_eq!(array[2], JsonValue::new_number(12.34.into()));
1740 
1741         array.remove(1);
1742         assert_eq!(array[0], JsonValue::new_boolean(false));
1743         assert_eq!(array[1], JsonValue::new_number(12.34.into()));
1744         assert_eq!(array[2], JsonValue::new_null());
1745     }
1746 
1747     /// UT test for `JsonValue::from_reader`.
1748     ///
1749     /// # Title
1750     /// ut_json_value_from_reader
1751     ///
1752     /// # Brief
1753     /// 1. Calls `JsonValue::from_reader` to create some `JsonValue`.
1754     /// 2. Checks if the test results are correct.
1755     #[test]
ut_json_value_from_reader()1756     fn ut_json_value_from_reader() {
1757         struct TestErrorIo;
1758 
1759         impl Read for TestErrorIo {
1760             fn read(&mut self, _buf: &mut [u8]) -> Result<usize> {
1761                 Err(ErrorKind::AddrInUse.into())
1762             }
1763         }
1764 
1765         assert!(JsonValue::from_reader(TestErrorIo).is_err());
1766     }
1767 }
1768