Debian Codegraph @

.cargo/vendor/serde_json/tests/test.rs

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