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