Debian Codegraph @

src/de/tests.rs

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