1 #![cfg(not(feature = "preserve_order"))]
2 #![allow(
3     clippy::assertions_on_result_states,
4     clippy::cast_precision_loss,
5     clippy::derive_partial_eq_without_eq,
6     clippy::excessive_precision,
7     clippy::float_cmp,
8     clippy::items_after_statements,
9     clippy::let_underscore_untyped,
10     clippy::shadow_unrelated,
11     clippy::too_many_lines,
12     clippy::unreadable_literal,
13     clippy::unseparated_literal_suffix,
14     clippy::vec_init_then_push,
15     clippy::zero_sized_map_values
16 )]
17 #![cfg_attr(feature = "trace-macros", feature(trace_macros))]
18 #[cfg(feature = "trace-macros")]
19 trace_macros!(true);
20 
21 #[macro_use]
22 mod macros;
23 
24 #[cfg(feature = "raw_value")]
25 use ref_cast::RefCast;
26 use serde::de::{self, IgnoredAny, IntoDeserializer};
27 use serde::ser::{self, SerializeMap, SerializeSeq, Serializer};
28 use serde::{Deserialize, Serialize};
29 use serde_bytes::{ByteBuf, Bytes};
30 #[cfg(feature = "raw_value")]
31 use serde_json::value::RawValue;
32 use serde_json::{
33     from_reader, from_slice, from_str, from_value, json, to_string, to_string_pretty, to_value,
34     to_vec, Deserializer, Number, Value,
35 };
36 use std::collections::hash_map::DefaultHasher;
37 use std::collections::BTreeMap;
38 #[cfg(feature = "raw_value")]
39 use std::collections::HashMap;
40 use std::fmt::{self, Debug};
41 use std::hash::{Hash, Hasher};
42 use std::io;
43 use std::iter;
44 use std::marker::PhantomData;
45 use std::mem;
46 use std::str::FromStr;
47 use std::string::ToString;
48 use std::{f32, f64};
49 use std::{i16, i32, i64, i8};
50 use std::{u16, u32, u64, u8};
51 
52 macro_rules! treemap {
53     () => {
54         BTreeMap::new()
55     };
56     ($($k:expr => $v:expr),+) => {
57         {
58             let mut m = BTreeMap::new();
59             $(
60                 m.insert($k, $v);
61             )+
62             m
63         }
64     };
65 }
66 
67 #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
68 #[serde(deny_unknown_fields)]
69 enum Animal {
70     Dog,
71     Frog(String, Vec<isize>),
72     Cat { age: usize, name: String },
73     AntHive(Vec<String>),
74 }
75 
76 #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
77 struct Inner {
78     a: (),
79     b: usize,
80     c: Vec<String>,
81 }
82 
83 #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
84 struct Outer {
85     inner: Vec<Inner>,
86 }
87 
test_encode_ok<T>(errors: &[(T, &str)]) where T: PartialEq + Debug + ser::Serialize,88 fn test_encode_ok<T>(errors: &[(T, &str)])
89 where
90     T: PartialEq + Debug + ser::Serialize,
91 {
92     for &(ref value, out) in errors {
93         let out = out.to_string();
94 
95         let s = to_string(value).unwrap();
96         assert_eq!(s, out);
97 
98         let v = to_value(value).unwrap();
99         let s = to_string(&v).unwrap();
100         assert_eq!(s, out);
101     }
102 }
103 
test_pretty_encode_ok<T>(errors: &[(T, &str)]) where T: PartialEq + Debug + ser::Serialize,104 fn test_pretty_encode_ok<T>(errors: &[(T, &str)])
105 where
106     T: PartialEq + Debug + ser::Serialize,
107 {
108     for &(ref value, out) in errors {
109         let out = out.to_string();
110 
111         let s = to_string_pretty(value).unwrap();
112         assert_eq!(s, out);
113 
114         let v = to_value(value).unwrap();
115         let s = to_string_pretty(&v).unwrap();
116         assert_eq!(s, out);
117     }
118 }
119 
120 #[test]
test_write_null()121 fn test_write_null() {
122     let tests = &[((), "null")];
123     test_encode_ok(tests);
124     test_pretty_encode_ok(tests);
125 }
126 
127 #[test]
test_write_u64()128 fn test_write_u64() {
129     let tests = &[(3u64, "3"), (u64::MAX, &u64::MAX.to_string())];
130     test_encode_ok(tests);
131     test_pretty_encode_ok(tests);
132 }
133 
134 #[test]
test_write_i64()135 fn test_write_i64() {
136     let tests = &[
137         (3i64, "3"),
138         (-2i64, "-2"),
139         (-1234i64, "-1234"),
140         (i64::MIN, &i64::MIN.to_string()),
141     ];
142     test_encode_ok(tests);
143     test_pretty_encode_ok(tests);
144 }
145 
146 #[test]
test_write_f64()147 fn test_write_f64() {
148     let tests = &[
149         (3.0, "3.0"),
150         (3.1, "3.1"),
151         (-1.5, "-1.5"),
152         (0.5, "0.5"),
153         (f64::MIN, "-1.7976931348623157e308"),
154         (f64::MAX, "1.7976931348623157e308"),
155         (f64::EPSILON, "2.220446049250313e-16"),
156     ];
157     test_encode_ok(tests);
158     test_pretty_encode_ok(tests);
159 }
160 
161 #[test]
test_encode_nonfinite_float_yields_null()162 fn test_encode_nonfinite_float_yields_null() {
163     let v = to_value(::std::f64::NAN).unwrap();
164     assert!(v.is_null());
165 
166     let v = to_value(::std::f64::INFINITY).unwrap();
167     assert!(v.is_null());
168 
169     let v = to_value(::std::f32::NAN).unwrap();
170     assert!(v.is_null());
171 
172     let v = to_value(::std::f32::INFINITY).unwrap();
173     assert!(v.is_null());
174 }
175 
176 #[test]
test_write_str()177 fn test_write_str() {
178     let tests = &[("", "\"\""), ("foo", "\"foo\"")];
179     test_encode_ok(tests);
180     test_pretty_encode_ok(tests);
181 }
182 
183 #[test]
test_write_bool()184 fn test_write_bool() {
185     let tests = &[(true, "true"), (false, "false")];
186     test_encode_ok(tests);
187     test_pretty_encode_ok(tests);
188 }
189 
190 #[test]
test_write_char()191 fn test_write_char() {
192     let tests = &[
193         ('n', "\"n\""),
194         ('"', "\"\\\"\""),
195         ('\\', "\"\\\\\""),
196         ('/', "\"/\""),
197         ('\x08', "\"\\b\""),
198         ('\x0C', "\"\\f\""),
199         ('\n', "\"\\n\""),
200         ('\r', "\"\\r\""),
201         ('\t', "\"\\t\""),
202         ('\x0B', "\"\\u000b\""),
203         ('\u{3A3}', "\"\u{3A3}\""),
204     ];
205     test_encode_ok(tests);
206     test_pretty_encode_ok(tests);
207 }
208 
209 #[test]
test_write_list()210 fn test_write_list() {
211     test_encode_ok(&[
212         (vec![], "[]"),
213         (vec![true], "[true]"),
214         (vec![true, false], "[true,false]"),
215     ]);
216 
217     test_encode_ok(&[
218         (vec![vec![], vec![], vec![]], "[[],[],[]]"),
219         (vec![vec![1, 2, 3], vec![], vec![]], "[[1,2,3],[],[]]"),
220         (vec![vec![], vec![1, 2, 3], vec![]], "[[],[1,2,3],[]]"),
221         (vec![vec![], vec![], vec![1, 2, 3]], "[[],[],[1,2,3]]"),
222     ]);
223 
224     test_pretty_encode_ok(&[
225         (vec![vec![], vec![], vec![]], pretty_str!([[], [], []])),
226         (
227             vec![vec![1, 2, 3], vec![], vec![]],
228             pretty_str!([[1, 2, 3], [], []]),
229         ),
230         (
231             vec![vec![], vec![1, 2, 3], vec![]],
232             pretty_str!([[], [1, 2, 3], []]),
233         ),
234         (
235             vec![vec![], vec![], vec![1, 2, 3]],
236             pretty_str!([[], [], [1, 2, 3]]),
237         ),
238     ]);
239 
240     test_pretty_encode_ok(&[
241         (vec![], "[]"),
242         (vec![true], pretty_str!([true])),
243         (vec![true, false], pretty_str!([true, false])),
244     ]);
245 
246     let long_test_list = json!([false, null, ["foo\nbar", 3.5]]);
247 
248     test_encode_ok(&[(
249         long_test_list.clone(),
250         json_str!([false, null, ["foo\nbar", 3.5]]),
251     )]);
252 
253     test_pretty_encode_ok(&[(
254         long_test_list,
255         pretty_str!([false, null, ["foo\nbar", 3.5]]),
256     )]);
257 }
258 
259 #[test]
test_write_object()260 fn test_write_object() {
261     test_encode_ok(&[
262         (treemap!(), "{}"),
263         (treemap!("a".to_string() => true), "{\"a\":true}"),
264         (
265             treemap!(
266                 "a".to_string() => true,
267                 "b".to_string() => false
268             ),
269             "{\"a\":true,\"b\":false}",
270         ),
271     ]);
272 
273     test_encode_ok(&[
274         (
275             treemap![
276                 "a".to_string() => treemap![],
277                 "b".to_string() => treemap![],
278                 "c".to_string() => treemap![]
279             ],
280             "{\"a\":{},\"b\":{},\"c\":{}}",
281         ),
282         (
283             treemap![
284                 "a".to_string() => treemap![
285                     "a".to_string() => treemap!["a" => vec![1,2,3]],
286                     "b".to_string() => treemap![],
287                     "c".to_string() => treemap![]
288                 ],
289                 "b".to_string() => treemap![],
290                 "c".to_string() => treemap![]
291             ],
292             "{\"a\":{\"a\":{\"a\":[1,2,3]},\"b\":{},\"c\":{}},\"b\":{},\"c\":{}}",
293         ),
294         (
295             treemap![
296                 "a".to_string() => treemap![],
297                 "b".to_string() => treemap![
298                     "a".to_string() => treemap!["a" => vec![1,2,3]],
299                     "b".to_string() => treemap![],
300                     "c".to_string() => treemap![]
301                 ],
302                 "c".to_string() => treemap![]
303             ],
304             "{\"a\":{},\"b\":{\"a\":{\"a\":[1,2,3]},\"b\":{},\"c\":{}},\"c\":{}}",
305         ),
306         (
307             treemap![
308                 "a".to_string() => treemap![],
309                 "b".to_string() => treemap![],
310                 "c".to_string() => treemap![
311                     "a".to_string() => treemap!["a" => vec![1,2,3]],
312                     "b".to_string() => treemap![],
313                     "c".to_string() => treemap![]
314                 ]
315             ],
316             "{\"a\":{},\"b\":{},\"c\":{\"a\":{\"a\":[1,2,3]},\"b\":{},\"c\":{}}}",
317         ),
318     ]);
319 
320     test_encode_ok(&[(treemap!['c' => ()], "{\"c\":null}")]);
321 
322     test_pretty_encode_ok(&[
323         (
324             treemap![
325                 "a".to_string() => treemap![],
326                 "b".to_string() => treemap![],
327                 "c".to_string() => treemap![]
328             ],
329             pretty_str!({
330                 "a": {},
331                 "b": {},
332                 "c": {}
333             }),
334         ),
335         (
336             treemap![
337                 "a".to_string() => treemap![
338                     "a".to_string() => treemap!["a" => vec![1,2,3]],
339                     "b".to_string() => treemap![],
340                     "c".to_string() => treemap![]
341                 ],
342                 "b".to_string() => treemap![],
343                 "c".to_string() => treemap![]
344             ],
345             pretty_str!({
346                 "a": {
347                     "a": {
348                         "a": [
349                             1,
350                             2,
351                             3
352                         ]
353                     },
354                     "b": {},
355                     "c": {}
356                 },
357                 "b": {},
358                 "c": {}
359             }),
360         ),
361         (
362             treemap![
363                 "a".to_string() => treemap![],
364                 "b".to_string() => treemap![
365                     "a".to_string() => treemap!["a" => vec![1,2,3]],
366                     "b".to_string() => treemap![],
367                     "c".to_string() => treemap![]
368                 ],
369                 "c".to_string() => treemap![]
370             ],
371             pretty_str!({
372                 "a": {},
373                 "b": {
374                     "a": {
375                         "a": [
376                             1,
377                             2,
378                             3
379                         ]
380                     },
381                     "b": {},
382                     "c": {}
383                 },
384                 "c": {}
385             }),
386         ),
387         (
388             treemap![
389                 "a".to_string() => treemap![],
390                 "b".to_string() => treemap![],
391                 "c".to_string() => treemap![
392                     "a".to_string() => treemap!["a" => vec![1,2,3]],
393                     "b".to_string() => treemap![],
394                     "c".to_string() => treemap![]
395                 ]
396             ],
397             pretty_str!({
398                 "a": {},
399                 "b": {},
400                 "c": {
401                     "a": {
402                         "a": [
403                             1,
404                             2,
405                             3
406                         ]
407                     },
408                     "b": {},
409                     "c": {}
410                 }
411             }),
412         ),
413     ]);
414 
415     test_pretty_encode_ok(&[
416         (treemap!(), "{}"),
417         (
418             treemap!("a".to_string() => true),
419             pretty_str!({
420                 "a": true
421             }),
422         ),
423         (
424             treemap!(
425                 "a".to_string() => true,
426                 "b".to_string() => false
427             ),
428             pretty_str!( {
429                 "a": true,
430                 "b": false
431             }),
432         ),
433     ]);
434 
435     let complex_obj = json!({
436         "b": [
437             {"c": "\x0c\x1f\r"},
438             {"d": ""}
439         ]
440     });
441 
442     test_encode_ok(&[(
443         complex_obj.clone(),
444         json_str!({
445             "b": [
446                 {
447                     "c": (r#""\f\u001f\r""#)
448                 },
449                 {
450                     "d": ""
451                 }
452             ]
453         }),
454     )]);
455 
456     test_pretty_encode_ok(&[(
457         complex_obj,
458         pretty_str!({
459             "b": [
460                 {
461                     "c": (r#""\f\u001f\r""#)
462                 },
463                 {
464                     "d": ""
465                 }
466             ]
467         }),
468     )]);
469 }
470 
471 #[test]
test_write_tuple()472 fn test_write_tuple() {
473     test_encode_ok(&[((5,), "[5]")]);
474 
475     test_pretty_encode_ok(&[((5,), pretty_str!([5]))]);
476 
477     test_encode_ok(&[((5, (6, "abc")), "[5,[6,\"abc\"]]")]);
478 
479     test_pretty_encode_ok(&[((5, (6, "abc")), pretty_str!([5, [6, "abc"]]))]);
480 }
481 
482 #[test]
test_write_enum()483 fn test_write_enum() {
484     test_encode_ok(&[
485         (Animal::Dog, "\"Dog\""),
486         (
487             Animal::Frog("Henry".to_string(), vec![]),
488             "{\"Frog\":[\"Henry\",[]]}",
489         ),
490         (
491             Animal::Frog("Henry".to_string(), vec![349]),
492             "{\"Frog\":[\"Henry\",[349]]}",
493         ),
494         (
495             Animal::Frog("Henry".to_string(), vec![349, 102]),
496             "{\"Frog\":[\"Henry\",[349,102]]}",
497         ),
498         (
499             Animal::Cat {
500                 age: 5,
501                 name: "Kate".to_string(),
502             },
503             "{\"Cat\":{\"age\":5,\"name\":\"Kate\"}}",
504         ),
505         (
506             Animal::AntHive(vec!["Bob".to_string(), "Stuart".to_string()]),
507             "{\"AntHive\":[\"Bob\",\"Stuart\"]}",
508         ),
509     ]);
510 
511     test_pretty_encode_ok(&[
512         (Animal::Dog, "\"Dog\""),
513         (
514             Animal::Frog("Henry".to_string(), vec![]),
515             pretty_str!({
516                 "Frog": [
517                     "Henry",
518                     []
519                 ]
520             }),
521         ),
522         (
523             Animal::Frog("Henry".to_string(), vec![349]),
524             pretty_str!({
525                 "Frog": [
526                     "Henry",
527                     [
528                         349
529                     ]
530                 ]
531             }),
532         ),
533         (
534             Animal::Frog("Henry".to_string(), vec![349, 102]),
535             pretty_str!({
536                 "Frog": [
537                     "Henry",
538                     [
539                       349,
540                       102
541                     ]
542                 ]
543             }),
544         ),
545     ]);
546 }
547 
548 #[test]
test_write_option()549 fn test_write_option() {
550     test_encode_ok(&[(None, "null"), (Some("jodhpurs"), "\"jodhpurs\"")]);
551 
552     test_encode_ok(&[
553         (None, "null"),
554         (Some(vec!["foo", "bar"]), "[\"foo\",\"bar\"]"),
555     ]);
556 
557     test_pretty_encode_ok(&[(None, "null"), (Some("jodhpurs"), "\"jodhpurs\"")]);
558 
559     test_pretty_encode_ok(&[
560         (None, "null"),
561         (Some(vec!["foo", "bar"]), pretty_str!(["foo", "bar"])),
562     ]);
563 }
564 
565 #[test]
test_write_newtype_struct()566 fn test_write_newtype_struct() {
567     #[derive(Serialize, PartialEq, Debug)]
568     struct Newtype(BTreeMap<String, i32>);
569 
570     let inner = Newtype(treemap!(String::from("inner") => 123));
571     let outer = treemap!(String::from("outer") => to_value(&inner).unwrap());
572 
573     test_encode_ok(&[(inner, r#"{"inner":123}"#)]);
574 
575     test_encode_ok(&[(outer, r#"{"outer":{"inner":123}}"#)]);
576 }
577 
578 #[test]
test_deserialize_number_to_untagged_enum()579 fn test_deserialize_number_to_untagged_enum() {
580     #[derive(Eq, PartialEq, Deserialize, Debug)]
581     #[serde(untagged)]
582     enum E {
583         N(i64),
584     }
585 
586     assert_eq!(E::N(0), E::deserialize(Number::from(0)).unwrap());
587 }
588 
test_parse_ok<T>(tests: Vec<(&str, T)>) where T: Clone + Debug + PartialEq + ser::Serialize + de::DeserializeOwned,589 fn test_parse_ok<T>(tests: Vec<(&str, T)>)
590 where
591     T: Clone + Debug + PartialEq + ser::Serialize + de::DeserializeOwned,
592 {
593     for (s, value) in tests {
594         let v: T = from_str(s).unwrap();
595         assert_eq!(v, value.clone());
596 
597         let v: T = from_slice(s.as_bytes()).unwrap();
598         assert_eq!(v, value.clone());
599 
600         // Make sure we can deserialize into a `Value`.
601         let json_value: Value = from_str(s).unwrap();
602         assert_eq!(json_value, to_value(&value).unwrap());
603 
604         // Make sure we can deserialize from a `&Value`.
605         let v = T::deserialize(&json_value).unwrap();
606         assert_eq!(v, value);
607 
608         // Make sure we can deserialize from a `Value`.
609         let v: T = from_value(json_value.clone()).unwrap();
610         assert_eq!(v, value);
611 
612         // Make sure we can round trip back to `Value`.
613         let json_value2: Value = from_value(json_value.clone()).unwrap();
614         assert_eq!(json_value2, json_value);
615 
616         // Make sure we can fully ignore.
617         let twoline = s.to_owned() + "\n3735928559";
618         let mut de = Deserializer::from_str(&twoline);
619         IgnoredAny::deserialize(&mut de).unwrap();
620         assert_eq!(0xDEAD_BEEF, u64::deserialize(&mut de).unwrap());
621 
622         // Make sure every prefix is an EOF error, except that a prefix of a
623         // number may be a valid number.
624         if !json_value.is_number() {
625             for (i, _) in s.trim_end().char_indices() {
626                 assert!(from_str::<Value>(&s[..i]).unwrap_err().is_eof());
627                 assert!(from_str::<IgnoredAny>(&s[..i]).unwrap_err().is_eof());
628             }
629         }
630     }
631 }
632 
633 // For testing representations that the deserializer accepts but the serializer
634 // never generates. These do not survive a round-trip through Value.
test_parse_unusual_ok<T>(tests: Vec<(&str, T)>) where T: Clone + Debug + PartialEq + ser::Serialize + de::DeserializeOwned,635 fn test_parse_unusual_ok<T>(tests: Vec<(&str, T)>)
636 where
637     T: Clone + Debug + PartialEq + ser::Serialize + de::DeserializeOwned,
638 {
639     for (s, value) in tests {
640         let v: T = from_str(s).unwrap();
641         assert_eq!(v, value.clone());
642 
643         let v: T = from_slice(s.as_bytes()).unwrap();
644         assert_eq!(v, value.clone());
645     }
646 }
647 
648 macro_rules! test_parse_err {
649     ($name:ident::<$($ty:ty),*>($arg:expr) => $expected:expr) => {
650         let actual = $name::<$($ty),*>($arg).unwrap_err().to_string();
651         assert_eq!(actual, $expected, "unexpected {} error", stringify!($name));
652     };
653 }
654 
test_parse_err<T>(errors: &[(&str, &'static str)]) where T: Debug + PartialEq + de::DeserializeOwned,655 fn test_parse_err<T>(errors: &[(&str, &'static str)])
656 where
657     T: Debug + PartialEq + de::DeserializeOwned,
658 {
659     for &(s, err) in errors {
660         test_parse_err!(from_str::<T>(s) => err);
661         test_parse_err!(from_slice::<T>(s.as_bytes()) => err);
662     }
663 }
664 
test_parse_slice_err<T>(errors: &[(&[u8], &'static str)]) where T: Debug + PartialEq + de::DeserializeOwned,665 fn test_parse_slice_err<T>(errors: &[(&[u8], &'static str)])
666 where
667     T: Debug + PartialEq + de::DeserializeOwned,
668 {
669     for &(s, err) in errors {
670         test_parse_err!(from_slice::<T>(s) => err);
671     }
672 }
673 
test_fromstr_parse_err<T>(errors: &[(&str, &'static str)]) where T: Debug + PartialEq + FromStr, <T as FromStr>::Err: ToString,674 fn test_fromstr_parse_err<T>(errors: &[(&str, &'static str)])
675 where
676     T: Debug + PartialEq + FromStr,
677     <T as FromStr>::Err: ToString,
678 {
679     for &(s, err) in errors {
680         let actual = s.parse::<T>().unwrap_err().to_string();
681         assert_eq!(actual, err, "unexpected parsing error");
682     }
683 }
684 
685 #[test]
test_parse_null()686 fn test_parse_null() {
687     test_parse_err::<()>(&[
688         ("n", "EOF while parsing a value at line 1 column 1"),
689         ("nul", "EOF while parsing a value at line 1 column 3"),
690         ("nulla", "trailing characters at line 1 column 5"),
691     ]);
692 
693     test_parse_ok(vec![("null", ())]);
694 }
695 
696 #[test]
test_parse_bool()697 fn test_parse_bool() {
698     test_parse_err::<bool>(&[
699         ("t", "EOF while parsing a value at line 1 column 1"),
700         ("truz", "expected ident at line 1 column 4"),
701         ("f", "EOF while parsing a value at line 1 column 1"),
702         ("faz", "expected ident at line 1 column 3"),
703         ("truea", "trailing characters at line 1 column 5"),
704         ("falsea", "trailing characters at line 1 column 6"),
705     ]);
706 
707     test_parse_ok(vec![
708         ("true", true),
709         (" true ", true),
710         ("false", false),
711         (" false ", false),
712     ]);
713 }
714 
715 #[test]
test_parse_char()716 fn test_parse_char() {
717     test_parse_err::<char>(&[
718         (
719             "\"ab\"",
720             "invalid value: string \"ab\", expected a character at line 1 column 4",
721         ),
722         (
723             "10",
724             "invalid type: integer `10`, expected a character at line 1 column 2",
725         ),
726     ]);
727 
728     test_parse_ok(vec![
729         ("\"n\"", 'n'),
730         ("\"\\\"\"", '"'),
731         ("\"\\\\\"", '\\'),
732         ("\"/\"", '/'),
733         ("\"\\b\"", '\x08'),
734         ("\"\\f\"", '\x0C'),
735         ("\"\\n\"", '\n'),
736         ("\"\\r\"", '\r'),
737         ("\"\\t\"", '\t'),
738         ("\"\\u000b\"", '\x0B'),
739         ("\"\\u000B\"", '\x0B'),
740         ("\"\u{3A3}\"", '\u{3A3}'),
741     ]);
742 }
743 
744 #[test]
test_parse_number_errors()745 fn test_parse_number_errors() {
746     test_parse_err::<f64>(&[
747         ("+", "expected value at line 1 column 1"),
748         (".", "expected value at line 1 column 1"),
749         ("-", "EOF while parsing a value at line 1 column 1"),
750         ("00", "invalid number at line 1 column 2"),
751         ("0x80", "trailing characters at line 1 column 2"),
752         ("\\0", "expected value at line 1 column 1"),
753         (".0", "expected value at line 1 column 1"),
754         ("0.", "EOF while parsing a value at line 1 column 2"),
755         ("1.", "EOF while parsing a value at line 1 column 2"),
756         ("1.a", "invalid number at line 1 column 3"),
757         ("1.e1", "invalid number at line 1 column 3"),
758         ("1e", "EOF while parsing a value at line 1 column 2"),
759         ("1e+", "EOF while parsing a value at line 1 column 3"),
760         ("1a", "trailing characters at line 1 column 2"),
761         (
762             "100e777777777777777777777777777",
763             "number out of range at line 1 column 14",
764         ),
765         (
766             "-100e777777777777777777777777777",
767             "number out of range at line 1 column 15",
768         ),
769         (
770             "1000000000000000000000000000000000000000000000000000000000000\
771              000000000000000000000000000000000000000000000000000000000000\
772              000000000000000000000000000000000000000000000000000000000000\
773              000000000000000000000000000000000000000000000000000000000000\
774              000000000000000000000000000000000000000000000000000000000000\
775              000000000", // 1e309
776             "number out of range at line 1 column 310",
777         ),
778         (
779             "1000000000000000000000000000000000000000000000000000000000000\
780              000000000000000000000000000000000000000000000000000000000000\
781              000000000000000000000000000000000000000000000000000000000000\
782              000000000000000000000000000000000000000000000000000000000000\
783              000000000000000000000000000000000000000000000000000000000000\
784              .0e9", // 1e309
785             "number out of range at line 1 column 305",
786         ),
787         (
788             "1000000000000000000000000000000000000000000000000000000000000\
789              000000000000000000000000000000000000000000000000000000000000\
790              000000000000000000000000000000000000000000000000000000000000\
791              000000000000000000000000000000000000000000000000000000000000\
792              000000000000000000000000000000000000000000000000000000000000\
793              e9", // 1e309
794             "number out of range at line 1 column 303",
795         ),
796     ]);
797 }
798 
799 #[test]
test_parse_i64()800 fn test_parse_i64() {
801     test_parse_ok(vec![
802         ("-2", -2),
803         ("-1234", -1234),
804         (" -1234 ", -1234),
805         (&i64::MIN.to_string(), i64::MIN),
806         (&i64::MAX.to_string(), i64::MAX),
807     ]);
808 }
809 
810 #[test]
test_parse_u64()811 fn test_parse_u64() {
812     test_parse_ok(vec![
813         ("0", 0u64),
814         ("3", 3u64),
815         ("1234", 1234),
816         (&u64::MAX.to_string(), u64::MAX),
817     ]);
818 }
819 
820 #[test]
test_parse_negative_zero()821 fn test_parse_negative_zero() {
822     for negative_zero in &[
823         "-0",
824         "-0.0",
825         "-0e2",
826         "-0.0e2",
827         "-1e-400",
828         "-1e-4000000000000000000000000000000000000000000000000",
829     ] {
830         assert!(
831             from_str::<f32>(negative_zero).unwrap().is_sign_negative(),
832             "should have been negative: {:?}",
833             negative_zero,
834         );
835         assert!(
836             from_str::<f64>(negative_zero).unwrap().is_sign_negative(),
837             "should have been negative: {:?}",
838             negative_zero,
839         );
840     }
841 }
842 
843 #[test]
test_parse_f64()844 fn test_parse_f64() {
845     test_parse_ok(vec![
846         ("0.0", 0.0f64),
847         ("3.0", 3.0f64),
848         ("3.1", 3.1),
849         ("-1.2", -1.2),
850         ("0.4", 0.4),
851         // Edge case from:
852         // https://github.com/serde-rs/json/issues/536#issuecomment-583714900
853         ("2.638344616030823e-256", 2.638344616030823e-256),
854     ]);
855 
856     #[cfg(not(feature = "arbitrary_precision"))]
857     test_parse_ok(vec![
858         // With arbitrary-precision enabled, this parses as Number{"3.00"}
859         // but the float is Number{"3.0"}
860         ("3.00", 3.0f64),
861         ("0.4e5", 0.4e5),
862         ("0.4e+5", 0.4e5),
863         ("0.4e15", 0.4e15),
864         ("0.4e+15", 0.4e15),
865         ("0.4e-01", 0.4e-1),
866         (" 0.4e-01 ", 0.4e-1),
867         ("0.4e-001", 0.4e-1),
868         ("0.4e-0", 0.4e0),
869         ("0.00e00", 0.0),
870         ("0.00e+00", 0.0),
871         ("0.00e-00", 0.0),
872         ("3.5E-2147483647", 0.0),
873         ("0.0100000000000000000001", 0.01),
874         (
875             &format!("{}", (i64::MIN as f64) - 1.0),
876             (i64::MIN as f64) - 1.0,
877         ),
878         (
879             &format!("{}", (u64::MAX as f64) + 1.0),
880             (u64::MAX as f64) + 1.0,
881         ),
882         (&format!("{}", f64::EPSILON), f64::EPSILON),
883         (
884             "0.0000000000000000000000000000000000000000000000000123e50",
885             1.23,
886         ),
887         ("100e-777777777777777777777777777", 0.0),
888         (
889             "1010101010101010101010101010101010101010",
890             10101010101010101010e20,
891         ),
892         (
893             "0.1010101010101010101010101010101010101010",
894             0.1010101010101010101,
895         ),
896         ("0e1000000000000000000000000000000000000000000000", 0.0),
897         (
898             "1000000000000000000000000000000000000000000000000000000000000\
899              000000000000000000000000000000000000000000000000000000000000\
900              000000000000000000000000000000000000000000000000000000000000\
901              000000000000000000000000000000000000000000000000000000000000\
902              000000000000000000000000000000000000000000000000000000000000\
903              00000000",
904             1e308,
905         ),
906         (
907             "1000000000000000000000000000000000000000000000000000000000000\
908              000000000000000000000000000000000000000000000000000000000000\
909              000000000000000000000000000000000000000000000000000000000000\
910              000000000000000000000000000000000000000000000000000000000000\
911              000000000000000000000000000000000000000000000000000000000000\
912              .0e8",
913             1e308,
914         ),
915         (
916             "1000000000000000000000000000000000000000000000000000000000000\
917              000000000000000000000000000000000000000000000000000000000000\
918              000000000000000000000000000000000000000000000000000000000000\
919              000000000000000000000000000000000000000000000000000000000000\
920              000000000000000000000000000000000000000000000000000000000000\
921              e8",
922             1e308,
923         ),
924         (
925             "1000000000000000000000000000000000000000000000000000000000000\
926              000000000000000000000000000000000000000000000000000000000000\
927              000000000000000000000000000000000000000000000000000000000000\
928              000000000000000000000000000000000000000000000000000000000000\
929              000000000000000000000000000000000000000000000000000000000000\
930              000000000000000000e-10",
931             1e308,
932         ),
933     ]);
934 }
935 
936 #[test]
test_value_as_f64()937 fn test_value_as_f64() {
938     let v = serde_json::from_str::<Value>("1e1000");
939 
940     #[cfg(not(feature = "arbitrary_precision"))]
941     assert!(v.is_err());
942 
943     #[cfg(feature = "arbitrary_precision")]
944     assert_eq!(v.unwrap().as_f64(), None);
945 }
946 
947 // Test roundtrip with some values that were not perfectly roundtripped by the
948 // old f64 deserializer.
949 #[cfg(feature = "float_roundtrip")]
950 #[test]
test_roundtrip_f64()951 fn test_roundtrip_f64() {
952     for &float in &[
953         // Samples from quickcheck-ing roundtrip with `input: f64`. Comments
954         // indicate the value returned by the old deserializer.
955         51.24817837550540_4,  // 51.2481783755054_1
956         -93.3113703768803_3,  // -93.3113703768803_2
957         -36.5739948427534_36, // -36.5739948427534_4
958         52.31400820410624_4,  // 52.31400820410624_
959         97.4536532003468_5,   // 97.4536532003468_4
960         // Samples from `rng.next_u64` + `f64::from_bits` + `is_finite` filter.
961         2.0030397744267762e-253,
962         7.101215824554616e260,
963         1.769268377902049e74,
964         -1.6727517818542075e58,
965         3.9287532173373315e299,
966     ] {
967         let json = serde_json::to_string(&float).unwrap();
968         let output: f64 = serde_json::from_str(&json).unwrap();
969         assert_eq!(float, output);
970     }
971 }
972 
973 #[test]
test_roundtrip_f32()974 fn test_roundtrip_f32() {
975     // This number has 1 ULP error if parsed via f64 and converted to f32.
976     // https://github.com/serde-rs/json/pull/671#issuecomment-628534468
977     let float = 7.038531e-26;
978     let json = serde_json::to_string(&float).unwrap();
979     let output: f32 = serde_json::from_str(&json).unwrap();
980     assert_eq!(float, output);
981 }
982 
983 #[test]
test_serialize_char()984 fn test_serialize_char() {
985     let value = json!(
986         ({
987             let mut map = BTreeMap::new();
988             map.insert('c', ());
989             map
990         })
991     );
992     assert_eq!(&Value::Null, value.get("c").unwrap());
993 }
994 
995 #[cfg(feature = "arbitrary_precision")]
996 #[test]
test_malicious_number()997 fn test_malicious_number() {
998     #[derive(Serialize)]
999     #[serde(rename = "$serde_json::private::Number")]
1000     struct S {
1001         #[serde(rename = "$serde_json::private::Number")]
1002         f: &'static str,
1003     }
1004 
1005     let actual = serde_json::to_value(&S { f: "not a number" })
1006         .unwrap_err()
1007         .to_string();
1008     assert_eq!(actual, "invalid number at line 1 column 1");
1009 }
1010 
1011 #[test]
test_parse_number()1012 fn test_parse_number() {
1013     test_parse_ok(vec![
1014         ("0.0", Number::from_f64(0.0f64).unwrap()),
1015         ("3.0", Number::from_f64(3.0f64).unwrap()),
1016         ("3.1", Number::from_f64(3.1).unwrap()),
1017         ("-1.2", Number::from_f64(-1.2).unwrap()),
1018         ("0.4", Number::from_f64(0.4).unwrap()),
1019     ]);
1020 
1021     test_fromstr_parse_err::<Number>(&[
1022         (" 1.0", "invalid number at line 1 column 1"),
1023         ("1.0 ", "invalid number at line 1 column 4"),
1024         ("\t1.0", "invalid number at line 1 column 1"),
1025         ("1.0\t", "invalid number at line 1 column 4"),
1026     ]);
1027 
1028     #[cfg(feature = "arbitrary_precision")]
1029     test_parse_ok(vec![
1030         ("1e999", Number::from_string_unchecked("1e999".to_owned())),
1031         ("1e+999", Number::from_string_unchecked("1e+999".to_owned())),
1032         ("-1e999", Number::from_string_unchecked("-1e999".to_owned())),
1033         ("1e-999", Number::from_string_unchecked("1e-999".to_owned())),
1034         ("1E999", Number::from_string_unchecked("1E999".to_owned())),
1035         ("1E+999", Number::from_string_unchecked("1E+999".to_owned())),
1036         ("-1E999", Number::from_string_unchecked("-1E999".to_owned())),
1037         ("1E-999", Number::from_string_unchecked("1E-999".to_owned())),
1038         ("1E+000", Number::from_string_unchecked("1E+000".to_owned())),
1039         (
1040             "2.3e999",
1041             Number::from_string_unchecked("2.3e999".to_owned()),
1042         ),
1043         (
1044             "-2.3e999",
1045             Number::from_string_unchecked("-2.3e999".to_owned()),
1046         ),
1047     ]);
1048 }
1049 
1050 #[test]
test_parse_string()1051 fn test_parse_string() {
1052     test_parse_err::<String>(&[
1053         ("\"", "EOF while parsing a string at line 1 column 1"),
1054         ("\"lol", "EOF while parsing a string at line 1 column 4"),
1055         ("\"lol\"a", "trailing characters at line 1 column 6"),
1056         (
1057             "\"\\uD83C\\uFFFF\"",
1058             "lone leading surrogate in hex escape at line 1 column 13",
1059         ),
1060         (
1061             "\"\n\"",
1062             "control character (\\u0000-\\u001F) found while parsing a string at line 2 column 0",
1063         ),
1064         (
1065             "\"\x1F\"",
1066             "control character (\\u0000-\\u001F) found while parsing a string at line 1 column 2",
1067         ),
1068     ]);
1069 
1070     test_parse_slice_err::<String>(&[
1071         (
1072             &[b'"', 159, 146, 150, b'"'],
1073             "invalid unicode code point at line 1 column 5",
1074         ),
1075         (
1076             &[b'"', b'\\', b'n', 159, 146, 150, b'"'],
1077             "invalid unicode code point at line 1 column 7",
1078         ),
1079         (
1080             &[b'"', b'\\', b'u', 48, 48, 51],
1081             "EOF while parsing a string at line 1 column 6",
1082         ),
1083         (
1084             &[b'"', b'\\', b'u', 250, 48, 51, 48, b'"'],
1085             "invalid escape at line 1 column 4",
1086         ),
1087         (
1088             &[b'"', b'\\', b'u', 48, 250, 51, 48, b'"'],
1089             "invalid escape at line 1 column 5",
1090         ),
1091         (
1092             &[b'"', b'\\', b'u', 48, 48, 250, 48, b'"'],
1093             "invalid escape at line 1 column 6",
1094         ),
1095         (
1096             &[b'"', b'\\', b'u', 48, 48, 51, 250, b'"'],
1097             "invalid escape at line 1 column 7",
1098         ),
1099         (
1100             &[b'"', b'\n', b'"'],
1101             "control character (\\u0000-\\u001F) found while parsing a string at line 2 column 0",
1102         ),
1103         (
1104             &[b'"', b'\x1F', b'"'],
1105             "control character (\\u0000-\\u001F) found while parsing a string at line 1 column 2",
1106         ),
1107     ]);
1108 
1109     test_parse_ok(vec![
1110         ("\"\"", String::new()),
1111         ("\"foo\"", "foo".to_string()),
1112         (" \"foo\" ", "foo".to_string()),
1113         ("\"\\\"\"", "\"".to_string()),
1114         ("\"\\b\"", "\x08".to_string()),
1115         ("\"\\n\"", "\n".to_string()),
1116         ("\"\\r\"", "\r".to_string()),
1117         ("\"\\t\"", "\t".to_string()),
1118         ("\"\\u12ab\"", "\u{12ab}".to_string()),
1119         ("\"\\uAB12\"", "\u{AB12}".to_string()),
1120         ("\"\\uD83C\\uDF95\"", "\u{1F395}".to_string()),
1121     ]);
1122 }
1123 
1124 #[test]
test_parse_list()1125 fn test_parse_list() {
1126     test_parse_err::<Vec<f64>>(&[
1127         ("[", "EOF while parsing a list at line 1 column 1"),
1128         ("[ ", "EOF while parsing a list at line 1 column 2"),
1129         ("[1", "EOF while parsing a list at line 1 column 2"),
1130         ("[1,", "EOF while parsing a value at line 1 column 3"),
1131         ("[1,]", "trailing comma at line 1 column 4"),
1132         ("[1 2]", "expected `,` or `]` at line 1 column 4"),
1133         ("[]a", "trailing characters at line 1 column 3"),
1134     ]);
1135 
1136     test_parse_ok(vec![
1137         ("[]", vec![]),
1138         ("[ ]", vec![]),
1139         ("[null]", vec![()]),
1140         (" [ null ] ", vec![()]),
1141     ]);
1142 
1143     test_parse_ok(vec![("[true]", vec![true])]);
1144 
1145     test_parse_ok(vec![("[3,1]", vec![3u64, 1]), (" [ 3 , 1 ] ", vec![3, 1])]);
1146 
1147     test_parse_ok(vec![("[[3], [1, 2]]", vec![vec![3u64], vec![1, 2]])]);
1148 
1149     test_parse_ok(vec![("[1]", (1u64,))]);
1150 
1151     test_parse_ok(vec![("[1, 2]", (1u64, 2u64))]);
1152 
1153     test_parse_ok(vec![("[1, 2, 3]", (1u64, 2u64, 3u64))]);
1154 
1155     test_parse_ok(vec![("[1, [2, 3]]", (1u64, (2u64, 3u64)))]);
1156 }
1157 
1158 #[test]
test_parse_object()1159 fn test_parse_object() {
1160     test_parse_err::<BTreeMap<String, u32>>(&[
1161         ("{", "EOF while parsing an object at line 1 column 1"),
1162         ("{ ", "EOF while parsing an object at line 1 column 2"),
1163         ("{1", "key must be a string at line 1 column 2"),
1164         ("{ \"a\"", "EOF while parsing an object at line 1 column 5"),
1165         ("{\"a\"", "EOF while parsing an object at line 1 column 4"),
1166         ("{\"a\" ", "EOF while parsing an object at line 1 column 5"),
1167         ("{\"a\" 1", "expected `:` at line 1 column 6"),
1168         ("{\"a\":", "EOF while parsing a value at line 1 column 5"),
1169         ("{\"a\":1", "EOF while parsing an object at line 1 column 6"),
1170         ("{\"a\":1 1", "expected `,` or `}` at line 1 column 8"),
1171         ("{\"a\":1,", "EOF while parsing a value at line 1 column 7"),
1172         ("{}a", "trailing characters at line 1 column 3"),
1173     ]);
1174 
1175     test_parse_ok(vec![
1176         ("{}", treemap!()),
1177         ("{ }", treemap!()),
1178         ("{\"a\":3}", treemap!("a".to_string() => 3u64)),
1179         ("{ \"a\" : 3 }", treemap!("a".to_string() => 3)),
1180         (
1181             "{\"a\":3,\"b\":4}",
1182             treemap!("a".to_string() => 3, "b".to_string() => 4),
1183         ),
1184         (
1185             " { \"a\" : 3 , \"b\" : 4 } ",
1186             treemap!("a".to_string() => 3, "b".to_string() => 4),
1187         ),
1188     ]);
1189 
1190     test_parse_ok(vec![(
1191         "{\"a\": {\"b\": 3, \"c\": 4}}",
1192         treemap!(
1193             "a".to_string() => treemap!(
1194                 "b".to_string() => 3u64,
1195                 "c".to_string() => 4
1196             )
1197         ),
1198     )]);
1199 
1200     test_parse_ok(vec![("{\"c\":null}", treemap!('c' => ()))]);
1201 }
1202 
1203 #[test]
test_parse_struct()1204 fn test_parse_struct() {
1205     test_parse_err::<Outer>(&[
1206         (
1207             "5",
1208             "invalid type: integer `5`, expected struct Outer at line 1 column 1",
1209         ),
1210         (
1211             "\"hello\"",
1212             "invalid type: string \"hello\", expected struct Outer at line 1 column 7",
1213         ),
1214         (
1215             "{\"inner\": true}",
1216             "invalid type: boolean `true`, expected a sequence at line 1 column 14",
1217         ),
1218         ("{}", "missing field `inner` at line 1 column 2"),
1219         (
1220             r#"{"inner": [{"b": 42, "c": []}]}"#,
1221             "missing field `a` at line 1 column 29",
1222         ),
1223     ]);
1224 
1225     test_parse_ok(vec![
1226         (
1227             "{
1228                 \"inner\": []
1229             }",
1230             Outer { inner: vec![] },
1231         ),
1232         (
1233             "{
1234                 \"inner\": [
1235                     { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
1236                 ]
1237             }",
1238             Outer {
1239                 inner: vec![Inner {
1240                     a: (),
1241                     b: 2,
1242                     c: vec!["abc".to_string(), "xyz".to_string()],
1243                 }],
1244             },
1245         ),
1246     ]);
1247 
1248     let v: Outer = from_str(
1249         "[
1250             [
1251                 [ null, 2, [\"abc\", \"xyz\"] ]
1252             ]
1253         ]",
1254     )
1255     .unwrap();
1256 
1257     assert_eq!(
1258         v,
1259         Outer {
1260             inner: vec![Inner {
1261                 a: (),
1262                 b: 2,
1263                 c: vec!["abc".to_string(), "xyz".to_string()],
1264             }],
1265         }
1266     );
1267 
1268     let j = json!([null, 2, []]);
1269     Inner::deserialize(&j).unwrap();
1270     Inner::deserialize(j).unwrap();
1271 }
1272 
1273 #[test]
test_parse_option()1274 fn test_parse_option() {
1275     test_parse_ok(vec![
1276         ("null", None::<String>),
1277         ("\"jodhpurs\"", Some("jodhpurs".to_string())),
1278     ]);
1279 
1280     #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1281     struct Foo {
1282         x: Option<isize>,
1283     }
1284 
1285     let value: Foo = from_str("{}").unwrap();
1286     assert_eq!(value, Foo { x: None });
1287 
1288     test_parse_ok(vec![
1289         ("{\"x\": null}", Foo { x: None }),
1290         ("{\"x\": 5}", Foo { x: Some(5) }),
1291     ]);
1292 }
1293 
1294 #[test]
test_parse_enum_errors()1295 fn test_parse_enum_errors() {
1296     test_parse_err::<Animal>(
1297         &[
1298             ("{}", "expected value at line 1 column 2"),
1299             ("[]", "expected value at line 1 column 1"),
1300             ("\"unknown\"",
1301              "unknown variant `unknown`, expected one of `Dog`, `Frog`, `Cat`, `AntHive` at line 1 column 9"),
1302             ("{\"unknown\":null}",
1303              "unknown variant `unknown`, expected one of `Dog`, `Frog`, `Cat`, `AntHive` at line 1 column 10"),
1304             ("{\"Dog\":", "EOF while parsing a value at line 1 column 7"),
1305             ("{\"Dog\":}", "expected value at line 1 column 8"),
1306             ("{\"Dog\":{}}", "invalid type: map, expected unit at line 1 column 7"),
1307             ("\"Frog\"", "invalid type: unit variant, expected tuple variant"),
1308             ("\"Frog\" 0 ", "invalid type: unit variant, expected tuple variant"),
1309             ("{\"Frog\":{}}",
1310              "invalid type: map, expected tuple variant Animal::Frog at line 1 column 8"),
1311             ("{\"Cat\":[]}", "invalid length 0, expected struct variant Animal::Cat with 2 elements at line 1 column 9"),
1312             ("{\"Cat\":[0]}", "invalid length 1, expected struct variant Animal::Cat with 2 elements at line 1 column 10"),
1313             ("{\"Cat\":[0, \"\", 2]}", "trailing characters at line 1 column 16"),
1314             ("{\"Cat\":{\"age\": 5, \"name\": \"Kate\", \"foo\":\"bar\"}",
1315              "unknown field `foo`, expected `age` or `name` at line 1 column 39"),
1316 
1317             // JSON does not allow trailing commas in data structures
1318             ("{\"Cat\":[0, \"Kate\",]}", "trailing comma at line 1 column 19"),
1319             ("{\"Cat\":{\"age\": 2, \"name\": \"Kate\",}}",
1320              "trailing comma at line 1 column 34"),
1321         ],
1322     );
1323 }
1324 
1325 #[test]
test_parse_enum()1326 fn test_parse_enum() {
1327     test_parse_ok(vec![
1328         ("\"Dog\"", Animal::Dog),
1329         (" \"Dog\" ", Animal::Dog),
1330         (
1331             "{\"Frog\":[\"Henry\",[]]}",
1332             Animal::Frog("Henry".to_string(), vec![]),
1333         ),
1334         (
1335             " { \"Frog\": [ \"Henry\" , [ 349, 102 ] ] } ",
1336             Animal::Frog("Henry".to_string(), vec![349, 102]),
1337         ),
1338         (
1339             "{\"Cat\": {\"age\": 5, \"name\": \"Kate\"}}",
1340             Animal::Cat {
1341                 age: 5,
1342                 name: "Kate".to_string(),
1343             },
1344         ),
1345         (
1346             " { \"Cat\" : { \"age\" : 5 , \"name\" : \"Kate\" } } ",
1347             Animal::Cat {
1348                 age: 5,
1349                 name: "Kate".to_string(),
1350             },
1351         ),
1352         (
1353             " { \"AntHive\" : [\"Bob\", \"Stuart\"] } ",
1354             Animal::AntHive(vec!["Bob".to_string(), "Stuart".to_string()]),
1355         ),
1356     ]);
1357 
1358     test_parse_unusual_ok(vec![
1359         ("{\"Dog\":null}", Animal::Dog),
1360         (" { \"Dog\" : null } ", Animal::Dog),
1361     ]);
1362 
1363     test_parse_ok(vec![(
1364         concat!(
1365             "{",
1366             "  \"a\": \"Dog\",",
1367             "  \"b\": {\"Frog\":[\"Henry\", []]}",
1368             "}"
1369         ),
1370         treemap!(
1371             "a".to_string() => Animal::Dog,
1372             "b".to_string() => Animal::Frog("Henry".to_string(), vec![])
1373         ),
1374     )]);
1375 }
1376 
1377 #[test]
test_parse_trailing_whitespace()1378 fn test_parse_trailing_whitespace() {
1379     test_parse_ok(vec![
1380         ("[1, 2] ", vec![1u64, 2]),
1381         ("[1, 2]\n", vec![1, 2]),
1382         ("[1, 2]\t", vec![1, 2]),
1383         ("[1, 2]\t \n", vec![1, 2]),
1384     ]);
1385 }
1386 
1387 #[test]
test_multiline_errors()1388 fn test_multiline_errors() {
1389     test_parse_err::<BTreeMap<String, String>>(&[(
1390         "{\n  \"foo\":\n \"bar\"",
1391         "EOF while parsing an object at line 3 column 6",
1392     )]);
1393 }
1394 
1395 #[test]
test_missing_option_field()1396 fn test_missing_option_field() {
1397     #[derive(Debug, PartialEq, Deserialize)]
1398     struct Foo {
1399         x: Option<u32>,
1400     }
1401 
1402     let value: Foo = from_str("{}").unwrap();
1403     assert_eq!(value, Foo { x: None });
1404 
1405     let value: Foo = from_str("{\"x\": 5}").unwrap();
1406     assert_eq!(value, Foo { x: Some(5) });
1407 
1408     let value: Foo = from_value(json!({})).unwrap();
1409     assert_eq!(value, Foo { x: None });
1410 
1411     let value: Foo = from_value(json!({"x": 5})).unwrap();
1412     assert_eq!(value, Foo { x: Some(5) });
1413 }
1414 
1415 #[test]
test_missing_nonoption_field()1416 fn test_missing_nonoption_field() {
1417     #[derive(Debug, PartialEq, Deserialize)]
1418     struct Foo {
1419         x: u32,
1420     }
1421 
1422     test_parse_err::<Foo>(&[("{}", "missing field `x` at line 1 column 2")]);
1423 }
1424 
1425 #[test]
test_missing_renamed_field()1426 fn test_missing_renamed_field() {
1427     #[derive(Debug, PartialEq, Deserialize)]
1428     struct Foo {
1429         #[serde(rename = "y")]
1430         x: Option<u32>,
1431     }
1432 
1433     let value: Foo = from_str("{}").unwrap();
1434     assert_eq!(value, Foo { x: None });
1435 
1436     let value: Foo = from_str("{\"y\": 5}").unwrap();
1437     assert_eq!(value, Foo { x: Some(5) });
1438 
1439     let value: Foo = from_value(json!({})).unwrap();
1440     assert_eq!(value, Foo { x: None });
1441 
1442     let value: Foo = from_value(json!({"y": 5})).unwrap();
1443     assert_eq!(value, Foo { x: Some(5) });
1444 }
1445 
1446 #[test]
test_serialize_seq_with_no_len()1447 fn test_serialize_seq_with_no_len() {
1448     #[derive(Clone, Debug, PartialEq)]
1449     struct MyVec<T>(Vec<T>);
1450 
1451     impl<T> ser::Serialize for MyVec<T>
1452     where
1453         T: ser::Serialize,
1454     {
1455         #[inline]
1456         fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1457         where
1458             S: ser::Serializer,
1459         {
1460             let mut seq = serializer.serialize_seq(None)?;
1461             for elem in &self.0 {
1462                 seq.serialize_element(elem)?;
1463             }
1464             seq.end()
1465         }
1466     }
1467 
1468     struct Visitor<T> {
1469         marker: PhantomData<MyVec<T>>,
1470     }
1471 
1472     impl<'de, T> de::Visitor<'de> for Visitor<T>
1473     where
1474         T: de::Deserialize<'de>,
1475     {
1476         type Value = MyVec<T>;
1477 
1478         fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1479             formatter.write_str("array")
1480         }
1481 
1482         #[inline]
1483         fn visit_unit<E>(self) -> Result<MyVec<T>, E>
1484         where
1485             E: de::Error,
1486         {
1487             Ok(MyVec(Vec::new()))
1488         }
1489 
1490         #[inline]
1491         fn visit_seq<V>(self, mut visitor: V) -> Result<MyVec<T>, V::Error>
1492         where
1493             V: de::SeqAccess<'de>,
1494         {
1495             let mut values = Vec::new();
1496 
1497             while let Some(value) = visitor.next_element()? {
1498                 values.push(value);
1499             }
1500 
1501             Ok(MyVec(values))
1502         }
1503     }
1504 
1505     impl<'de, T> de::Deserialize<'de> for MyVec<T>
1506     where
1507         T: de::Deserialize<'de>,
1508     {
1509         fn deserialize<D>(deserializer: D) -> Result<MyVec<T>, D::Error>
1510         where
1511             D: de::Deserializer<'de>,
1512         {
1513             deserializer.deserialize_map(Visitor {
1514                 marker: PhantomData,
1515             })
1516         }
1517     }
1518 
1519     let mut vec = Vec::new();
1520     vec.push(MyVec(Vec::new()));
1521     vec.push(MyVec(Vec::new()));
1522     let vec: MyVec<MyVec<u32>> = MyVec(vec);
1523 
1524     test_encode_ok(&[(vec.clone(), "[[],[]]")]);
1525 
1526     let s = to_string_pretty(&vec).unwrap();
1527     let expected = pretty_str!([[], []]);
1528     assert_eq!(s, expected);
1529 }
1530 
1531 #[test]
test_serialize_map_with_no_len()1532 fn test_serialize_map_with_no_len() {
1533     #[derive(Clone, Debug, PartialEq)]
1534     struct MyMap<K, V>(BTreeMap<K, V>);
1535 
1536     impl<K, V> ser::Serialize for MyMap<K, V>
1537     where
1538         K: ser::Serialize + Ord,
1539         V: ser::Serialize,
1540     {
1541         #[inline]
1542         fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1543         where
1544             S: ser::Serializer,
1545         {
1546             let mut map = serializer.serialize_map(None)?;
1547             for (k, v) in &self.0 {
1548                 map.serialize_entry(k, v)?;
1549             }
1550             map.end()
1551         }
1552     }
1553 
1554     struct Visitor<K, V> {
1555         marker: PhantomData<MyMap<K, V>>,
1556     }
1557 
1558     impl<'de, K, V> de::Visitor<'de> for Visitor<K, V>
1559     where
1560         K: de::Deserialize<'de> + Eq + Ord,
1561         V: de::Deserialize<'de>,
1562     {
1563         type Value = MyMap<K, V>;
1564 
1565         fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1566             formatter.write_str("map")
1567         }
1568 
1569         #[inline]
1570         fn visit_unit<E>(self) -> Result<MyMap<K, V>, E>
1571         where
1572             E: de::Error,
1573         {
1574             Ok(MyMap(BTreeMap::new()))
1575         }
1576 
1577         #[inline]
1578         fn visit_map<Visitor>(self, mut visitor: Visitor) -> Result<MyMap<K, V>, Visitor::Error>
1579         where
1580             Visitor: de::MapAccess<'de>,
1581         {
1582             let mut values = BTreeMap::new();
1583 
1584             while let Some((key, value)) = visitor.next_entry()? {
1585                 values.insert(key, value);
1586             }
1587 
1588             Ok(MyMap(values))
1589         }
1590     }
1591 
1592     impl<'de, K, V> de::Deserialize<'de> for MyMap<K, V>
1593     where
1594         K: de::Deserialize<'de> + Eq + Ord,
1595         V: de::Deserialize<'de>,
1596     {
1597         fn deserialize<D>(deserializer: D) -> Result<MyMap<K, V>, D::Error>
1598         where
1599             D: de::Deserializer<'de>,
1600         {
1601             deserializer.deserialize_map(Visitor {
1602                 marker: PhantomData,
1603             })
1604         }
1605     }
1606 
1607     let mut map = BTreeMap::new();
1608     map.insert("a", MyMap(BTreeMap::new()));
1609     map.insert("b", MyMap(BTreeMap::new()));
1610     let map: MyMap<_, MyMap<u32, u32>> = MyMap(map);
1611 
1612     test_encode_ok(&[(map.clone(), "{\"a\":{},\"b\":{}}")]);
1613 
1614     let s = to_string_pretty(&map).unwrap();
1615     let expected = pretty_str!({
1616         "a": {},
1617         "b": {}
1618     });
1619     assert_eq!(s, expected);
1620 }
1621 
1622 #[cfg(not(miri))]
1623 #[test]
test_deserialize_from_stream()1624 fn test_deserialize_from_stream() {
1625     use serde_json::to_writer;
1626     use std::net::{TcpListener, TcpStream};
1627     use std::thread;
1628 
1629     #[derive(Debug, PartialEq, Serialize, Deserialize)]
1630     struct Message {
1631         message: String,
1632     }
1633 
1634     let l = TcpListener::bind("localhost:20000").unwrap();
1635 
1636     thread::spawn(|| {
1637         let l = l;
1638         for stream in l.incoming() {
1639             let mut stream = stream.unwrap();
1640             let read_stream = stream.try_clone().unwrap();
1641 
1642             let mut de = Deserializer::from_reader(read_stream);
1643             let request = Message::deserialize(&mut de).unwrap();
1644             let response = Message {
1645                 message: request.message,
1646             };
1647             to_writer(&mut stream, &response).unwrap();
1648         }
1649     });
1650 
1651     let mut stream = TcpStream::connect("localhost:20000").unwrap();
1652     let request = Message {
1653         message: "hi there".to_string(),
1654     };
1655     to_writer(&mut stream, &request).unwrap();
1656 
1657     let mut de = Deserializer::from_reader(stream);
1658     let response = Message::deserialize(&mut de).unwrap();
1659 
1660     assert_eq!(request, response);
1661 }
1662 
1663 #[test]
test_serialize_rejects_bool_keys()1664 fn test_serialize_rejects_bool_keys() {
1665     let map = treemap!(
1666         true => 2,
1667         false => 4
1668     );
1669 
1670     let err = to_vec(&map).unwrap_err();
1671     assert_eq!(err.to_string(), "key must be a string");
1672 }
1673 
1674 #[test]
test_serialize_rejects_adt_keys()1675 fn test_serialize_rejects_adt_keys() {
1676     let map = treemap!(
1677         Some("a") => 2,
1678         Some("b") => 4,
1679         None => 6
1680     );
1681 
1682     let err = to_vec(&map).unwrap_err();
1683     assert_eq!(err.to_string(), "key must be a string");
1684 }
1685 
1686 #[test]
test_bytes_ser()1687 fn test_bytes_ser() {
1688     let buf = vec![];
1689     let bytes = Bytes::new(&buf);
1690     assert_eq!(to_string(&bytes).unwrap(), "[]".to_string());
1691 
1692     let buf = vec![1, 2, 3];
1693     let bytes = Bytes::new(&buf);
1694     assert_eq!(to_string(&bytes).unwrap(), "[1,2,3]".to_string());
1695 }
1696 
1697 #[test]
test_byte_buf_ser()1698 fn test_byte_buf_ser() {
1699     let bytes = ByteBuf::new();
1700     assert_eq!(to_string(&bytes).unwrap(), "[]".to_string());
1701 
1702     let bytes = ByteBuf::from(vec![1, 2, 3]);
1703     assert_eq!(to_string(&bytes).unwrap(), "[1,2,3]".to_string());
1704 }
1705 
1706 #[test]
test_byte_buf_de()1707 fn test_byte_buf_de() {
1708     let bytes = ByteBuf::new();
1709     let v: ByteBuf = from_str("[]").unwrap();
1710     assert_eq!(v, bytes);
1711 
1712     let bytes = ByteBuf::from(vec![1, 2, 3]);
1713     let v: ByteBuf = from_str("[1, 2, 3]").unwrap();
1714     assert_eq!(v, bytes);
1715 }
1716 
1717 #[test]
test_byte_buf_de_lone_surrogate()1718 fn test_byte_buf_de_lone_surrogate() {
1719     let bytes = ByteBuf::from(vec![237, 160, 188]);
1720     let v: ByteBuf = from_str(r#""\ud83c""#).unwrap();
1721     assert_eq!(v, bytes);
1722 
1723     let bytes = ByteBuf::from(vec![237, 160, 188, 10]);
1724     let v: ByteBuf = from_str(r#""\ud83c\n""#).unwrap();
1725     assert_eq!(v, bytes);
1726 
1727     let bytes = ByteBuf::from(vec![237, 160, 188, 32]);
1728     let v: ByteBuf = from_str(r#""\ud83c ""#).unwrap();
1729     assert_eq!(v, bytes);
1730 
1731     let bytes = ByteBuf::from(vec![237, 176, 129]);
1732     let v: ByteBuf = from_str(r#""\udc01""#).unwrap();
1733     assert_eq!(v, bytes);
1734 
1735     let res = from_str::<ByteBuf>(r#""\ud83c\!""#);
1736     assert!(res.is_err());
1737 
1738     let res = from_str::<ByteBuf>(r#""\ud83c\u""#);
1739     assert!(res.is_err());
1740 
1741     let res = from_str::<ByteBuf>(r#""\ud83c\ud83c""#);
1742     assert!(res.is_err());
1743 }
1744 
1745 #[cfg(feature = "raw_value")]
1746 #[test]
test_raw_de_lone_surrogate()1747 fn test_raw_de_lone_surrogate() {
1748     use serde_json::value::RawValue;
1749 
1750     assert!(from_str::<Box<RawValue>>(r#""\ud83c""#).is_ok());
1751     assert!(from_str::<Box<RawValue>>(r#""\ud83c\n""#).is_ok());
1752     assert!(from_str::<Box<RawValue>>(r#""\ud83c ""#).is_ok());
1753     assert!(from_str::<Box<RawValue>>(r#""\udc01 ""#).is_ok());
1754     assert!(from_str::<Box<RawValue>>(r#""\udc01\!""#).is_err());
1755     assert!(from_str::<Box<RawValue>>(r#""\udc01\u""#).is_err());
1756     assert!(from_str::<Box<RawValue>>(r#""\ud83c\ud83c""#).is_ok());
1757 }
1758 
1759 #[test]
test_byte_buf_de_multiple()1760 fn test_byte_buf_de_multiple() {
1761     let s: Vec<ByteBuf> = from_str(r#"["ab\nc", "cd\ne"]"#).unwrap();
1762     let a = ByteBuf::from(b"ab\nc".to_vec());
1763     let b = ByteBuf::from(b"cd\ne".to_vec());
1764     assert_eq!(vec![a, b], s);
1765 }
1766 
1767 #[test]
test_json_pointer()1768 fn test_json_pointer() {
1769     // Test case taken from https://tools.ietf.org/html/rfc6901#page-5
1770     let data: Value = from_str(
1771         r#"{
1772         "foo": ["bar", "baz"],
1773         "": 0,
1774         "a/b": 1,
1775         "c%d": 2,
1776         "e^f": 3,
1777         "g|h": 4,
1778         "i\\j": 5,
1779         "k\"l": 6,
1780         " ": 7,
1781         "m~n": 8
1782     }"#,
1783     )
1784     .unwrap();
1785     assert_eq!(data.pointer("").unwrap(), &data);
1786     assert_eq!(data.pointer("/foo").unwrap(), &json!(["bar", "baz"]));
1787     assert_eq!(data.pointer("/foo/0").unwrap(), &json!("bar"));
1788     assert_eq!(data.pointer("/").unwrap(), &json!(0));
1789     assert_eq!(data.pointer("/a~1b").unwrap(), &json!(1));
1790     assert_eq!(data.pointer("/c%d").unwrap(), &json!(2));
1791     assert_eq!(data.pointer("/e^f").unwrap(), &json!(3));
1792     assert_eq!(data.pointer("/g|h").unwrap(), &json!(4));
1793     assert_eq!(data.pointer("/i\\j").unwrap(), &json!(5));
1794     assert_eq!(data.pointer("/k\"l").unwrap(), &json!(6));
1795     assert_eq!(data.pointer("/ ").unwrap(), &json!(7));
1796     assert_eq!(data.pointer("/m~0n").unwrap(), &json!(8));
1797     // Invalid pointers
1798     assert!(data.pointer("/unknown").is_none());
1799     assert!(data.pointer("/e^f/ertz").is_none());
1800     assert!(data.pointer("/foo/00").is_none());
1801     assert!(data.pointer("/foo/01").is_none());
1802 }
1803 
1804 #[test]
test_json_pointer_mut()1805 fn test_json_pointer_mut() {
1806     // Test case taken from https://tools.ietf.org/html/rfc6901#page-5
1807     let mut data: Value = from_str(
1808         r#"{
1809         "foo": ["bar", "baz"],
1810         "": 0,
1811         "a/b": 1,
1812         "c%d": 2,
1813         "e^f": 3,
1814         "g|h": 4,
1815         "i\\j": 5,
1816         "k\"l": 6,
1817         " ": 7,
1818         "m~n": 8
1819     }"#,
1820     )
1821     .unwrap();
1822 
1823     // Basic pointer checks
1824     assert_eq!(data.pointer_mut("/foo").unwrap(), &json!(["bar", "baz"]));
1825     assert_eq!(data.pointer_mut("/foo/0").unwrap(), &json!("bar"));
1826     assert_eq!(data.pointer_mut("/").unwrap(), 0);
1827     assert_eq!(data.pointer_mut("/a~1b").unwrap(), 1);
1828     assert_eq!(data.pointer_mut("/c%d").unwrap(), 2);
1829     assert_eq!(data.pointer_mut("/e^f").unwrap(), 3);
1830     assert_eq!(data.pointer_mut("/g|h").unwrap(), 4);
1831     assert_eq!(data.pointer_mut("/i\\j").unwrap(), 5);
1832     assert_eq!(data.pointer_mut("/k\"l").unwrap(), 6);
1833     assert_eq!(data.pointer_mut("/ ").unwrap(), 7);
1834     assert_eq!(data.pointer_mut("/m~0n").unwrap(), 8);
1835 
1836     // Invalid pointers
1837     assert!(data.pointer_mut("/unknown").is_none());
1838     assert!(data.pointer_mut("/e^f/ertz").is_none());
1839     assert!(data.pointer_mut("/foo/00").is_none());
1840     assert!(data.pointer_mut("/foo/01").is_none());
1841 
1842     // Mutable pointer checks
1843     *data.pointer_mut("/").unwrap() = 100.into();
1844     assert_eq!(data.pointer("/").unwrap(), 100);
1845     *data.pointer_mut("/foo/0").unwrap() = json!("buzz");
1846     assert_eq!(data.pointer("/foo/0").unwrap(), &json!("buzz"));
1847 
1848     // Example of ownership stealing
1849     assert_eq!(
1850         data.pointer_mut("/a~1b")
1851             .map(|m| mem::replace(m, json!(null)))
1852             .unwrap(),
1853         1
1854     );
1855     assert_eq!(data.pointer("/a~1b").unwrap(), &json!(null));
1856 
1857     // Need to compare against a clone so we don't anger the borrow checker
1858     // by taking out two references to a mutable value
1859     let mut d2 = data.clone();
1860     assert_eq!(data.pointer_mut("").unwrap(), &mut d2);
1861 }
1862 
1863 #[test]
test_stack_overflow()1864 fn test_stack_overflow() {
1865     let brackets: String = iter::repeat('[')
1866         .take(127)
1867         .chain(iter::repeat(']').take(127))
1868         .collect();
1869     let _: Value = from_str(&brackets).unwrap();
1870 
1871     let brackets = "[".repeat(129);
1872     test_parse_err::<Value>(&[(&brackets, "recursion limit exceeded at line 1 column 128")]);
1873 }
1874 
1875 #[test]
1876 #[cfg(feature = "unbounded_depth")]
test_disable_recursion_limit()1877 fn test_disable_recursion_limit() {
1878     let brackets: String = iter::repeat('[')
1879         .take(140)
1880         .chain(iter::repeat(']').take(140))
1881         .collect();
1882 
1883     let mut deserializer = Deserializer::from_str(&brackets);
1884     deserializer.disable_recursion_limit();
1885     Value::deserialize(&mut deserializer).unwrap();
1886 }
1887 
1888 #[test]
test_integer_key()1889 fn test_integer_key() {
1890     // map with integer keys
1891     let map = treemap!(
1892         1 => 2,
1893         -1 => 6
1894     );
1895     let j = r#"{"-1":6,"1":2}"#;
1896     test_encode_ok(&[(&map, j)]);
1897     test_parse_ok(vec![(j, map)]);
1898 
1899     let j = r#"{"x":null}"#;
1900     test_parse_err::<BTreeMap<i32, ()>>(&[(
1901         j,
1902         "invalid type: string \"x\", expected i32 at line 1 column 4",
1903     )]);
1904 }
1905 
1906 #[test]
test_integer128_key()1907 fn test_integer128_key() {
1908     let map = treemap! {
1909         100000000000000000000000000000000000000u128 => ()
1910     };
1911     let j = r#"{"100000000000000000000000000000000000000":null}"#;
1912     assert_eq!(to_string(&map).unwrap(), j);
1913     assert_eq!(from_str::<BTreeMap<u128, ()>>(j).unwrap(), map);
1914 }
1915 
1916 #[test]
test_deny_float_key()1917 fn test_deny_float_key() {
1918     #[derive(Eq, PartialEq, Ord, PartialOrd)]
1919     struct Float;
1920     impl Serialize for Float {
1921         fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1922         where
1923             S: Serializer,
1924         {
1925             serializer.serialize_f32(1.0)
1926         }
1927     }
1928 
1929     // map with float key
1930     let map = treemap!(Float => "x");
1931     assert!(serde_json::to_value(map).is_err());
1932 }
1933 
1934 #[test]
test_borrowed_key()1935 fn test_borrowed_key() {
1936     let map: BTreeMap<&str, ()> = from_str("{\"borrowed\":null}").unwrap();
1937     let expected = treemap! { "borrowed" => () };
1938     assert_eq!(map, expected);
1939 
1940     #[derive(Deserialize, Debug, Ord, PartialOrd, Eq, PartialEq)]
1941     struct NewtypeStr<'a>(&'a str);
1942 
1943     let map: BTreeMap<NewtypeStr, ()> = from_str("{\"borrowed\":null}").unwrap();
1944     let expected = treemap! { NewtypeStr("borrowed") => () };
1945     assert_eq!(map, expected);
1946 }
1947 
1948 #[test]
test_effectively_string_keys()1949 fn test_effectively_string_keys() {
1950     #[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Clone, Serialize, Deserialize)]
1951     enum Enum {
1952         One,
1953         Two,
1954     }
1955     let map = treemap! {
1956         Enum::One => 1,
1957         Enum::Two => 2
1958     };
1959     let expected = r#"{"One":1,"Two":2}"#;
1960     test_encode_ok(&[(&map, expected)]);
1961     test_parse_ok(vec![(expected, map)]);
1962 
1963     #[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Clone, Serialize, Deserialize)]
1964     struct Wrapper(String);
1965     let map = treemap! {
1966         Wrapper("zero".to_owned()) => 0,
1967         Wrapper("one".to_owned()) => 1
1968     };
1969     let expected = r#"{"one":1,"zero":0}"#;
1970     test_encode_ok(&[(&map, expected)]);
1971     test_parse_ok(vec![(expected, map)]);
1972 }
1973 
1974 #[test]
test_json_macro()1975 fn test_json_macro() {
1976     // This is tricky because the <...> is not a single TT and the comma inside
1977     // looks like an array element separator.
1978     let _ = json!([
1979         <Result<(), ()> as Clone>::clone(&Ok(())),
1980         <Result<(), ()> as Clone>::clone(&Err(()))
1981     ]);
1982 
1983     // Same thing but in the map values.
1984     let _ = json!({
1985         "ok": <Result<(), ()> as Clone>::clone(&Ok(())),
1986         "err": <Result<(), ()> as Clone>::clone(&Err(()))
1987     });
1988 
1989     // It works in map keys but only if they are parenthesized.
1990     let _ = json!({
1991         (<Result<&str, ()> as Clone>::clone(&Ok("")).unwrap()): "ok",
1992         (<Result<(), &str> as Clone>::clone(&Err("")).unwrap_err()): "err"
1993     });
1994 
1995     #[deny(unused_results)]
1996     let _ = json!({ "architecture": [true, null] });
1997 }
1998 
1999 #[test]
issue_220()2000 fn issue_220() {
2001     #[derive(Debug, PartialEq, Eq, Deserialize)]
2002     enum E {
2003         V(u8),
2004     }
2005 
2006     assert!(from_str::<E>(r#" "V"0 "#).is_err());
2007 
2008     assert_eq!(from_str::<E>(r#"{"V": 0}"#).unwrap(), E::V(0));
2009 }
2010 
2011 macro_rules! number_partialeq_ok {
2012     ($($n:expr)*) => {
2013         $(
2014             let value = to_value($n).unwrap();
2015             let s = $n.to_string();
2016             assert_eq!(value, $n);
2017             assert_eq!($n, value);
2018             assert_ne!(value, s);
2019         )*
2020     }
2021 }
2022 
2023 #[test]
test_partialeq_number()2024 fn test_partialeq_number() {
2025     number_partialeq_ok!(0 1 100
2026         i8::MIN i8::MAX i16::MIN i16::MAX i32::MIN i32::MAX i64::MIN i64::MAX
2027         u8::MIN u8::MAX u16::MIN u16::MAX u32::MIN u32::MAX u64::MIN u64::MAX
2028         f32::MIN f32::MAX f32::MIN_EXP f32::MAX_EXP f32::MIN_POSITIVE
2029         f64::MIN f64::MAX f64::MIN_EXP f64::MAX_EXP f64::MIN_POSITIVE
2030         f32::consts::E f32::consts::PI f32::consts::LN_2 f32::consts::LOG2_E
2031         f64::consts::E f64::consts::PI f64::consts::LN_2 f64::consts::LOG2_E
2032     );
2033 }
2034 
2035 #[test]
2036 #[cfg(integer128)]
2037 #[cfg(feature = "arbitrary_precision")]
test_partialeq_integer128()2038 fn test_partialeq_integer128() {
2039     number_partialeq_ok!(i128::MIN i128::MAX u128::MIN u128::MAX)
2040 }
2041 
2042 #[test]
test_partialeq_string()2043 fn test_partialeq_string() {
2044     let v = to_value("42").unwrap();
2045     assert_eq!(v, "42");
2046     assert_eq!("42", v);
2047     assert_ne!(v, 42);
2048     assert_eq!(v, String::from("42"));
2049     assert_eq!(String::from("42"), v);
2050 }
2051 
2052 #[test]
test_partialeq_bool()2053 fn test_partialeq_bool() {
2054     let v = to_value(true).unwrap();
2055     assert_eq!(v, true);
2056     assert_eq!(true, v);
2057     assert_ne!(v, false);
2058     assert_ne!(v, "true");
2059     assert_ne!(v, 1);
2060     assert_ne!(v, 0);
2061 }
2062 
2063 struct FailReader(io::ErrorKind);
2064 
2065 impl io::Read for FailReader {
read(&mut self, _: &mut [u8]) -> io::Result<usize>2066     fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
2067         Err(io::Error::new(self.0, "oh no!"))
2068     }
2069 }
2070 
2071 #[test]
test_category()2072 fn test_category() {
2073     assert!(from_str::<String>("123").unwrap_err().is_data());
2074 
2075     assert!(from_str::<String>("]").unwrap_err().is_syntax());
2076 
2077     assert!(from_str::<String>("").unwrap_err().is_eof());
2078     assert!(from_str::<String>("\"").unwrap_err().is_eof());
2079     assert!(from_str::<String>("\"\\").unwrap_err().is_eof());
2080     assert!(from_str::<String>("\"\\u").unwrap_err().is_eof());
2081     assert!(from_str::<String>("\"\\u0").unwrap_err().is_eof());
2082     assert!(from_str::<String>("\"\\u00").unwrap_err().is_eof());
2083     assert!(from_str::<String>("\"\\u000").unwrap_err().is_eof());
2084 
2085     assert!(from_str::<Vec<usize>>("[").unwrap_err().is_eof());
2086     assert!(from_str::<Vec<usize>>("[0").unwrap_err().is_eof());
2087     assert!(from_str::<Vec<usize>>("[0,").unwrap_err().is_eof());
2088 
2089     assert!(from_str::<BTreeMap<String, usize>>("{")
2090         .unwrap_err()
2091         .is_eof());
2092     assert!(from_str::<BTreeMap<String, usize>>("{\"k\"")
2093         .unwrap_err()
2094         .is_eof());
2095     assert!(from_str::<BTreeMap<String, usize>>("{\"k\":")
2096         .unwrap_err()
2097         .is_eof());
2098     assert!(from_str::<BTreeMap<String, usize>>("{\"k\":0")
2099         .unwrap_err()
2100         .is_eof());
2101     assert!(from_str::<BTreeMap<String, usize>>("{\"k\":0,")
2102         .unwrap_err()
2103         .is_eof());
2104 
2105     let fail = FailReader(io::ErrorKind::NotConnected);
2106     assert!(from_reader::<_, String>(fail).unwrap_err().is_io());
2107 }
2108 
2109 #[test]
2110 // Clippy false positive: https://github.com/Manishearth/rust-clippy/issues/292
2111 #[allow(clippy::needless_lifetimes)]
test_into_io_error()2112 fn test_into_io_error() {
2113     fn io_error<'de, T: Deserialize<'de> + Debug>(j: &'static str) -> io::Error {
2114         from_str::<T>(j).unwrap_err().into()
2115     }
2116 
2117     assert_eq!(
2118         io_error::<String>("\"\\u").kind(),
2119         io::ErrorKind::UnexpectedEof
2120     );
2121     assert_eq!(io_error::<String>("0").kind(), io::ErrorKind::InvalidData);
2122     assert_eq!(io_error::<String>("]").kind(), io::ErrorKind::InvalidData);
2123 
2124     let fail = FailReader(io::ErrorKind::NotConnected);
2125     let io_err: io::Error = from_reader::<_, u8>(fail).unwrap_err().into();
2126     assert_eq!(io_err.kind(), io::ErrorKind::NotConnected);
2127 }
2128 
2129 #[test]
test_borrow()2130 fn test_borrow() {
2131     let s: &str = from_str("\"borrowed\"").unwrap();
2132     assert_eq!("borrowed", s);
2133 
2134     let s: &str = from_slice(b"\"borrowed\"").unwrap();
2135     assert_eq!("borrowed", s);
2136 }
2137 
2138 #[test]
null_invalid_type()2139 fn null_invalid_type() {
2140     let err = serde_json::from_str::<String>("null").unwrap_err();
2141     assert_eq!(
2142         format!("{}", err),
2143         String::from("invalid type: null, expected a string at line 1 column 4")
2144     );
2145 }
2146 
2147 #[test]
test_integer128()2148 fn test_integer128() {
2149     let signed = &[i128::min_value(), -1, 0, 1, i128::max_value()];
2150     let unsigned = &[0, 1, u128::max_value()];
2151 
2152     for integer128 in signed {
2153         let expected = integer128.to_string();
2154         assert_eq!(to_string(integer128).unwrap(), expected);
2155         assert_eq!(from_str::<i128>(&expected).unwrap(), *integer128);
2156     }
2157 
2158     for integer128 in unsigned {
2159         let expected = integer128.to_string();
2160         assert_eq!(to_string(integer128).unwrap(), expected);
2161         assert_eq!(from_str::<u128>(&expected).unwrap(), *integer128);
2162     }
2163 
2164     test_parse_err::<i128>(&[
2165         (
2166             "-170141183460469231731687303715884105729",
2167             "number out of range at line 1 column 40",
2168         ),
2169         (
2170             "170141183460469231731687303715884105728",
2171             "number out of range at line 1 column 39",
2172         ),
2173     ]);
2174 
2175     test_parse_err::<u128>(&[
2176         ("-1", "number out of range at line 1 column 1"),
2177         (
2178             "340282366920938463463374607431768211456",
2179             "number out of range at line 1 column 39",
2180         ),
2181     ]);
2182 }
2183 
2184 #[test]
test_integer128_to_value()2185 fn test_integer128_to_value() {
2186     let signed = &[i128::from(i64::min_value()), i128::from(u64::max_value())];
2187     let unsigned = &[0, u128::from(u64::max_value())];
2188 
2189     for integer128 in signed {
2190         let expected = integer128.to_string();
2191         assert_eq!(to_value(integer128).unwrap().to_string(), expected);
2192     }
2193 
2194     for integer128 in unsigned {
2195         let expected = integer128.to_string();
2196         assert_eq!(to_value(integer128).unwrap().to_string(), expected);
2197     }
2198 
2199     if !cfg!(feature = "arbitrary_precision") {
2200         let err = to_value(u128::from(u64::max_value()) + 1).unwrap_err();
2201         assert_eq!(err.to_string(), "number out of range");
2202     }
2203 }
2204 
2205 #[cfg(feature = "raw_value")]
2206 #[test]
test_borrowed_raw_value()2207 fn test_borrowed_raw_value() {
2208     #[derive(Serialize, Deserialize)]
2209     struct Wrapper<'a> {
2210         a: i8,
2211         #[serde(borrow)]
2212         b: &'a RawValue,
2213         c: i8,
2214     }
2215 
2216     let wrapper_from_str: Wrapper =
2217         serde_json::from_str(r#"{"a": 1, "b": {"foo": 2}, "c": 3}"#).unwrap();
2218     assert_eq!(r#"{"foo": 2}"#, wrapper_from_str.b.get());
2219 
2220     let wrapper_to_string = serde_json::to_string(&wrapper_from_str).unwrap();
2221     assert_eq!(r#"{"a":1,"b":{"foo": 2},"c":3}"#, wrapper_to_string);
2222 
2223     let wrapper_to_value = serde_json::to_value(&wrapper_from_str).unwrap();
2224     assert_eq!(json!({"a": 1, "b": {"foo": 2}, "c": 3}), wrapper_to_value);
2225 
2226     let array_from_str: Vec<&RawValue> =
2227         serde_json::from_str(r#"["a", 42, {"foo": "bar"}, null]"#).unwrap();
2228     assert_eq!(r#""a""#, array_from_str[0].get());
2229     assert_eq!(r#"42"#, array_from_str[1].get());
2230     assert_eq!(r#"{"foo": "bar"}"#, array_from_str[2].get());
2231     assert_eq!(r#"null"#, array_from_str[3].get());
2232 
2233     let array_to_string = serde_json::to_string(&array_from_str).unwrap();
2234     assert_eq!(r#"["a",42,{"foo": "bar"},null]"#, array_to_string);
2235 }
2236 
2237 #[cfg(feature = "raw_value")]
2238 #[test]
test_raw_value_in_map_key()2239 fn test_raw_value_in_map_key() {
2240     #[derive(RefCast)]
2241     #[repr(transparent)]
2242     struct RawMapKey(RawValue);
2243 
2244     impl<'de> Deserialize<'de> for &'de RawMapKey {
2245         fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2246         where
2247             D: serde::Deserializer<'de>,
2248         {
2249             let raw_value = <&RawValue>::deserialize(deserializer)?;
2250             Ok(RawMapKey::ref_cast(raw_value))
2251         }
2252     }
2253 
2254     impl PartialEq for RawMapKey {
2255         fn eq(&self, other: &Self) -> bool {
2256             self.0.get() == other.0.get()
2257         }
2258     }
2259 
2260     impl Eq for RawMapKey {}
2261 
2262     impl Hash for RawMapKey {
2263         fn hash<H: Hasher>(&self, hasher: &mut H) {
2264             self.0.get().hash(hasher);
2265         }
2266     }
2267 
2268     let map_from_str: HashMap<&RawMapKey, &RawValue> =
2269         serde_json::from_str(r#" {"\\k":"\\v"} "#).unwrap();
2270     let (map_k, map_v) = map_from_str.into_iter().next().unwrap();
2271     assert_eq!("\"\\\\k\"", map_k.0.get());
2272     assert_eq!("\"\\\\v\"", map_v.get());
2273 }
2274 
2275 #[cfg(feature = "raw_value")]
2276 #[test]
test_boxed_raw_value()2277 fn test_boxed_raw_value() {
2278     #[derive(Serialize, Deserialize)]
2279     struct Wrapper {
2280         a: i8,
2281         b: Box<RawValue>,
2282         c: i8,
2283     }
2284 
2285     let wrapper_from_str: Wrapper =
2286         serde_json::from_str(r#"{"a": 1, "b": {"foo": 2}, "c": 3}"#).unwrap();
2287     assert_eq!(r#"{"foo": 2}"#, wrapper_from_str.b.get());
2288 
2289     let wrapper_from_reader: Wrapper =
2290         serde_json::from_reader(br#"{"a": 1, "b": {"foo": 2}, "c": 3}"#.as_ref()).unwrap();
2291     assert_eq!(r#"{"foo": 2}"#, wrapper_from_reader.b.get());
2292 
2293     let wrapper_from_value: Wrapper =
2294         serde_json::from_value(json!({"a": 1, "b": {"foo": 2}, "c": 3})).unwrap();
2295     assert_eq!(r#"{"foo":2}"#, wrapper_from_value.b.get());
2296 
2297     let wrapper_to_string = serde_json::to_string(&wrapper_from_str).unwrap();
2298     assert_eq!(r#"{"a":1,"b":{"foo": 2},"c":3}"#, wrapper_to_string);
2299 
2300     let wrapper_to_value = serde_json::to_value(&wrapper_from_str).unwrap();
2301     assert_eq!(json!({"a": 1, "b": {"foo": 2}, "c": 3}), wrapper_to_value);
2302 
2303     let array_from_str: Vec<Box<RawValue>> =
2304         serde_json::from_str(r#"["a", 42, {"foo": "bar"}, null]"#).unwrap();
2305     assert_eq!(r#""a""#, array_from_str[0].get());
2306     assert_eq!(r#"42"#, array_from_str[1].get());
2307     assert_eq!(r#"{"foo": "bar"}"#, array_from_str[2].get());
2308     assert_eq!(r#"null"#, array_from_str[3].get());
2309 
2310     let array_from_reader: Vec<Box<RawValue>> =
2311         serde_json::from_reader(br#"["a", 42, {"foo": "bar"}, null]"#.as_ref()).unwrap();
2312     assert_eq!(r#""a""#, array_from_reader[0].get());
2313     assert_eq!(r#"42"#, array_from_reader[1].get());
2314     assert_eq!(r#"{"foo": "bar"}"#, array_from_reader[2].get());
2315     assert_eq!(r#"null"#, array_from_reader[3].get());
2316 
2317     let array_to_string = serde_json::to_string(&array_from_str).unwrap();
2318     assert_eq!(r#"["a",42,{"foo": "bar"},null]"#, array_to_string);
2319 }
2320 
2321 #[cfg(feature = "raw_value")]
2322 #[test]
test_raw_invalid_utf8()2323 fn test_raw_invalid_utf8() {
2324     let j = &[b'"', b'\xCE', b'\xF8', b'"'];
2325     let value_err = serde_json::from_slice::<Value>(j).unwrap_err();
2326     let raw_value_err = serde_json::from_slice::<Box<RawValue>>(j).unwrap_err();
2327 
2328     assert_eq!(
2329         value_err.to_string(),
2330         "invalid unicode code point at line 1 column 4",
2331     );
2332     assert_eq!(
2333         raw_value_err.to_string(),
2334         "invalid unicode code point at line 1 column 4",
2335     );
2336 }
2337 
2338 #[cfg(feature = "raw_value")]
2339 #[test]
test_serialize_unsized_value_to_raw_value()2340 fn test_serialize_unsized_value_to_raw_value() {
2341     assert_eq!(
2342         serde_json::value::to_raw_value("foobar").unwrap().get(),
2343         r#""foobar""#,
2344     );
2345 }
2346 
2347 #[test]
test_borrow_in_map_key()2348 fn test_borrow_in_map_key() {
2349     #[derive(Deserialize, Debug)]
2350     struct Outer {
2351         #[allow(dead_code)]
2352         map: BTreeMap<MyMapKey, ()>,
2353     }
2354 
2355     #[derive(Ord, PartialOrd, Eq, PartialEq, Debug)]
2356     struct MyMapKey(usize);
2357 
2358     impl<'de> Deserialize<'de> for MyMapKey {
2359         fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2360         where
2361             D: de::Deserializer<'de>,
2362         {
2363             let s = <&str>::deserialize(deserializer)?;
2364             let n = s.parse().map_err(de::Error::custom)?;
2365             Ok(MyMapKey(n))
2366         }
2367     }
2368 
2369     let value = json!({ "map": { "1": null } });
2370     Outer::deserialize(&value).unwrap();
2371 }
2372 
2373 #[test]
test_value_into_deserializer()2374 fn test_value_into_deserializer() {
2375     #[derive(Deserialize)]
2376     struct Outer {
2377         inner: Inner,
2378     }
2379 
2380     #[derive(Deserialize)]
2381     struct Inner {
2382         string: String,
2383     }
2384 
2385     let mut map = BTreeMap::new();
2386     map.insert("inner", json!({ "string": "Hello World" }));
2387 
2388     let outer = Outer::deserialize(map.into_deserializer()).unwrap();
2389     assert_eq!(outer.inner.string, "Hello World");
2390 }
2391 
2392 #[test]
hash_positive_and_negative_zero()2393 fn hash_positive_and_negative_zero() {
2394     fn hash(obj: impl Hash) -> u64 {
2395         let mut hasher = DefaultHasher::new();
2396         obj.hash(&mut hasher);
2397         hasher.finish()
2398     }
2399 
2400     let k1 = serde_json::from_str::<Number>("0.0").unwrap();
2401     let k2 = serde_json::from_str::<Number>("-0.0").unwrap();
2402     if cfg!(feature = "arbitrary_precision") {
2403         assert_ne!(k1, k2);
2404         assert_ne!(hash(k1), hash(k2));
2405     } else {
2406         assert_eq!(k1, k2);
2407         assert_eq!(hash(k1), hash(k2));
2408     }
2409 }
2410