interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / vendor / serde_json / tests / test.rs

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