1 #![cfg(not(feature = "preserve_order"))]
3 clippy
::assertions_on_result_states
,
4 clippy
::cast_precision_loss
,
5 clippy
::derive_partial_eq_without_eq
,
6 clippy
::excessive_precision
,
8 clippy
::items_after_statements
,
9 clippy
::let_underscore_drop
,
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
17 #![cfg_attr(feature = "trace-macros", feature(trace_macros))]
18 #[cfg(feature = "trace-macros")]
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
;
33 from_reader
, from_slice
, from_str
, from_value
, json
, to_string
, to_string_pretty
, to_value
,
34 to_vec
, Deserializer
, Number
, Value
,
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}
;
44 use std
::marker
::PhantomData
;
46 use std
::str::FromStr
;
47 use std
::string
::ToString
;
49 use std
::{i16, i32, i64, i8}
;
50 use std
::{u16, u32, u64, u8}
;
52 macro_rules
! treemap
{
56 ($
($k
:expr
=> $v
:expr
),+) => {
58 let mut m
= BTreeMap
::new();
67 #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
68 #[serde(deny_unknown_fields)]
71 Frog(String
, Vec
<isize>),
72 Cat { age: usize, name: String }
,
76 #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
83 #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
88 fn test_encode_ok
<T
>(errors
: &[(T
, &str)])
90 T
: PartialEq
+ Debug
+ ser
::Serialize
,
92 for &(ref value
, out
) in errors
{
93 let out
= out
.to_string();
95 let s
= to_string(value
).unwrap();
98 let v
= to_value(value
).unwrap();
99 let s
= to_string(&v
).unwrap();
104 fn test_pretty_encode_ok
<T
>(errors
: &[(T
, &str)])
106 T
: PartialEq
+ Debug
+ ser
::Serialize
,
108 for &(ref value
, out
) in errors
{
109 let out
= out
.to_string();
111 let s
= to_string_pretty(value
).unwrap();
114 let v
= to_value(value
).unwrap();
115 let s
= to_string_pretty(&v
).unwrap();
121 fn test_write_null() {
122 let tests
= &[((), "null")];
123 test_encode_ok(tests
);
124 test_pretty_encode_ok(tests
);
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
);
135 fn test_write_i64() {
140 (i64::MIN
, &i64::MIN
.to_string()),
142 test_encode_ok(tests
);
143 test_pretty_encode_ok(tests
);
147 fn test_write_f64() {
153 (f64::MIN
, "-1.7976931348623157e308"),
154 (f64::MAX
, "1.7976931348623157e308"),
155 (f64::EPSILON
, "2.220446049250313e-16"),
157 test_encode_ok(tests
);
158 test_pretty_encode_ok(tests
);
162 fn test_encode_nonfinite_float_yields_null() {
163 let v
= to_value(::std
::f64::NAN
).unwrap();
164 assert
!(v
.is_null());
166 let v
= to_value(::std
::f64::INFINITY
).unwrap();
167 assert
!(v
.is_null());
169 let v
= to_value(::std
::f32::NAN
).unwrap();
170 assert
!(v
.is_null());
172 let v
= to_value(::std
::f32::INFINITY
).unwrap();
173 assert
!(v
.is_null());
177 fn test_write_str() {
178 let tests
= &[("", "\"\""), ("foo", "\"foo\"")];
179 test_encode_ok(tests
);
180 test_pretty_encode_ok(tests
);
184 fn test_write_bool() {
185 let tests
= &[(true, "true"), (false, "false")];
186 test_encode_ok(tests
);
187 test_pretty_encode_ok(tests
);
191 fn test_write_char() {
202 ('\x0B', "\"\\u000b
\""),
203 ('\u{3A3}', "\"\u{3A3}
\""),
205 test_encode_ok(tests);
206 test_pretty_encode_ok(tests);
210 fn test_write_list() {
213 (vec![true], "[true]"),
214 (vec![true, false], "[true,false]"),
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]]"),
224 test_pretty_encode_ok(&[
225 (vec![vec![], vec![], vec![]], pretty_str!([[], [], []])),
227 vec![vec![1, 2, 3], vec![], vec![]],
228 pretty_str!([[1, 2, 3], [], []]),
231 vec![vec![], vec![1, 2, 3], vec![]],
232 pretty_str!([[], [1, 2, 3], []]),
235 vec![vec![], vec![], vec![1, 2, 3]],
236 pretty_str!([[], [], [1, 2, 3]]),
240 test_pretty_encode_ok(&[
242 (vec![true], pretty_str!([true])),
243 (vec![true, false], pretty_str!([true, false])),
246 let long_test_list = json!([false, null, ["foo
\nbar
", 3.5]]);
249 long_test_list.clone(),
250 json_str!([false, null, ["foo
\nbar
", 3.5]]),
253 test_pretty_encode_ok(&[(
255 pretty_str!([false, null, ["foo
\nbar
", 3.5]]),
260 fn test_write_object() {
263 (treemap!("a
".to_string() => true), "{\"a\":true}
"),
266 "a
".to_string() => true,
267 "b
".to_string() => false
269 "{\"a\":true,\"b\":false}
",
276 "a
".to_string() => treemap![],
277 "b
".to_string() => treemap![],
278 "c
".to_string() => treemap![]
280 "{\"a\":{}
,\"b
\":{}
,\"c
\":{}
}",
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![]
289 "b
".to_string() => treemap![],
290 "c
".to_string() => treemap![]
292 "{\"a\":{\"a\":{\"a\":[1,2,3]}
,\"b
\":{}
,\"c
\":{}
},\"b
\":{}
,\"c
\":{}
}",
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![]
302 "c
".to_string() => treemap![]
304 "{\"a\":{}
,\"b
\":{\"a\":{\"a\":[1,2,3]}
,\"b
\":{}
,\"c
\":{}
},\"c
\":{}
}",
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![]
316 "{\"a\":{}
,\"b
\":{}
,\"c
\":{\"a\":{\"a\":[1,2,3]}
,\"b
\":{}
,\"c
\":{}
}}",
320 test_encode_ok(&[(treemap!['c' => ()], "{\"c\":null}
")]);
322 test_pretty_encode_ok(&[
325 "a
".to_string() => treemap![],
326 "b
".to_string() => treemap![],
327 "c
".to_string() => 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![]
342 "b
".to_string() => treemap![],
343 "c
".to_string() => 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![]
369 "c
".to_string() => 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![]
415 test_pretty_encode_ok(&[
418 treemap!("a
".to_string() => true),
425 "a
".to_string() => true,
426 "b
".to_string() => false
435 let complex_obj = json!({
447 "c
": (r#""\f\u001f\r""#)
456 test_pretty_encode_ok(&[(
461 "c
": (r#""\f\u001f\r""#)
472 fn test_write_tuple() {
473 test_encode_ok(&[((5,), "[5]")]);
475 test_pretty_encode_ok(&[((5,), pretty_str!([5]))]);
477 test_encode_ok(&[((5, (6, "abc
")), "[5,[6,\"abc
\"]]")]);
479 test_pretty_encode_ok(&[((5, (6, "abc
")), pretty_str!([5, [6, "abc
"]]))]);
483 fn test_write_enum() {
485 (Animal::Dog, "\"Dog
\""),
487 Animal::Frog("Henry
".to_string(), vec![]),
488 "{\"Frog\":[\"Henry\",[]]}
",
491 Animal::Frog("Henry
".to_string(), vec![349]),
492 "{\"Frog\":[\"Henry\",[349]]}
",
495 Animal::Frog("Henry
".to_string(), vec![349, 102]),
496 "{\"Frog\":[\"Henry\",[349,102]]}
",
501 name: "Kate
".to_string(),
503 "{\"Cat\":{\"age\":5,\"name\":\"Kate\"}
}",
506 Animal::AntHive(vec!["Bob
".to_string(), "Stuart
".to_string()]),
507 "{\"AntHive\":[\"Bob\",\"Stuart\"]}
",
511 test_pretty_encode_ok(&[
512 (Animal::Dog, "\"Dog
\""),
514 Animal::Frog("Henry
".to_string(), vec![]),
523 Animal::Frog("Henry
".to_string(), vec![349]),
534 Animal::Frog("Henry
".to_string(), vec![349, 102]),
549 fn test_write_option() {
550 test_encode_ok(&[(None, "null
"), (Some("jodhpurs
"), "\"jodhpurs
\"")]);
554 (Some(vec!["foo
", "bar
"]), "[\"foo
\",\"bar
\"]"),
557 test_pretty_encode_ok(&[(None, "null
"), (Some("jodhpurs
"), "\"jodhpurs
\"")]);
559 test_pretty_encode_ok(&[
561 (Some(vec!["foo
", "bar
"]), pretty_str!(["foo
", "bar
"])),
566 fn test_write_newtype_struct() {
567 #[derive(Serialize, PartialEq, Debug)]
568 struct Newtype(BTreeMap<String, i32>);
570 let inner = Newtype(treemap!(String::from("inner
") => 123));
571 let outer = treemap!(String::from("outer
") => to_value(&inner).unwrap());
573 test_encode_ok(&[(inner, r#"{"inner":123}
"#)]);
575 test_encode_ok(&[(outer, r#"{"outer":{"inner":123}
}"#)]);
579 fn test_deserialize_number_to_untagged_enum() {
580 #[derive(Eq, PartialEq, Deserialize, Debug)]
586 assert_eq!(E::N(0), E::deserialize(Number::from(0)).unwrap());
589 fn test_parse_ok<T>(tests: Vec<(&str, T)>)
591 T: Clone + Debug + PartialEq + ser::Serialize + de::DeserializeOwned,
593 for (s, value) in tests {
594 let v: T = from_str(s).unwrap();
595 assert_eq!(v, value.clone());
597 let v: T = from_slice(s.as_bytes()).unwrap();
598 assert_eq!(v, value.clone());
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());
604 // Make sure we can deserialize from a `&Value`.
605 let v = T::deserialize(&json_value).unwrap();
606 assert_eq!(v, value);
608 // Make sure we can deserialize from a `Value`.
609 let v: T = from_value(json_value.clone()).unwrap();
610 assert_eq!(v, value);
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);
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());
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());
633 // For testing representations that the deserializer accepts but the serializer
634 // never generates. These do not survive a round-trip through Value.
635 fn test_parse_unusual_ok<T>(tests: Vec<(&str, T)>)
637 T: Clone + Debug + PartialEq + ser::Serialize + de::DeserializeOwned,
639 for (s, value) in tests {
640 let v: T = from_str(s).unwrap();
641 assert_eq!(v, value.clone());
643 let v: T = from_slice(s.as_bytes()).unwrap();
644 assert_eq!(v, value.clone());
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));
655 fn test_parse_err<T>(errors: &[(&str, &'static str)])
657 T: Debug + PartialEq + de::DeserializeOwned,
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);
665 fn test_parse_slice_err<T>(errors: &[(&[u8], &'static str)])
667 T: Debug + PartialEq + de::DeserializeOwned,
669 for &(s, err) in errors {
670 test_parse_err!(from_slice::<T>(s) => err);
674 fn test_fromstr_parse_err<T>(errors: &[(&str, &'static str)])
676 T: Debug + PartialEq + FromStr,
677 <T as FromStr>::Err: ToString,
679 for &(s, err) in errors {
680 let actual = s.parse::<T>().unwrap_err().to_string();
681 assert_eq!(actual, err, "unexpected parsing error
");
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"),
693 test_parse_ok(vec![("null
", ())]);
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"),
716 fn test_parse_char() {
717 test_parse_err::<char>(&[
720 "invalid value
: string
\"ab
\", expected a character at line
1 column
4",
724 "invalid
type: integer `
10`
, expected a character at line
1 column
2",
738 ("\"\\u000b\"", '
\x0B'
),
739 ("\"\\u000B\"", '
\x0B'
),
740 ("\"\u{3A3}\"", '
\u{3A3}'
),
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"),
762 "100e777777777777777777777777777",
763 "number out of range at line 1 column 14",
766 "-100e777777777777777777777777777",
767 "number out of range at line 1 column 15",
770 "1000000000000000000000000000000000000000000000000000000000000\
771 000000000000000000000000000000000000000000000000000000000000\
772 000000000000000000000000000000000000000000000000000000000000\
773 000000000000000000000000000000000000000000000000000000000000\
774 000000000000000000000000000000000000000000000000000000000000\
776 "number out of range at line 1 column 310",
779 "1000000000000000000000000000000000000000000000000000000000000\
780 000000000000000000000000000000000000000000000000000000000000\
781 000000000000000000000000000000000000000000000000000000000000\
782 000000000000000000000000000000000000000000000000000000000000\
783 000000000000000000000000000000000000000000000000000000000000\
785 "number out of range at line 1 column 305",
788 "1000000000000000000000000000000000000000000000000000000000000\
789 000000000000000000000000000000000000000000000000000000000000\
790 000000000000000000000000000000000000000000000000000000000000\
791 000000000000000000000000000000000000000000000000000000000000\
792 000000000000000000000000000000000000000000000000000000000000\
794 "number out of range at line 1 column 303",
800 fn test_parse_i64() {
805 (&i64::MIN
.to_string(), i64::MIN
),
806 (&i64::MAX
.to_string(), i64::MAX
),
811 fn test_parse_u64() {
816 (&u64::MAX
.to_string(), u64::MAX
),
821 fn test_parse_negative_zero() {
822 for negative_zero
in &[
828 "-1e-4000000000000000000000000000000000000000000000000",
831 from_str
::<f32>(negative_zero
).unwrap().is_sign_negative(),
832 "should have been negative: {:?}",
836 from_str
::<f64>(negative_zero
).unwrap().is_sign_negative(),
837 "should have been negative: {:?}",
844 fn test_parse_f64() {
852 // https://github.com/serde-rs/json/issues/536#issuecomment-583714900
853 ("2.638344616030823e-256", 2.638344616030823e-256),
856 #[cfg(not(feature = "arbitrary_precision"))]
858 // With arbitrary-precision enabled, this parses as Number{"3.00"}
859 // but the float is Number{"3.0"}
866 (" 0.4e-01 ", 0.4e-1),
867 ("0.4e-001", 0.4e-1),
872 ("3.5E-2147483647", 0.0),
873 ("0.0100000000000000000001", 0.01),
875 &format
!("{}", (i64::MIN
as f64) - 1.0),
876 (i64::MIN
as f64) - 1.0,
879 &format
!("{}", (u64::MAX
as f64) + 1.0),
880 (u64::MAX
as f64) + 1.0,
882 (&format
!("{}", f64::EPSILON
), f64::EPSILON
),
884 "0.0000000000000000000000000000000000000000000000000123e50",
887 ("100e-777777777777777777777777777", 0.0),
889 "1010101010101010101010101010101010101010",
890 10101010101010101010e20
,
893 "0.1010101010101010101010101010101010101010",
894 0.1010101010101010101,
896 ("0e1000000000000000000000000000000000000000000000", 0.0),
898 "1000000000000000000000000000000000000000000000000000000000000\
899 000000000000000000000000000000000000000000000000000000000000\
900 000000000000000000000000000000000000000000000000000000000000\
901 000000000000000000000000000000000000000000000000000000000000\
902 000000000000000000000000000000000000000000000000000000000000\
907 "1000000000000000000000000000000000000000000000000000000000000\
908 000000000000000000000000000000000000000000000000000000000000\
909 000000000000000000000000000000000000000000000000000000000000\
910 000000000000000000000000000000000000000000000000000000000000\
911 000000000000000000000000000000000000000000000000000000000000\
916 "1000000000000000000000000000000000000000000000000000000000000\
917 000000000000000000000000000000000000000000000000000000000000\
918 000000000000000000000000000000000000000000000000000000000000\
919 000000000000000000000000000000000000000000000000000000000000\
920 000000000000000000000000000000000000000000000000000000000000\
925 "1000000000000000000000000000000000000000000000000000000000000\
926 000000000000000000000000000000000000000000000000000000000000\
927 000000000000000000000000000000000000000000000000000000000000\
928 000000000000000000000000000000000000000000000000000000000000\
929 000000000000000000000000000000000000000000000000000000000000\
930 000000000000000000e-10",
937 fn test_value_as_f64() {
938 let v
= serde_json
::from_str
::<Value
>("1e1000");
940 #[cfg(not(feature = "arbitrary_precision"))]
943 #[cfg(feature = "arbitrary_precision")]
944 assert_eq
!(v
.unwrap().as_f64(), None
);
947 // Test roundtrip with some values that were not perfectly roundtripped by the
948 // old f64 deserializer.
949 #[cfg(feature = "float_roundtrip")]
951 fn test_roundtrip_f64() {
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
,
967 let json
= serde_json
::to_string(&float
).unwrap();
968 let output
: f64 = serde_json
::from_str(&json
).unwrap();
969 assert_eq
!(float
, output
);
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
);
984 fn test_serialize_char() {
987 let mut map
= BTreeMap
::new();
992 assert_eq
!(&Value
::Null
, value
.get("c").unwrap());
995 #[cfg(feature = "arbitrary_precision")]
997 fn test_malicious_number() {
999 #[serde(rename = "$serde_json::private::Number")]
1001 #[serde(rename = "$serde_json::private::Number")]
1005 let actual
= serde_json
::to_value(&S { f: "not a number" }
)
1008 assert_eq
!(actual
, "invalid number at line 1 column 1");
1012 fn test_parse_number() {
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()),
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"),
1028 #[cfg(feature = "arbitrary_precision")]
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())),
1041 Number
::from_string_unchecked("2.3e999".to_owned()),
1045 Number
::from_string_unchecked("-2.3e999".to_owned()),
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"),
1057 "\"\\uD83C\\uFFFF\"",
1058 "lone leading surrogate in hex escape at line 1 column 13",
1062 "control character (\\u0000-\\u001F) found while parsing a string at line 2 column 0",
1066 "control character (\\u0000-\\u001F) found while parsing a string at line 1 column 2",
1070 test_parse_slice_err
::<String
>(&[
1072 &[b'
"', 159, 146, 150, b'"'
],
1073 "invalid unicode code point at line 1 column 5",
1076 &[b'
"', b'\\', b'n', 159, 146, 150, b'"'
],
1077 "invalid unicode code point at line 1 column 7",
1080 &[b'
"', b'\\', b'u', 48, 48, 51],
1081 "EOF
while parsing a string at line
1 column
6",
1084 &[b'"'
, b'
\\'
, b'u'
, 250, 48, 51, 48, b'
"'],
1085 "invalid escape at line
1 column
4",
1088 &[b'"'
, b'
\\'
, b'u'
, 48, 250, 51, 48, b'
"'],
1089 "invalid escape at line
1 column
5",
1092 &[b'"'
, b'
\\'
, b'u'
, 48, 48, 250, 48, b'
"'],
1093 "invalid escape at line
1 column
6",
1096 &[b'"'
, b'
\\'
, b'u'
, 48, 48, 51, 250, b'
"'],
1097 "invalid escape at line
1 column
7",
1100 &[b'"'
, b'
\n'
, b'
"'],
1101 "control
character (\\u0000
-\\u001F
) found
while parsing a string at line
2 column
0",
1104 &[b'"'
, b'
\x1F'
, b'
"'],
1105 "control
character (\\u0000
-\\u001F
) found
while parsing a string at line
1 column
2",
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()),
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"),
1139 ("[null
]", vec![()]),
1140 (" [ null
] ", vec![()]),
1143 test_parse_ok(vec![("[true]", vec![true])]);
1145 test_parse_ok(vec![("[3,1]", vec![3u64, 1]), (" [ 3 , 1 ] ", vec![3, 1])]);
1147 test_parse_ok(vec![("[[3], [1, 2]]", vec![vec![3u64], vec![1, 2]])]);
1149 test_parse_ok(vec![("[1]", (1u64,))]);
1151 test_parse_ok(vec![("[1, 2]", (1u64, 2u64))]);
1153 test_parse_ok(vec![("[1, 2, 3]", (1u64, 2u64, 3u64))]);
1155 test_parse_ok(vec![("[1, [2, 3]]", (1u64, (2u64, 3u64)))]);
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"),
1177 ("{ }
", treemap!()),
1178 ("{\"a\":3}
", treemap!("a
".to_string() => 3u64)),
1179 ("{ \"a\" : 3 }
", treemap!("a
".to_string() => 3)),
1181 "{\"a\":3,\"b\":4}
",
1182 treemap!("a
".to_string() => 3, "b
".to_string() => 4),
1185 " { \"a\" : 3 , \"b\" : 4 }
",
1186 treemap!("a
".to_string() => 3, "b
".to_string() => 4),
1190 test_parse_ok(vec![(
1191 "{\"a\": {\"b\": 3, \"c\": 4}
}",
1193 "a
".to_string() => treemap!(
1194 "b
".to_string() => 3u64,
1195 "c
".to_string() => 4
1200 test_parse_ok(vec![("{\"c\":null}
", treemap!('c' => ()))]);
1204 fn test_parse_struct() {
1205 test_parse_err::<Outer>(&[
1208 "invalid
type: integer `
5`
, expected
struct Outer at line
1 column
1",
1212 "invalid
type: string
\"hello
\", expected
struct Outer at line
1 column
7",
1215 "{\"inner\": true}
",
1216 "invalid
type: boolean `
true`
, expected a sequence at line
1 column
14",
1218 ("{}
", "missing field `inner` at line
1 column
2"),
1220 r#"{"inner": [{"b": 42, "c": []}
]}"#,
1221 "missing field `a` at line
1 column
29",
1230 Outer { inner: vec![] },
1235 { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
1242 c: vec!["abc
".to_string(), "xyz
".to_string()],
1248 let v: Outer = from_str(
1251 [ null
, 2, [\"abc
\", \"xyz
\"] ]
1263 c: vec!["abc
".to_string(), "xyz
".to_string()],
1268 let j = json!([null, 2, []]);
1269 Inner::deserialize(&j).unwrap();
1270 Inner::deserialize(j).unwrap();
1274 fn test_parse_option() {
1276 ("null
", None::<String>),
1277 ("\"jodhpurs
\"", Some("jodhpurs
".to_string())),
1280 #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1285 let value: Foo = from_str("{}
").unwrap();
1286 assert_eq!(value, Foo { x: None });
1289 ("{\"x\": null}
", Foo { x: None }),
1290 ("{\"x\": 5}
", Foo { x: Some(5) }),
1295 fn test_parse_enum_errors() {
1296 test_parse_err::<Animal>(
1298 ("{}
", "expected value at line
1 column
2"),
1299 ("[]", "expected value at line
1 column
1"),
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
"),
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"),
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"),
1326 fn test_parse_enum() {
1328 ("\"Dog
\"", Animal::Dog),
1329 (" \"Dog
\" ", Animal::Dog),
1331 "{\"Frog\":[\"Henry\",[]]}
",
1332 Animal::Frog("Henry
".to_string(), vec![]),
1335 " { \"Frog\": [ \"Henry\" , [ 349, 102 ] ] }
",
1336 Animal::Frog("Henry
".to_string(), vec![349, 102]),
1339 "{\"Cat\": {\"age\": 5, \"name\": \"Kate\"}
}",
1342 name: "Kate
".to_string(),
1346 " { \"Cat\" : { \"age\" : 5 , \"name\" : \"Kate\" }
} ",
1349 name: "Kate
".to_string(),
1353 " { \"AntHive\" : [\"Bob\", \"Stuart\"] }
",
1354 Animal::AntHive(vec!["Bob
".to_string(), "Stuart
".to_string()]),
1358 test_parse_unusual_ok(vec![
1359 ("{\"Dog\":null}
", Animal::Dog),
1360 (" { \"Dog\" : null }
", Animal::Dog),
1363 test_parse_ok(vec![(
1367 " \"b
\": {\"Frog\":[\"Henry\", []]}
",
1371 "a
".to_string() => Animal::Dog,
1372 "b
".to_string() => Animal::Frog("Henry
".to_string(), vec![])
1378 fn test_parse_trailing_whitespace() {
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]),
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",
1396 fn test_missing_option_field() {
1397 #[derive(Debug, PartialEq, Deserialize)]
1402 let value: Foo = from_str("{}
").unwrap();
1403 assert_eq!(value, Foo { x: None });
1405 let value: Foo = from_str("{\"x\": 5}
").unwrap();
1406 assert_eq!(value, Foo { x: Some(5) });
1408 let value: Foo = from_value(json!({})).unwrap();
1409 assert_eq!(value, Foo { x: None });
1411 let value: Foo = from_value(json!({"x": 5})).unwrap();
1412 assert_eq!(value, Foo { x: Some(5) });
1416 fn test_missing_nonoption_field() {
1417 #[derive(Debug, PartialEq, Deserialize)]
1422 test_parse_err::<Foo>(&[("{}
", "missing field `x` at line
1 column
2")]);
1426 fn test_missing_renamed_field() {
1427 #[derive(Debug, PartialEq, Deserialize)]
1429 #[serde(rename = "y
")]
1433 let value: Foo = from_str("{}
").unwrap();
1434 assert_eq!(value, Foo { x: None });
1436 let value: Foo = from_str("{\"y\": 5}
").unwrap();
1437 assert_eq!(value, Foo { x: Some(5) });
1439 let value: Foo = from_value(json!({})).unwrap();
1440 assert_eq!(value, Foo { x: None });
1442 let value: Foo = from_value(json!({"y": 5})).unwrap();
1443 assert_eq!(value, Foo { x: Some(5) });
1447 fn test_serialize_seq_with_no_len() {
1448 #[derive(Clone, Debug, PartialEq)]
1449 struct MyVec<T>(Vec<T>);
1451 impl<T> ser::Serialize for MyVec<T>
1456 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1460 let mut seq = serializer.serialize_seq(None)?;
1461 for elem in &self.0 {
1462 seq.serialize_element(elem)?;
1469 marker: PhantomData<MyVec<T>>,
1472 impl<'de, T> de::Visitor<'de> for Visitor<T>
1474 T: de::Deserialize<'de>,
1476 type Value = MyVec<T>;
1478 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1479 formatter.write_str("array
")
1483 fn visit_unit<E>(self) -> Result<MyVec<T>, E>
1487 Ok(MyVec(Vec::new()))
1491 fn visit_seq<V>(self, mut visitor: V) -> Result<MyVec<T>, V::Error>
1493 V: de::SeqAccess<'de>,
1495 let mut values = Vec::new();
1497 while let Some(value) = visitor.next_element()? {
1505 impl<'de, T> de::Deserialize<'de> for MyVec<T>
1507 T: de::Deserialize<'de>,
1509 fn deserialize<D>(deserializer: D) -> Result<MyVec<T>, D::Error>
1511 D: de::Deserializer<'de>,
1513 deserializer.deserialize_map(Visitor {
1514 marker: PhantomData,
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);
1524 test_encode_ok(&[(vec.clone(), "[[],[]]")]);
1526 let s = to_string_pretty(&vec).unwrap();
1527 let expected = pretty_str!([[], []]);
1528 assert_eq!(s, expected);
1532 fn test_serialize_map_with_no_len() {
1533 #[derive(Clone, Debug, PartialEq)]
1534 struct MyMap<K, V>(BTreeMap<K, V>);
1536 impl<K, V> ser::Serialize for MyMap<K, V>
1538 K: ser::Serialize + Ord,
1542 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1546 let mut map = serializer.serialize_map(None)?;
1547 for (k, v) in &self.0 {
1548 map.serialize_entry(k, v)?;
1554 struct Visitor<K, V> {
1555 marker: PhantomData<MyMap<K, V>>,
1558 impl<'de, K, V> de::Visitor<'de> for Visitor<K, V>
1560 K: de::Deserialize<'de> + Eq + Ord,
1561 V: de::Deserialize<'de>,
1563 type Value = MyMap<K, V>;
1565 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1566 formatter.write_str("map
")
1570 fn visit_unit<E>(self) -> Result<MyMap<K, V>, E>
1574 Ok(MyMap(BTreeMap::new()))
1578 fn visit_map<Visitor>(self, mut visitor: Visitor) -> Result<MyMap<K, V>, Visitor::Error>
1580 Visitor: de::MapAccess<'de>,
1582 let mut values = BTreeMap::new();
1584 while let Some((key, value)) = visitor.next_entry()? {
1585 values.insert(key, value);
1592 impl<'de, K, V> de::Deserialize<'de> for MyMap<K, V>
1594 K: de::Deserialize<'de> + Eq + Ord,
1595 V: de::Deserialize<'de>,
1597 fn deserialize<D>(deserializer: D) -> Result<MyMap<K, V>, D::Error>
1599 D: de::Deserializer<'de>,
1601 deserializer.deserialize_map(Visitor {
1602 marker: PhantomData,
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);
1612 test_encode_ok(&[(map.clone(), "{\"a\":{}
,\"b
\":{}
}")]);
1614 let s = to_string_pretty(&map).unwrap();
1615 let expected = pretty_str!({
1619 assert_eq!(s, expected);
1624 fn test_deserialize_from_stream() {
1625 use serde_json::to_writer;
1626 use std::net::{TcpListener, TcpStream};
1629 #[derive(Debug, PartialEq, Serialize, Deserialize)]
1634 let l = TcpListener::bind("localhost
:20000").unwrap();
1638 for stream in l.incoming() {
1639 let mut stream = stream.unwrap();
1640 let read_stream = stream.try_clone().unwrap();
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,
1647 to_writer(&mut stream, &response).unwrap();
1651 let mut stream = TcpStream::connect("localhost
:20000").unwrap();
1652 let request = Message {
1653 message: "hi there
".to_string(),
1655 to_writer(&mut stream, &request).unwrap();
1657 let mut de = Deserializer::from_reader(stream);
1658 let response = Message::deserialize(&mut de).unwrap();
1660 assert_eq!(request, response);
1664 fn test_serialize_rejects_bool_keys() {
1670 let err = to_vec(&map).unwrap_err();
1671 assert_eq!(err.to_string(), "key must be a string
");
1675 fn test_serialize_rejects_adt_keys() {
1682 let err = to_vec(&map).unwrap_err();
1683 assert_eq!(err.to_string(), "key must be a string
");
1687 fn test_bytes_ser() {
1689 let bytes = Bytes::new(&buf);
1690 assert_eq!(to_string(&bytes).unwrap(), "[]".to_string());
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());
1698 fn test_byte_buf_ser() {
1699 let bytes = ByteBuf::new();
1700 assert_eq!(to_string(&bytes).unwrap(), "[]".to_string());
1702 let bytes = ByteBuf::from(vec![1, 2, 3]);
1703 assert_eq!(to_string(&bytes).unwrap(), "[1,2,3]".to_string());
1707 fn test_byte_buf_de() {
1708 let bytes = ByteBuf::new();
1709 let v: ByteBuf = from_str("[]").unwrap();
1710 assert_eq!(v, bytes);
1712 let bytes = ByteBuf::from(vec![1, 2, 3]);
1713 let v: ByteBuf = from_str("[1, 2, 3]").unwrap();
1714 assert_eq!(v, bytes);
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);
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);
1727 let bytes = ByteBuf::from(vec![237, 160, 188, 32]);
1728 let v: ByteBuf = from_str(r#""\ud83c ""#).unwrap();
1729 assert_eq!(v, bytes);
1731 let bytes = ByteBuf::from(vec![237, 176, 129]);
1732 let v: ByteBuf = from_str(r#""\udc01""#).unwrap();
1733 assert_eq!(v, bytes);
1735 let res = from_str::<ByteBuf>(r#""\ud83c\!""#);
1736 assert!(res.is_err());
1738 let res = from_str::<ByteBuf>(r#""\ud83c\u""#);
1739 assert!(res.is_err());
1741 let res = from_str::<ByteBuf>(r#""\ud83c\ud83c""#);
1742 assert!(res.is_err());
1745 #[cfg(feature = "raw_value
")]
1747 fn test_raw_de_lone_surrogate() {
1748 use serde_json::value::RawValue;
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());
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);
1768 fn test_json_pointer() {
1769 // Test case taken from https://tools.ietf.org/html/rfc6901#page-5
1770 let data: Value = from_str(
1772 "foo": ["bar", "baz"],
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));
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());
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(
1809 "foo": ["bar", "baz"],
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);
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());
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
"));
1848 // Example of ownership stealing
1850 data.pointer_mut("/a
~1b
")
1851 .map(|m| mem::replace(m, json!(null)))
1855 assert_eq!(data.pointer("/a
~1b
").unwrap(), &json!(null));
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);
1864 fn test_stack_overflow() {
1865 let brackets: String = iter::repeat('[')
1867 .chain(iter::repeat(']').take(127))
1869 let _: Value = from_str(&brackets).unwrap();
1871 let brackets = "[".repeat(129);
1872 test_parse_err::<Value>(&[(&brackets, "recursion limit exceeded at line
1 column
128")]);
1876 #[cfg(feature = "unbounded_depth
")]
1877 fn test_disable_recursion_limit() {
1878 let brackets: String = iter::repeat('[')
1880 .chain(iter::repeat(']').take(140))
1883 let mut deserializer = Deserializer::from_str(&brackets);
1884 deserializer.disable_recursion_limit();
1885 Value::deserialize(&mut deserializer).unwrap();
1889 fn test_integer_key() {
1890 // map with integer keys
1895 let j = r#"{"-1":6,"1":2}
"#;
1896 test_encode_ok(&[(&map, j)]);
1897 test_parse_ok(vec![(j, map)]);
1899 let j = r#"{"x":null}
"#;
1900 test_parse_err::<BTreeMap<i32, ()>>(&[(
1902 "invalid
type: string
\"x
\", expected
i32 at line
1 column
4",
1907 fn test_integer128_key() {
1908 let map = treemap! {
1909 100000000000000000000000000000000000000u128 => ()
1911 let j = r#"{"100000000000000000000000000000000000000":null}
"#;
1912 assert_eq!(to_string(&map).unwrap(), j);
1913 assert_eq!(from_str::<BTreeMap<u128, ()>>(j).unwrap(), map);
1917 fn test_deny_float_key() {
1918 #[derive(Eq, PartialEq, Ord, PartialOrd)]
1920 impl Serialize for Float {
1921 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1925 serializer.serialize_f32(1.0)
1929 // map with float key
1930 let map = treemap!(Float => "x
");
1931 assert!(serde_json::to_value(&map).is_err());
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);
1940 #[derive(Deserialize, Debug, Ord, PartialOrd, Eq, PartialEq)]
1941 struct NewtypeStr<'a>(&'a str);
1943 let map: BTreeMap<NewtypeStr, ()> = from_str("{\"borrowed\":null}
").unwrap();
1944 let expected = treemap! { NewtypeStr("borrowed") => () };
1945 assert_eq!(map, expected);
1949 fn test_effectively_string_keys() {
1950 #[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Clone, Serialize, Deserialize)]
1955 let map = treemap! {
1959 let expected = r#"{"One":1,"Two":2}
"#;
1960 test_encode_ok(&[(&map, expected)]);
1961 test_parse_ok(vec![(expected, map)]);
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
1969 let expected = r#"{"one":1,"zero":0}
"#;
1970 test_encode_ok(&[(&map, expected)]);
1971 test_parse_ok(vec![(expected, map)]);
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.
1979 <Result<(), ()> as Clone>::clone(&Ok(())),
1980 <Result<(), ()> as Clone>::clone(&Err(()))
1983 // Same thing but in the map values.
1985 "ok
": <Result<(), ()> as Clone>::clone(&Ok(())),
1986 "err
": <Result<(), ()> as Clone>::clone(&Err(()))
1989 // It works in map keys but only if they are parenthesized.
1991 (<Result<&str, ()> as Clone>::clone(&Ok("")).unwrap()): "ok
",
1992 (<Result<(), &str> as Clone>::clone(&Err("")).unwrap_err()): "err
"
1995 #[deny(unused_results)]
1996 let _ = json!({ "architecture": [true, null] });
2001 #[derive(Debug, PartialEq, Eq, Deserialize)]
2006 assert!(from_str::<E>(r#" "V"0 "#).is_err());
2008 assert_eq!(from_str::<E>(r#"{"V": 0}
"#).unwrap(), E::V(0));
2011 macro_rules! number_partialeq_ok {
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);
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
2037 #[cfg(feature = "arbitrary_precision
")]
2038 fn test_partialeq_integer128() {
2039 number_partialeq_ok!(i128::MIN i128::MAX u128::MIN u128::MAX)
2043 fn test_partialeq_string() {
2044 let v = to_value("42").unwrap();
2045 assert_eq!(v, "42");
2046 assert_eq!("42", v);
2048 assert_eq!(v, String::from("42"));
2049 assert_eq!(String::from("42"), v);
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");
2063 struct FailReader(io::ErrorKind);
2065 impl io::Read for FailReader {
2066 fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
2067 Err(io::Error::new(self.0, "oh no
!"))
2072 fn test_category() {
2073 assert!(from_str::<String>("123").unwrap_err().is_data());
2075 assert!(from_str::<String>("]").unwrap_err().is_syntax());
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());
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());
2089 assert!(from_str::<BTreeMap<String, usize>>("{")
2092 assert!(from_str::<BTreeMap<String, usize>>("{\"k
\"")
2095 assert!(from_str::<BTreeMap<String, usize>>("{\"k
\":")
2098 assert!(from_str::<BTreeMap<String, usize>>("{\"k
\":0")
2101 assert!(from_str::<BTreeMap<String, usize>>("{\"k
\":0,")
2105 let fail = FailReader(io::ErrorKind::NotConnected);
2106 assert!(from_reader::<_, String>(fail).unwrap_err().is_io());
2110 // Clippy false positive: https://github.com/Manishearth/rust-clippy/issues/292
2111 #[allow(clippy::needless_lifetimes)]
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()
2118 io_error::<String>("\"\\u
").kind(),
2119 io::ErrorKind::UnexpectedEof
2121 assert_eq!(io_error::<String>("0").kind(), io::ErrorKind::InvalidData);
2122 assert_eq!(io_error::<String>("]").kind(), io::ErrorKind::InvalidData);
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);
2131 let s: &str = from_str("\"borrowed
\"").unwrap();
2132 assert_eq!("borrowed
", s);
2134 let s: &str = from_slice(b"\"borrowed
\"").unwrap();
2135 assert_eq!("borrowed
", s);
2139 fn null_invalid_type() {
2140 let err = serde_json::from_str::<String>("null
").unwrap_err();
2143 String::from("invalid
type: null
, expected a string at line
1 column
4")
2148 fn test_integer128() {
2149 let signed = &[i128::min_value(), -1, 0, 1, i128::max_value()];
2150 let unsigned = &[0, 1, u128::max_value()];
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);
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);
2164 test_parse_err::<i128>(&[
2166 "-170141183460469231731687303715884105729",
2167 "number out of range at line
1 column
40",
2170 "170141183460469231731687303715884105728",
2171 "number out of range at line
1 column
39",
2175 test_parse_err::<u128>(&[
2176 ("-1", "number out of range at line
1 column
1"),
2178 "340282366920938463463374607431768211456",
2179 "number out of range at line
1 column
39",
2184 #[cfg(feature = "raw_value
")]
2186 fn test_borrowed_raw_value() {
2187 #[derive(Serialize, Deserialize)]
2188 struct Wrapper<'a> {
2195 let wrapper_from_str: Wrapper =
2196 serde_json::from_str(r#"{"a": 1, "b": {"foo": 2}
, "c": 3}"#).unwrap();
2197 assert_eq!(r#"{"foo": 2}
"#, wrapper_from_str.b.get());
2199 let wrapper_to_string = serde_json::to_string(&wrapper_from_str).unwrap();
2200 assert_eq!(r#"{"a":1,"b":{"foo": 2}
,"c":3}"#, wrapper_to_string);
2202 let wrapper_to_value = serde_json::to_value(&wrapper_from_str).unwrap();
2203 assert_eq!(json!({"a": 1, "b": {"foo": 2}, "c
": 3}), wrapper_to_value);
2205 let array_from_str: Vec<&RawValue> =
2206 serde_json::from_str(r#"["a", 42, {"foo": "bar"}
, null
]"#).unwrap();
2207 assert_eq!(r#""a""#, array_from_str[0].get());
2208 assert_eq!(r#"42"#, array_from_str[1].get());
2209 assert_eq!(r#"{"foo": "bar"}
"#, array_from_str[2].get());
2210 assert_eq!(r#"null
"#, array_from_str[3].get());
2212 let array_to_string = serde_json::to_string(&array_from_str).unwrap();
2213 assert_eq!(r#"["a",42,{"foo": "bar"}
,null
]"#, array_to_string);
2216 #[cfg(feature = "raw_value
")]
2218 fn test_raw_value_in_map_key() {
2220 #[repr(transparent)]
2221 struct RawMapKey(RawValue);
2223 impl<'de> Deserialize<'de> for &'de RawMapKey {
2224 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2226 D: serde::Deserializer<'de>,
2228 let raw_value = <&RawValue>::deserialize(deserializer)?;
2229 Ok(RawMapKey::ref_cast(raw_value))
2233 impl PartialEq for RawMapKey {
2234 fn eq(&self, other: &Self) -> bool {
2235 self.0.get() == other.0.get()
2239 impl Eq for RawMapKey {}
2241 impl Hash for RawMapKey {
2242 fn hash<H: Hasher>(&self, hasher: &mut H) {
2243 self.0.get().hash(hasher);
2247 let map_from_str: HashMap<&RawMapKey, &RawValue> =
2248 serde_json::from_str(r#" {"\\k":"\\v"}
"#).unwrap();
2249 let (map_k, map_v) = map_from_str.into_iter().next().unwrap();
2250 assert_eq!("\"\\\\k
\"", map_k.0.get());
2251 assert_eq!("\"\\\\v
\"", map_v.get());
2254 #[cfg(feature = "raw_value
")]
2256 fn test_boxed_raw_value() {
2257 #[derive(Serialize, Deserialize)]
2264 let wrapper_from_str: Wrapper =
2265 serde_json::from_str(r#"{"a": 1, "b": {"foo": 2}
, "c": 3}"#).unwrap();
2266 assert_eq!(r#"{"foo": 2}
"#, wrapper_from_str.b.get());
2268 let wrapper_from_reader: Wrapper =
2269 serde_json::from_reader(br#"{"a": 1, "b": {"foo": 2}
, "c": 3}"#.as_ref()).unwrap();
2270 assert_eq!(r#"{"foo": 2}
"#, wrapper_from_reader.b.get());
2272 let wrapper_from_value: Wrapper =
2273 serde_json::from_value(json!({"a": 1, "b": {"foo": 2}, "c
": 3})).unwrap();
2274 assert_eq!(r#"{"foo":2}
"#, wrapper_from_value.b.get());
2276 let wrapper_to_string = serde_json::to_string(&wrapper_from_str).unwrap();
2277 assert_eq!(r#"{"a":1,"b":{"foo": 2}
,"c":3}"#, wrapper_to_string);
2279 let wrapper_to_value = serde_json::to_value(&wrapper_from_str).unwrap();
2280 assert_eq!(json!({"a": 1, "b": {"foo": 2}, "c
": 3}), wrapper_to_value);
2282 let array_from_str: Vec<Box<RawValue>> =
2283 serde_json::from_str(r#"["a", 42, {"foo": "bar"}
, null
]"#).unwrap();
2284 assert_eq!(r#""a""#, array_from_str[0].get());
2285 assert_eq!(r#"42"#, array_from_str[1].get());
2286 assert_eq!(r#"{"foo": "bar"}
"#, array_from_str[2].get());
2287 assert_eq!(r#"null
"#, array_from_str[3].get());
2289 let array_from_reader: Vec<Box<RawValue>> =
2290 serde_json::from_reader(br#"["a", 42, {"foo": "bar"}
, null
]"#.as_ref()).unwrap();
2291 assert_eq!(r#""a""#, array_from_reader[0].get());
2292 assert_eq!(r#"42"#, array_from_reader[1].get());
2293 assert_eq!(r#"{"foo": "bar"}
"#, array_from_reader[2].get());
2294 assert_eq!(r#"null
"#, array_from_reader[3].get());
2296 let array_to_string = serde_json::to_string(&array_from_str).unwrap();
2297 assert_eq!(r#"["a",42,{"foo": "bar"}
,null
]"#, array_to_string);
2300 #[cfg(feature = "raw_value
")]
2302 fn test_raw_invalid_utf8() {
2303 let j = &[b'"'
, b'
\xCE'
, b'
\xF8'
, b'
"'];
2304 let value_err = serde_json::from_slice::<Value>(j).unwrap_err();
2305 let raw_value_err = serde_json::from_slice::<Box<RawValue>>(j).unwrap_err();
2308 value_err.to_string(),
2309 "invalid unicode code point at line
1 column
4",
2312 raw_value_err.to_string(),
2313 "invalid unicode code point at line
1 column
4",
2317 #[cfg(feature = "raw_value
")]
2319 fn test_serialize_unsized_value_to_raw_value() {
2321 serde_json::value::to_raw_value("foobar
").unwrap().get(),
2327 fn test_borrow_in_map_key() {
2328 #[derive(Deserialize, Debug)]
2331 map: BTreeMap<MyMapKey, ()>,
2334 #[derive(Ord, PartialOrd, Eq, PartialEq, Debug)]
2335 struct MyMapKey(usize);
2337 impl<'de> Deserialize<'de> for MyMapKey {
2338 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2340 D: de::Deserializer<'de>,
2342 let s = <&str>::deserialize(deserializer)?;
2343 let n = s.parse().map_err(de::Error::custom)?;
2348 let value = json!({ "map": { "1": null } });
2349 Outer::deserialize(&value).unwrap();
2353 fn test_value_into_deserializer() {
2354 #[derive(Deserialize)]
2359 #[derive(Deserialize)]
2364 let mut map = BTreeMap::new();
2365 map.insert("inner
", json!({ "string": "Hello World" }));
2367 let outer = Outer::deserialize(map.into_deserializer()).unwrap();
2368 assert_eq!(outer.inner.string, "Hello World
");
2372 fn hash_positive_and_negative_zero() {
2373 fn hash(obj: impl Hash) -> u64 {
2374 let mut hasher = DefaultHasher::new();
2375 obj.hash(&mut hasher);
2379 let k1 = serde_json::from_str::<Number>("0.0").unwrap();
2380 let k2 = serde_json::from_str::<Number>("-0.0").unwrap();
2381 if cfg!(feature = "arbitrary_precision
") {
2383 assert_ne!(hash(k1), hash(k2));
2386 assert_eq!(hash(k1), hash(k2));