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