Debian Codegraph @

third_party/rust/ron/src/de/tests.rs

raw
1 use serde_bytes;
2 use serde_derive::Deserialize;
3
4 use crate::{
5 error::{Error, Position, SpannedError, SpannedResult},
6 parse::Parser,
7 value::Number,
8 };
9
10 #[derive(Debug, PartialEq, Deserialize)]
11 struct EmptyStruct1;
12
13 #[derive(Debug, PartialEq, Deserialize)]
14 struct EmptyStruct2 {}
15
16 #[derive(Debug, PartialEq, Deserialize)]
17 struct NewType(i32);
18
19 #[derive(Debug, PartialEq, Deserialize)]
20 #[serde(rename = "")]
21 struct UnnamedNewType(i32);
22
23 #[derive(Debug, PartialEq, Deserialize)]
24 struct TupleStruct(f32, f32);
25
26 #[derive(Debug, PartialEq, Deserialize)]
27 #[serde(rename = "")]
28 struct UnnamedTupleStruct(f32, f32);
29
30 #[derive(Clone, Copy, Debug, PartialEq, Deserialize)]
31 struct MyStruct {
32 x: f32,
33 y: f32,
34 }
35
36 #[derive(Clone, Copy, Debug, PartialEq, Deserialize)]
37 enum MyEnum {
38 A,
39 B(bool),
40 C(bool, f32),
41 D { a: i32, b: i32 },
42 }
43
44 #[derive(Debug, Deserialize, PartialEq)]
45 struct BytesStruct {
46 small: Vec<u8>,
47 #[serde(with = "serde_bytes")]
48 large: Vec<u8>,
49 }
50
51 #[test]
52 fn test_empty_struct() {
53 check_from_str_bytes_reader("EmptyStruct1", Ok(EmptyStruct1));
54 check_from_str_bytes_reader("EmptyStruct2()", Ok(EmptyStruct2 {}));
55 }
56
57 #[test]
58 fn test_struct() {
59 let my_struct = MyStruct { x: 4.0, y: 7.0 };
60
61 check_from_str_bytes_reader("MyStruct(x:4,y:7,)", Ok(my_struct));
62 check_from_str_bytes_reader("(x:4,y:7)", Ok(my_struct));
63
64 check_from_str_bytes_reader("NewType(42)", Ok(NewType(42)));
65 check_from_str_bytes_reader("(33)", Ok(NewType(33)));
66
67 check_from_str_bytes_reader::<NewType>(
68 "NewType",
69 Err(SpannedError {
70 code: Error::ExpectedNamedStructLike("NewType"),
71 position: Position { line: 1, col: 8 },
72 }),
73 );
74 check_from_str_bytes_reader::<UnnamedNewType>(
75 "",
76 Err(SpannedError {
77 code: Error::ExpectedStructLike,
78 position: Position { line: 1, col: 1 },
79 }),
80 );
81 check_from_str_bytes_reader("(33)", Ok(UnnamedNewType(33)));
82 check_from_str_bytes_reader::<UnnamedNewType>(
83 "Newtype",
84 Err(SpannedError {
85 code: Error::ExpectedNamedStructLike(""),
86 position: Position { line: 1, col: 8 },
87 }),
88 );
89
90 check_from_str_bytes_reader("TupleStruct(2,5,)", Ok(TupleStruct(2.0, 5.0)));
91 check_from_str_bytes_reader("(3,4)", Ok(TupleStruct(3.0, 4.0)));
92 check_from_str_bytes_reader::<TupleStruct>(
93 "",
94 Err(SpannedError {
95 code: Error::ExpectedNamedStructLike("TupleStruct"),
96 position: Position { line: 1, col: 1 },
97 }),
98 );
99 check_from_str_bytes_reader::<UnnamedTupleStruct>(
100 "TupleStruct(2,5,)",
101 Err(SpannedError {
102 code: Error::ExpectedNamedStructLike(""),
103 position: Position { line: 1, col: 12 },
104 }),
105 );
106 check_from_str_bytes_reader("(3,4)", Ok(UnnamedTupleStruct(3.0, 4.0)));
107 check_from_str_bytes_reader::<UnnamedTupleStruct>(
108 "",
109 Err(SpannedError {
110 code: Error::ExpectedStructLike,
111 position: Position { line: 1, col: 1 },
112 }),
113 );
114 }
115
116 #[test]
117 fn test_unclosed_limited_seq_struct() {
118 #[derive(Debug, PartialEq)]
119 struct LimitedStruct;
120
121 impl<'de> serde::Deserialize<'de> for LimitedStruct {
122 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
123 struct Visitor;
124
125 impl<'de> serde::de::Visitor<'de> for Visitor {
126 type Value = LimitedStruct;
127
128 // GRCOV_EXCL_START
129 fn expecting(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
130 fmt.write_str("struct LimitedStruct")
131 }
132 // GRCOV_EXCL_STOP
133
134 fn visit_map<A: serde::de::MapAccess<'de>>(
135 self,
136 _map: A,
137 ) -> Result<Self::Value, A::Error> {
138 Ok(LimitedStruct)
139 }
140 }
141
142 deserializer.deserialize_struct("LimitedStruct", &[], Visitor)
143 }
144 }
145
146 check_from_str_bytes_reader::<LimitedStruct>(
147 "(",
148 Err(SpannedError {
149 code: Error::ExpectedStructLikeEnd,
150 position: Position { line: 1, col: 2 },
151 }),
152 )
153 }
154
155 #[test]
156 fn test_unclosed_limited_seq() {
157 #[derive(Debug, PartialEq)]
158 struct LimitedSeq;
159
160 impl<'de> serde::Deserialize<'de> for LimitedSeq {
161 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
162 struct Visitor;
163
164 impl<'de> serde::de::Visitor<'de> for Visitor {
165 type Value = LimitedSeq;
166
167 // GRCOV_EXCL_START
168 fn expecting(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
169 fmt.write_str("an empty sequence")
170 }
171 // GRCOV_EXCL_STOP
172
173 fn visit_seq<A: serde::de::SeqAccess<'de>>(
174 self,
175 _seq: A,
176 ) -> Result<Self::Value, A::Error> {
177 Ok(LimitedSeq)
178 }
179 }
180
181 deserializer.deserialize_seq(Visitor)
182 }
183 }
184
185 check_from_str_bytes_reader::<LimitedSeq>(
186 "[",
187 Err(SpannedError {
188 code: Error::ExpectedArrayEnd,
189 position: Position { line: 1, col: 2 },
190 }),
191 );
192
193 assert_eq!(
194 crate::Value::from(vec![42]).into_rust::<LimitedSeq>(),
195 Err(Error::ExpectedDifferentLength {
196 expected: String::from("a sequence of length 0"),
197 found: 1
198 })
199 );
200 }
201
202 #[test]
203 fn test_unclosed_limited_map() {
204 #[derive(Debug, PartialEq)]
205 struct LimitedMap;
206
207 impl<'de> serde::Deserialize<'de> for LimitedMap {
208 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
209 struct Visitor;
210
211 impl<'de> serde::de::Visitor<'de> for Visitor {
212 type Value = LimitedMap;
213
214 // GRCOV_EXCL_START
215 fn expecting(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
216 fmt.write_str("an empty map")
217 }
218 // GRCOV_EXCL_STOP
219
220 fn visit_map<A: serde::de::MapAccess<'de>>(
221 self,
222 _map: A,
223 ) -> Result<Self::Value, A::Error> {
224 Ok(LimitedMap)
225 }
226 }
227
228 deserializer.deserialize_map(Visitor)
229 }
230 }
231
232 check_from_str_bytes_reader::<LimitedMap>(
233 "{",
234 Err(SpannedError {
235 code: Error::ExpectedMapEnd,
236 position: Position { line: 1, col: 2 },
237 }),
238 );
239
240 assert_eq!(
241 crate::Value::Map([("a", 42)].into_iter().collect()).into_rust::<LimitedMap>(),
242 Err(Error::ExpectedDifferentLength {
243 expected: String::from("a map of length 0"),
244 found: 1
245 })
246 );
247 }
248
249 #[test]
250 fn test_option() {
251 check_from_str_bytes_reader("Some(1)", Ok(Some(1u8)));
252 check_from_str_bytes_reader("None", Ok(None::<u8>));
253 }
254
255 #[test]
256 fn test_enum() {
257 check_from_str_bytes_reader("A", Ok(MyEnum::A));
258 check_from_str_bytes_reader("B(true,)", Ok(MyEnum::B(true)));
259 check_from_str_bytes_reader::<MyEnum>(
260 "B",
261 Err(SpannedError {
262 code: Error::ExpectedStructLike,
263 position: Position { line: 1, col: 2 },
264 }),
265 );
266 check_from_str_bytes_reader("C(true,3.5,)", Ok(MyEnum::C(true, 3.5)));
267 check_from_str_bytes_reader("D(a:2,b:3,)", Ok(MyEnum::D { a: 2, b: 3 }));
268 }
269
270 #[test]
271 fn test_array() {
272 check_from_str_bytes_reader::<[i32; 0]>("()", Ok([]));
273 check_from_str_bytes_reader("[]", Ok(Vec::<i32>::new()));
274
275 check_from_str_bytes_reader("(2,3,4,)", Ok([2, 3, 4i32]));
276 check_from_str_bytes_reader("[2,3,4,]", Ok([2, 3, 4i32].to_vec()));
277 }
278
279 #[test]
280 fn test_map() {
281 use std::collections::HashMap;
282
283 let mut map = HashMap::new();
284 map.insert((true, false), 4);
285 map.insert((false, false), 123);
286
287 check_from_str_bytes_reader(
288 "{
289 (true,false,):4,
290 (false,false,):123,
291 }",
292 Ok(map),
293 );
294 }
295
296 #[test]
297 fn test_string() {
298 check_from_str_bytes_reader("\"String\"", Ok(String::from("String")));
299
300 check_from_str_bytes_reader("r\"String\"", Ok(String::from("String")));
301 check_from_str_bytes_reader("r#\"String\"#", Ok(String::from("String")));
302
303 check_from_str_bytes_reader(
304 "r#\"String with\nmultiple\nlines\n\"#",
305 Ok(String::from("String with\nmultiple\nlines\n")),
306 );
307
308 check_from_str_bytes_reader(
309 "r##\"String with \"#\"##",
310 Ok(String::from("String with \"#")),
311 );
312 }
313
314 #[test]
315 fn test_char() {
316 check_from_str_bytes_reader("'c'", Ok('c'));
317 }
318
319 #[test]
320 fn test_escape_char() {
321 check_from_str_bytes_reader("'\\''", Ok('\''));
322 }
323
324 #[test]
325 fn test_escape() {
326 check_from_str_bytes_reader(r#""\"Quoted\"""#, Ok(String::from("\"Quoted\"")));
327 }
328
329 #[test]
330 fn test_comment() {
331 check_from_str_bytes_reader(
332 "(
333 x: 1.0, // x is just 1
334 // There is another comment in the very next line..
335 // And y is indeed
336 y: 2.0 // 2!
337 )",
338 Ok(MyStruct { x: 1.0, y: 2.0 }),
339 );
340 }
341
342 fn err<T>(kind: Error, line: usize, col: usize) -> SpannedResult<T> {
343 Err(SpannedError {
344 code: kind,
345 position: Position { line, col },
346 })
347 }
348
349 #[test]
350 fn test_err_wrong_value() {
351 use std::collections::HashMap;
352
353 check_from_str_bytes_reader::<f32>("'c'", err(Error::ExpectedFloat, 1, 1));
354 check_from_str_bytes_reader::<String>("'c'", err(Error::ExpectedString, 1, 1));
355 check_from_str_bytes_reader::<HashMap<u32, u32>>("'c'", err(Error::ExpectedMap, 1, 1));
356 check_from_str_bytes_reader::<[u8; 5]>("'c'", err(Error::ExpectedStructLike, 1, 1));
357 check_from_str_bytes_reader::<Vec<u32>>("'c'", err(Error::ExpectedArray, 1, 1));
358 check_from_str_bytes_reader::<MyEnum>("'c'", err(Error::ExpectedIdentifier, 1, 1));
359 check_from_str_bytes_reader::<MyStruct>(
360 "'c'",
361 err(Error::ExpectedNamedStructLike("MyStruct"), 1, 1),
362 );
363 check_from_str_bytes_reader::<MyStruct>(
364 "NotMyStruct(x: 4, y: 2)",
365 err(
366 Error::ExpectedDifferentStructName {
367 expected: "MyStruct",
368 found: String::from("NotMyStruct"),
369 },
370 1,
371 12,
372 ),
373 );
374 check_from_str_bytes_reader::<(u8, bool)>("'c'", err(Error::ExpectedStructLike, 1, 1));
375 check_from_str_bytes_reader::<bool>("notabool", err(Error::ExpectedBoolean, 1, 1));
376
377 check_from_str_bytes_reader::<MyStruct>(
378 "MyStruct(\n x: true)",
379 err(Error::ExpectedFloat, 2, 8),
380 );
381 check_from_str_bytes_reader::<MyStruct>(
382 "MyStruct(\n x: 3.5, \n y:)",
383 err(Error::ExpectedFloat, 3, 7),
384 );
385 }
386
387 #[test]
388 fn test_perm_ws() {
389 check_from_str_bytes_reader(
390 "\nMyStruct \t ( \n x : 3.5 , \t y\n: 4.5 \n ) \t\n",
391 Ok(MyStruct { x: 3.5, y: 4.5 }),
392 );
393 }
394
395 #[test]
396 fn untagged() {
397 #[derive(Deserialize, Debug, PartialEq)]
398 #[serde(untagged)]
399 enum Untagged {
400 U8(u8),
401 Bool(bool),
402 Value(crate::Value),
403 }
404
405 check_from_str_bytes_reader("true", Ok(Untagged::Bool(true)));
406 check_from_str_bytes_reader("8", Ok(Untagged::U8(8)));
407
408 // Check for a failure in Deserializer::check_struct_type
409 // - untagged enum and a leading identifier trigger the serde content enum path
410 // - serde content uses deserialize_any, which retriggers the struct type check
411 // - struct type check inside a serde content performs a full newtype check
412 // - newtype check fails on the unclosed struct
413 check_from_str_bytes_reader::<Untagged>(
414 "Value(()",
415 Err(crate::error::SpannedError {
416 code: crate::Error::Eof,
417 position: crate::error::Position { line: 1, col: 9 },
418 }),
419 );
420 }
421
422 #[test]
423 fn rename() {
424 #[derive(Deserialize, Debug, PartialEq)]
425 enum Foo {
426 #[serde(rename = "2d")]
427 D2,
428 #[serde(rename = "triangle-list")]
429 TriangleList,
430 }
431
432 check_from_str_bytes_reader("r#2d", Ok(Foo::D2));
433 check_from_str_bytes_reader("r#triangle-list", Ok(Foo::TriangleList));
434 }
435
436 #[test]
437 fn forgot_apostrophes() {
438 check_from_str_bytes_reader::<(i32, String)>(
439 "(4, \"Hello)",
440 Err(SpannedError {
441 code: Error::ExpectedStringEnd,
442 position: Position { line: 1, col: 6 },
443 }),
444 );
445 }
446
447 #[test]
448 fn expected_attribute() {
449 check_from_str_bytes_reader::<String>("#\"Hello\"", err(Error::ExpectedAttribute, 1, 2));
450 }
451
452 #[test]
453 fn expected_attribute_end() {
454 check_from_str_bytes_reader::<String>(
455 "#![enable(unwrap_newtypes) \"Hello\"",
456 err(Error::ExpectedAttributeEnd, 1, 28),
457 );
458 }
459
460 #[test]
461 fn invalid_attribute() {
462 check_from_str_bytes_reader::<String>(
463 "#![enable(invalid)] \"Hello\"",
464 err(Error::NoSuchExtension("invalid".to_string()), 1, 18),
465 );
466 }
467
468 #[test]
469 fn multiple_attributes() {
470 #[derive(Debug, Deserialize, PartialEq)]
471 struct New(String);
472
473 check_from_str_bytes_reader(
474 "#![enable(unwrap_newtypes)] #![enable(unwrap_newtypes)] \"Hello\"",
475 Ok(New("Hello".to_owned())),
476 );
477 }
478
479 #[test]
480 fn uglified_attribute() {
481 check_from_str_bytes_reader(
482 "# !\
483 // We definitely want to add a comment here
484 [\t\tenable( // best style ever
485 unwrap_newtypes ) ] ()",
486 Ok(()),
487 );
488 }
489
490 #[test]
491 fn implicit_some() {
492 use serde::de::DeserializeOwned;
493
494 fn de<T: DeserializeOwned>(s: &str) -> Option<T> {
495 let enable = "#![enable(implicit_some)]\n".to_string();
496
497 super::from_str::<Option<T>>(&(enable + s)).unwrap()
498 }
499
500 assert_eq!(de("'c'"), Some('c'));
501 assert_eq!(de("5"), Some(5));
502 assert_eq!(de("\"Hello\""), Some("Hello".to_owned()));
503 assert_eq!(de("false"), Some(false));
504 assert_eq!(
505 de("MyStruct(x: .4, y: .5)"),
506 Some(MyStruct { x: 0.4, y: 0.5 })
507 );
508
509 assert_eq!(de::<char>("None"), None);
510
511 // Not concise
512 assert_eq!(de::<Option<Option<char>>>("None"), None);
513 }
514
515 #[test]
516 fn ws_tuple_newtype_variant() {
517 check_from_str_bytes_reader("B ( \n true \n ) ", Ok(MyEnum::B(true)));
518 }
519
520 #[test]
521 fn test_byte_stream() {
522 check_from_str_bytes_reader(
523 "BytesStruct( small:[1, 2], large:b\"\\x01\\x02\\x03\\x04\" )",
524 Ok(BytesStruct {
525 small: vec![1, 2],
526 large: vec![1, 2, 3, 4],
527 }),
528 );
529 }
530
531 #[test]
532 fn test_numbers() {
533 check_from_str_bytes_reader(
534 "[1_234, 12_345, 1_2_3_4_5_6, 1_234_567, 5_55_55_5]",
535 Ok(vec![1234, 12345, 123_456, 1_234_567, 555_555]),
536 );
537 }
538
539 fn check_de_any_number<
540 T: Copy + PartialEq + std::fmt::Debug + Into<Number> + serde::de::DeserializeOwned,
541 >(
542 s: &str,
543 cmp: T,
544 ) {
545 let mut parser = Parser::new(s).unwrap();
546 let number = parser.any_number().unwrap();
547
548 assert_eq!(number, Number::new(cmp));
549 assert_eq!(
550 Number::new(super::from_str::<T>(s).unwrap()),
551 Number::new(cmp)
552 );
553 }
554
555 #[test]
556 fn test_any_number_precision() {
557 check_de_any_number("1", 1_u8);
558 check_de_any_number("+1", 1_u8);
559 check_de_any_number("-1", -1_i8);
560 check_de_any_number("-1.0", -1.0_f32);
561 check_de_any_number("1.", 1.0_f32);
562 check_de_any_number("-1.", -1.0_f32);
563 check_de_any_number(".3", 0.3_f64);
564 check_de_any_number("-.3", -0.3_f64);
565 check_de_any_number("+.3", 0.3_f64);
566 check_de_any_number("0.3", 0.3_f64);
567 check_de_any_number("NaN", f32::NAN);
568 check_de_any_number("-NaN", -f32::NAN);
569 check_de_any_number("inf", f32::INFINITY);
570 check_de_any_number("-inf", f32::NEG_INFINITY);
571
572 macro_rules! test_min {
573 ($($ty:ty),*) => {
574 $(check_de_any_number(&format!("{}", <$ty>::MIN), <$ty>::MIN);)*
575 };
576 }
577
578 macro_rules! test_max {
579 ($($ty:ty),*) => {
580 $(check_de_any_number(&format!("{}", <$ty>::MAX), <$ty>::MAX);)*
581 };
582 }
583
584 test_min! { i8, i16, i32, i64, f64 }
585 test_max! { u8, u16, u32, u64, f64 }
586 #[cfg(feature = "integer128")]
587 test_min! { i128 }
588 #[cfg(feature = "integer128")]
589 test_max! { u128 }
590 }
591
592 #[test]
593 fn test_value_special_floats() {
594 use crate::{from_str, value::Number, Value};
595
596 assert_eq!(
597 from_str("NaN"),
598 Ok(Value::Number(Number::F32(f32::NAN.into())))
599 );
600 assert_eq!(
601 from_str("+NaN"),
602 Ok(Value::Number(Number::F32(f32::NAN.into())))
603 );
604 assert_eq!(
605 from_str("-NaN"),
606 Ok(Value::Number(Number::F32((-f32::NAN).into())))
607 );
608
609 assert_eq!(
610 from_str("inf"),
611 Ok(Value::Number(Number::F32(f32::INFINITY.into())))
612 );
613 assert_eq!(
614 from_str("+inf"),
615 Ok(Value::Number(Number::F32(f32::INFINITY.into())))
616 );
617 assert_eq!(
618 from_str("-inf"),
619 Ok(Value::Number(Number::F32(f32::NEG_INFINITY.into())))
620 );
621 }
622
623 #[test]
624 fn test_leading_whitespace() {
625 check_from_str_bytes_reader(" +1", Ok(1_u8));
626 check_from_str_bytes_reader(" EmptyStruct1", Ok(EmptyStruct1));
627 }
628
629 fn check_from_str_bytes_reader<T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug>(
630 ron: &str,
631 check: SpannedResult<T>,
632 ) {
633 let res_str = super::from_str::<T>(ron);
634 assert_eq!(res_str, check);
635
636 let res_bytes = super::from_bytes::<T>(ron.as_bytes());
637 assert_eq!(res_bytes, check);
638
639 let res_reader = super::from_reader::<&[u8], T>(ron.as_bytes());
640 assert_eq!(res_reader, check);
641 }
642
643 #[test]
644 fn test_remainder() {
645 let mut deserializer = super::Deserializer::from_str(" 42 ").unwrap();
646 assert_eq!(
647 <u8 as serde::Deserialize>::deserialize(&mut deserializer).unwrap(),
648 42
649 );
650 assert_eq!(deserializer.remainder(), " ");
651 assert_eq!(deserializer.end(), Ok(()));
652
653 let mut deserializer = super::Deserializer::from_str(" 42 37 ").unwrap();
654 assert_eq!(
655 <u8 as serde::Deserialize>::deserialize(&mut deserializer).unwrap(),
656 42
657 );
658 assert_eq!(deserializer.remainder(), " 37 ");
659 assert_eq!(deserializer.end(), Err(Error::TrailingCharacters));
660 }
661
662 #[test]
663 fn boolean_struct_name() {
664 check_from_str_bytes_reader::<bool>(
665 "true_",
666 Err(SpannedError {
667 code: Error::ExpectedBoolean,
668 position: Position { line: 1, col: 1 },
669 }),
670 );
671 check_from_str_bytes_reader::<bool>(
672 "false_",
673 Err(SpannedError {
674 code: Error::ExpectedBoolean,
675 position: Position { line: 1, col: 1 },
676 }),
677 );
678 }