Debian Codegraph @

third_party/rust/serde_json/tests/test.rs

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