1use alloc::borrow::Cow;
2use alloc::string::{String, ToString};
3use core::fmt::Display;
4use core::ops::Range;
5
6use serde::de::{DeserializeOwned, EnumAccess, MapAccess, SeqAccess, VariantAccess};
7use serde::Deserialize;
8
9use crate::parser::{self, Config, Event, EventKind, Name, Nested, Parser, Primitive};
10use crate::tokenizer::{self, Integer};
11
12pub struct Deserializer<'de> {
14 parser: BetterPeekable<Parser<'de>>,
15 newtype_state: Option<NewtypeState>,
16}
17
18#[derive(Clone, Copy, Eq, PartialEq)]
19enum NewtypeState {
20 StructVariant,
21 TupleVariant,
22}
23
24impl<'de> Deserializer<'de> {
25 #[must_use]
30 pub fn new(source: &'de str, configuration: Config) -> Self {
31 Self {
32 parser: BetterPeekable::new(Parser::new(source, configuration.include_comments(false))),
33 newtype_state: None,
34 }
35 }
36
37 pub fn ensure_eof(mut self) -> Result<(), Error> {
44 match self.parser.next() {
45 None => Ok(()),
46 Some(Ok(event)) => Err(Error::new(event.location, parser::ErrorKind::TrailingData)),
47 Some(Err(err)) => Err(Error::new(err.location, parser::ErrorKind::TrailingData)),
48 }
49 }
50
51 fn handle_unit(&mut self) -> Result<(), DeserializerError> {
52 self.with_error_context(|de| match de.parser.next().transpose()? {
53 Some(Event {
54 kind:
55 EventKind::BeginNested {
56 kind: Nested::Tuple,
57 ..
58 },
59 ..
60 }) => {
61 let mut nests = 1;
62 while nests > 0 {
63 match de.parser.next().transpose()? {
64 Some(Event {
65 kind: EventKind::BeginNested { .. },
66 ..
67 }) => nests += 1,
68 Some(Event {
69 kind: EventKind::EndNested,
70 ..
71 }) => nests -= 1,
72 Some(_) => {}
73 None => unreachable!("parser errors on early eof"),
74 }
75 }
76 Ok(())
77 }
78 Some(evt) => Err(DeserializerError::new(
79 evt.location,
80 ErrorKind::ExpectedUnit,
81 )),
82 None => Err(DeserializerError::new(None, ErrorKind::ExpectedUnit)),
83 })
84 }
85
86 fn with_error_context<T>(
87 &mut self,
88 f: impl FnOnce(&mut Self) -> Result<T, DeserializerError>,
89 ) -> Result<T, DeserializerError> {
90 let error_start = self.parser.current_offset();
91 self.with_error_start(error_start, f)
92 }
93
94 fn with_error_start<T>(
95 &mut self,
96 error_start: usize,
97 f: impl FnOnce(&mut Self) -> Result<T, DeserializerError>,
98 ) -> Result<T, DeserializerError> {
99 match f(&mut *self) {
100 Ok(result) => Ok(result),
101 Err(mut err) => {
102 if err.location.is_none() {
103 err.location = Some(error_start..self.parser.current_offset());
104 }
105 Err(err)
106 }
107 }
108 }
109
110 fn set_newtype_state(&mut self, state: NewtypeState) -> NewtypeStateModification {
111 let old_state = self.newtype_state.replace(state);
112 NewtypeStateModification(old_state)
113 }
114
115 fn finish_newtype(&mut self, modification: NewtypeStateModification) -> Option<NewtypeState> {
116 core::mem::replace(&mut self.newtype_state, modification.0)
117 }
118}
119
120#[must_use]
121#[derive(Copy, Clone)]
122struct NewtypeStateModification(Option<NewtypeState>);
123
124macro_rules! deserialize_int_impl {
125 ($de_name:ident, $visit_name:ident, $conv_name:ident) => {
126 fn $de_name<V>(self, visitor: V) -> Result<V::Value, Self::Error>
127 where
128 V: serde::de::Visitor<'de>,
129 {
130 self.with_error_context(|de| match de.parser.next().transpose()? {
131 Some(Event {
132 kind: EventKind::Primitive(Primitive::Integer(value)),
133 location,
134 }) => visitor.$visit_name(value.$conv_name().ok_or_else(|| {
135 DeserializerError::new(location, tokenizer::ErrorKind::IntegerTooLarge)
136 })?),
137 Some(evt) => Err(DeserializerError::new(
138 evt.location,
139 ErrorKind::ExpectedInteger,
140 )),
141 None => Err(DeserializerError::new(None, ErrorKind::ExpectedInteger)),
142 })
143 }
144 };
145}
146
147impl<'de> serde::de::Deserializer<'de> for &mut Deserializer<'de> {
148 type Error = DeserializerError;
149
150 deserialize_int_impl!(deserialize_i8, visit_i8, as_i8);
151
152 deserialize_int_impl!(deserialize_i16, visit_i16, as_i16);
153
154 deserialize_int_impl!(deserialize_i32, visit_i32, as_i32);
155
156 deserialize_int_impl!(deserialize_i64, visit_i64, as_i64);
157
158 deserialize_int_impl!(deserialize_i128, visit_i128, as_i128);
159
160 deserialize_int_impl!(deserialize_u8, visit_u8, as_u8);
161
162 deserialize_int_impl!(deserialize_u16, visit_u16, as_u16);
163
164 deserialize_int_impl!(deserialize_u32, visit_u32, as_u32);
165
166 deserialize_int_impl!(deserialize_u64, visit_u64, as_u64);
167
168 deserialize_int_impl!(deserialize_u128, visit_u128, as_u128);
169
170 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
171 where
172 V: serde::de::Visitor<'de>,
173 {
174 self.with_error_context(|de| {
175 let Some(event) = de.parser.next().transpose()? else {
176 return visitor.visit_unit();
177 };
178 match event.kind {
179 EventKind::BeginNested { name, kind } => match kind {
180 Nested::Tuple
183 if name.as_deref() == Some("Some")
184 && event.location.end - event.location.start == 4 =>
185 {
186 let value = visitor.visit_some(&mut *de)?;
187 let possible_close = de
188 .parser
189 .next()
190 .transpose()?
191 .expect("parser would error without EndNested");
192 match possible_close.kind {
193 EventKind::EndNested => Ok(value),
194 _ => Err(DeserializerError::new(
195 possible_close.location,
196 ErrorKind::SomeCanOnlyContainOneValue,
197 )),
198 }
199 }
200 Nested::List | Nested::Tuple => {
201 if matches!(
202 de.parser.peek(),
203 Some(Ok(Event {
204 kind: EventKind::EndNested,
205 ..
206 }))
207 ) {
208 de.parser.next();
209 visitor.visit_unit()
210 } else {
211 visitor.visit_seq(sealed::SequenceDeserializer::new(de))
212 }
213 }
214 Nested::Map => visitor.visit_map(de),
215 },
216 EventKind::Primitive(primitive) => match primitive {
217 Primitive::Bool(v) => visitor.visit_bool(v),
218 Primitive::Integer(v) =>
219 {
220 #[allow(clippy::cast_possible_truncation)]
221 match v {
222 Integer::Usize(usize) => match usize::BITS {
223 0..=16 => visitor.visit_u16(usize as u16),
224 17..=32 => visitor.visit_u32(usize as u32),
225 33..=64 => visitor.visit_u64(usize as u64),
226 65..=128 => visitor.visit_u128(usize as u128),
227 _ => unreachable!("unsupported pointer width"),
228 },
229 Integer::Isize(isize) => match usize::BITS {
230 0..=16 => visitor.visit_i16(isize as i16),
231 17..=32 => visitor.visit_i32(isize as i32),
232 33..=64 => visitor.visit_i64(isize as i64),
233 65..=128 => visitor.visit_i128(isize as i128),
234 _ => unreachable!("unsupported pointer width"),
235 },
236 #[cfg(feature = "integer128")]
237 Integer::UnsignedLarge(large) => visitor.visit_u128(large),
238 #[cfg(not(feature = "integer128"))]
239 Integer::UnsignedLarge(large) => visitor.visit_u64(large),
240 #[cfg(feature = "integer128")]
241 Integer::SignedLarge(large) => visitor.visit_i128(large),
242 #[cfg(not(feature = "integer128"))]
243 Integer::SignedLarge(large) => visitor.visit_i64(large),
244 }
245 }
246 Primitive::Float(v) => visitor.visit_f64(v),
247 Primitive::Char(v) => visitor.visit_char(v),
248 Primitive::String(v) => match v {
249 Cow::Borrowed(v) => visitor.visit_borrowed_str(v),
250 Cow::Owned(v) => visitor.visit_string(v),
251 },
252 Primitive::Identifier(v) => {
253 if v == "None" && event.location.end - event.location.start == 4 {
257 visitor.visit_none()
258 } else {
259 visitor.visit_borrowed_str(v)
260 }
261 }
262 Primitive::Bytes(v) => match v {
263 Cow::Borrowed(v) => visitor.visit_borrowed_bytes(v),
264 Cow::Owned(v) => visitor.visit_byte_buf(v),
265 },
266 },
267 EventKind::Comment(_) => unreachable!("comments are disabled"),
268 EventKind::EndNested => unreachable!("parser would error"),
269 }
270 })
271 }
272
273 fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
274 where
275 V: serde::de::Visitor<'de>,
276 {
277 self.with_error_context(|de| match de.parser.next().transpose()? {
278 Some(Event {
279 kind: EventKind::Primitive(Primitive::Bool(value)),
280 ..
281 }) => visitor.visit_bool(value),
282 Some(Event {
283 kind: EventKind::Primitive(Primitive::Integer(value)),
284 ..
285 }) => visitor.visit_bool(!value.is_zero()),
286 Some(evt) => Err(DeserializerError::new(
287 evt.location,
288 ErrorKind::ExpectedInteger,
289 )),
290 None => Err(DeserializerError::new(None, ErrorKind::ExpectedInteger)),
291 })
292 }
293
294 fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
295 where
296 V: serde::de::Visitor<'de>,
297 {
298 self.with_error_context(|de| de.deserialize_f64(visitor))
299 }
300
301 fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
302 where
303 V: serde::de::Visitor<'de>,
304 {
305 self.with_error_context(|de| match de.parser.next().transpose()? {
306 Some(Event {
307 kind: EventKind::Primitive(Primitive::Float(value)),
308 ..
309 }) => visitor.visit_f64(value),
310 Some(Event {
311 kind: EventKind::Primitive(Primitive::Integer(value)),
312 ..
313 }) => visitor.visit_f64(value.as_f64()),
314 Some(evt) => Err(DeserializerError::new(
315 evt.location,
316 ErrorKind::ExpectedFloat,
317 )),
318 None => Err(DeserializerError::new(None, ErrorKind::ExpectedFloat)),
319 })
320 }
321
322 fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
323 where
324 V: serde::de::Visitor<'de>,
325 {
326 self.with_error_context(|de| match de.parser.next().transpose()? {
327 Some(Event {
328 kind: EventKind::Primitive(Primitive::Char(value)),
329 ..
330 }) => visitor.visit_char(value),
331 Some(evt) => Err(DeserializerError::new(
332 evt.location,
333 ErrorKind::ExpectedChar,
334 )),
335 None => Err(DeserializerError::new(None, ErrorKind::ExpectedChar)),
336 })
337 }
338
339 fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
340 where
341 V: serde::de::Visitor<'de>,
342 {
343 self.with_error_context(|de| match de.parser.next().transpose()? {
344 Some(Event {
345 kind: EventKind::Primitive(Primitive::Identifier(str)),
346 ..
347 }) => visitor.visit_borrowed_str(str),
348 Some(Event {
349 kind: EventKind::Primitive(Primitive::String(str)),
350 ..
351 }) => match str {
352 Cow::Borrowed(str) => visitor.visit_borrowed_str(str),
353 Cow::Owned(str) => visitor.visit_string(str),
354 },
355 Some(Event {
356 kind: EventKind::Primitive(Primitive::Bytes(bytes)),
357 location,
358 }) => match bytes {
359 Cow::Borrowed(bytes) => visitor.visit_borrowed_str(
360 core::str::from_utf8(bytes)
361 .map_err(|_| DeserializerError::new(location, ErrorKind::InvalidUtf8))?,
362 ),
363 Cow::Owned(bytes) => visitor.visit_string(
364 String::from_utf8(bytes)
365 .map_err(|_| DeserializerError::new(location, ErrorKind::InvalidUtf8))?,
366 ),
367 },
368 Some(Event {
369 kind:
370 EventKind::BeginNested {
371 name: Some(name), ..
372 },
373 ..
374 }) => visitor.visit_str(name.name),
375 Some(evt) => Err(DeserializerError::new(
376 evt.location,
377 ErrorKind::ExpectedString,
378 )),
379 None => Err(DeserializerError::new(None, ErrorKind::ExpectedString)),
380 })
381 }
382
383 fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
384 where
385 V: serde::de::Visitor<'de>,
386 {
387 self.with_error_context(|de| de.deserialize_str(visitor))
388 }
389
390 fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
391 where
392 V: serde::de::Visitor<'de>,
393 {
394 self.with_error_context(|de| match de.parser.next().transpose()? {
395 Some(Event {
396 kind: EventKind::Primitive(Primitive::Identifier(str)),
397 ..
398 }) => visitor.visit_borrowed_bytes(str.as_bytes()),
399 Some(Event {
400 kind: EventKind::Primitive(Primitive::String(str)),
401 ..
402 }) => match str {
403 Cow::Borrowed(str) => visitor.visit_borrowed_bytes(str.as_bytes()),
404 Cow::Owned(str) => visitor.visit_byte_buf(str.into_bytes()),
405 },
406 Some(Event {
407 kind: EventKind::Primitive(Primitive::Bytes(bytes)),
408 ..
409 }) => match bytes {
410 Cow::Borrowed(bytes) => visitor.visit_borrowed_bytes(bytes),
411 Cow::Owned(bytes) => visitor.visit_byte_buf(bytes),
412 },
413 Some(evt) => Err(DeserializerError::new(
414 evt.location,
415 ErrorKind::ExpectedBytes,
416 )),
417 None => Err(DeserializerError::new(None, ErrorKind::ExpectedBytes)),
418 })
419 }
420
421 fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
422 where
423 V: serde::de::Visitor<'de>,
424 {
425 self.deserialize_bytes(visitor)
426 }
427
428 fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
429 where
430 V: serde::de::Visitor<'de>,
431 {
432 self.with_error_context(|de| match de.parser.peek() {
433 Some(Ok(Event {
434 kind: EventKind::Primitive(Primitive::Identifier(str)),
435 ..
436 })) if *str == "None" => {
437 de.parser.next();
438 visitor.visit_none()
439 }
440 Some(Ok(Event {
441 kind:
442 EventKind::BeginNested {
443 name: Some(Name { name: "Some", .. }),
444 kind: Nested::Tuple,
445 },
446 ..
447 })) => {
448 de.parser.next();
449 let result = visitor.visit_some(&mut *de)?;
450 match de.parser.next().transpose()? {
451 Some(Event {
452 kind: EventKind::EndNested,
453 ..
454 }) => Ok(result),
455 Some(evt) => Err(DeserializerError::new(
456 evt.location,
457 ErrorKind::SomeCanOnlyContainOneValue,
458 )),
459 None => unreachable!("parser errors on early eof"),
460 }
461 }
462 None => Err(DeserializerError::new(None, ErrorKind::ExpectedOption)),
463 _ => visitor.visit_some(de),
464 })
465 }
466
467 fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
468 where
469 V: serde::de::Visitor<'de>,
470 {
471 self.handle_unit()?;
472
473 visitor.visit_unit()
474 }
475
476 fn deserialize_unit_struct<V>(
477 self,
478 _name: &'static str,
479 visitor: V,
480 ) -> Result<V::Value, Self::Error>
481 where
482 V: serde::de::Visitor<'de>,
483 {
484 self.deserialize_unit(visitor)
485 }
486
487 fn deserialize_newtype_struct<V>(
488 self,
489 name: &'static str,
490 visitor: V,
491 ) -> Result<V::Value, Self::Error>
492 where
493 V: serde::de::Visitor<'de>,
494 {
495 self.deserialize_tuple_struct(name, 1, visitor)
496 }
497
498 fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
499 where
500 V: serde::de::Visitor<'de>,
501 {
502 self.with_error_context(|de| match de.parser.next().transpose()? {
503 Some(Event {
504 kind: EventKind::BeginNested { kind, .. },
505 location,
506 }) => {
507 if !matches!(kind, Nested::Tuple | Nested::List) {
508 return Err(DeserializerError::new(
509 location,
510 ErrorKind::ExpectedSequence,
511 ));
512 }
513
514 de.with_error_context(|de| visitor.visit_seq(sealed::SequenceDeserializer::new(de)))
515 }
516 Some(other) => Err(DeserializerError::new(
517 other.location,
518 ErrorKind::ExpectedSequence,
519 )),
520 None => Err(DeserializerError::new(
521 None,
522 parser::ErrorKind::UnexpectedEof,
523 )),
524 })
525 }
526
527 fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
528 where
529 V: serde::de::Visitor<'de>,
530 {
531 self.deserialize_seq(visitor)
532 }
533
534 fn deserialize_tuple_struct<V>(
535 self,
536 struct_name: &'static str,
537 _len: usize,
538 visitor: V,
539 ) -> Result<V::Value, Self::Error>
540 where
541 V: serde::de::Visitor<'de>,
542 {
543 let is_parsing_newtype_tuple =
544 matches!(self.newtype_state, Some(NewtypeState::TupleVariant));
545 let next_token_is_nested_tuple = matches!(
546 self.parser.peek(),
547 Some(Ok(Event {
548 kind: EventKind::BeginNested {
549 kind: Nested::Tuple,
550 ..
551 },
552 ..
553 }))
554 );
555 self.with_error_context(|de| {
556 if is_parsing_newtype_tuple {
557 if next_token_is_nested_tuple {
558 de.parser.next();
562 return visitor.visit_seq(sealed::SequenceDeserializer::new(de));
563 }
564 } else {
565 match de.parser.next().transpose()? {
566 Some(Event {
567 kind: EventKind::BeginNested { name, kind },
568 location,
569 }) => {
570 if name.map_or(false, |name| name != struct_name) {
571 return Err(DeserializerError::new(
572 location,
573 ErrorKind::NameMismatch(struct_name),
574 ));
575 }
576
577 if kind != Nested::Tuple {
578 return Err(DeserializerError::new(
579 location,
580 ErrorKind::ExpectedTupleStruct,
581 ));
582 }
583 }
584 Some(other) => {
585 return Err(DeserializerError::new(
586 other.location,
587 ErrorKind::ExpectedTupleStruct,
588 ));
589 }
590 None => {
591 return Err(DeserializerError::new(
592 None,
593 parser::ErrorKind::UnexpectedEof,
594 ))
595 }
596 }
597 }
598
599 visitor.visit_seq(sealed::SequenceDeserializer::new(de))
600 })
601 }
602
603 fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
604 where
605 V: serde::de::Visitor<'de>,
606 {
607 self.with_error_context(|de| match de.parser.next().transpose()? {
608 Some(Event {
609 kind: EventKind::BeginNested { kind, .. },
610 location,
611 }) => {
612 if kind != Nested::Map {
613 return Err(DeserializerError::new(location, ErrorKind::ExpectedMap));
614 }
615
616 visitor.visit_map(de)
617 }
618 Some(other) => Err(DeserializerError::new(
619 other.location,
620 ErrorKind::ExpectedMap,
621 )),
622 None => Err(DeserializerError::new(
623 None,
624 parser::ErrorKind::UnexpectedEof,
625 )),
626 })
627 }
628
629 fn deserialize_struct<V>(
630 self,
631 struct_name: &'static str,
632 _fields: &'static [&'static str],
633 visitor: V,
634 ) -> Result<V::Value, Self::Error>
635 where
636 V: serde::de::Visitor<'de>,
637 {
638 self.with_error_context(|de| {
639 match de.parser.next().transpose()? {
640 Some(Event {
641 kind: EventKind::BeginNested { name, kind },
642 location,
643 }) => {
644 if name.map_or(false, |name| name != struct_name)
645 && !matches!(de.newtype_state, Some(NewtypeState::StructVariant))
646 {
647 return Err(DeserializerError::new(
648 location,
649 ErrorKind::NameMismatch(struct_name),
650 ));
651 }
652
653 if kind != Nested::Map {
654 return Err(DeserializerError::new(
655 location,
656 ErrorKind::ExpectedMapStruct,
657 ));
658 }
659 }
660 Some(other) => {
661 return Err(DeserializerError::new(
662 other.location,
663 ErrorKind::ExpectedMapStruct,
664 ));
665 }
666 None => {
667 return Err(DeserializerError::new(
668 None,
669 parser::ErrorKind::UnexpectedEof,
670 ))
671 }
672 }
673
674 visitor.visit_map(de)
675 })
676 }
677
678 fn deserialize_enum<V>(
679 self,
680 _name: &'static str,
681 _variants: &'static [&'static str],
682 visitor: V,
683 ) -> Result<V::Value, Self::Error>
684 where
685 V: serde::de::Visitor<'de>,
686 {
687 self.with_error_context(|de| visitor.visit_enum(de))
688 }
689
690 fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
691 where
692 V: serde::de::Visitor<'de>,
693 {
694 self.with_error_context(|de| de.deserialize_str(visitor))
695 }
696
697 fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
698 where
699 V: serde::de::Visitor<'de>,
700 {
701 self.with_error_context(|de| {
702 let mut depth = 0;
703 loop {
704 match de.parser.next().transpose()? {
705 Some(Event {
706 kind: EventKind::BeginNested { .. },
707 ..
708 }) => {
709 depth += 1;
710 }
711 Some(Event {
712 kind: EventKind::EndNested,
713 ..
714 }) => {
715 depth -= 1;
716 }
717 Some(Event {
718 kind: EventKind::Primitive(_) | EventKind::Comment(_),
719 ..
720 }) => {}
721 None => {
722 return Err(DeserializerError::new(
723 None,
724 parser::ErrorKind::UnexpectedEof,
725 ))
726 }
727 }
728
729 if depth == 0 {
730 break;
731 }
732 }
733
734 visitor.visit_unit()
735 })
736 }
737}
738
739impl<'de> MapAccess<'de> for Deserializer<'de> {
740 type Error = DeserializerError;
741
742 fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
743 where
744 K: serde::de::DeserializeSeed<'de>,
745 {
746 self.with_error_context(|de| match de.parser.peek() {
747 Some(Ok(Event {
748 kind: EventKind::EndNested,
749 ..
750 })) => {
751 de.parser.next();
752 Ok(None)
753 }
754 Some(Ok(evt)) => {
755 let error_start = evt.location.start;
756 de.with_error_start(error_start, |de| seed.deserialize(de).map(Some))
757 }
758 Some(_) => seed.deserialize(de).map(Some),
759 None => Err(DeserializerError::new(
760 None,
761 parser::ErrorKind::UnexpectedEof,
762 )),
763 })
764 }
765
766 fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
767 where
768 V: serde::de::DeserializeSeed<'de>,
769 {
770 seed.deserialize(&mut *self)
771 }
772}
773
774mod sealed {
775 use super::{
776 parser, Deserializer, DeserializerError, EnumAccess, ErrorKind, Event, EventKind, Nested,
777 NewtypeState, Primitive, SeqAccess, VariantAccess,
778 };
779
780 pub struct SequenceDeserializer<'a, 'de> {
781 de: &'a mut Deserializer<'de>,
782 ended: bool,
783 }
784 impl<'a, 'de> SequenceDeserializer<'a, 'de> {
785 pub(crate) fn new(de: &'a mut Deserializer<'de>) -> Self {
786 Self { de, ended: false }
787 }
788 }
789
790 impl<'a, 'de> SeqAccess<'de> for SequenceDeserializer<'a, 'de> {
791 type Error = DeserializerError;
792
793 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
794 where
795 T: serde::de::DeserializeSeed<'de>,
796 {
797 self.de.with_error_context(|de| match de.parser.peek() {
798 Some(Ok(Event {
799 kind: EventKind::EndNested,
800 ..
801 })) => {
802 de.parser.next();
803 self.ended = true;
804 Ok(None)
805 }
806 Some(Ok(evt)) => {
807 let error_start = evt.location.start;
808 de.with_error_start(error_start, |de| seed.deserialize(de).map(Some))
809 }
810 Some(_) => seed.deserialize(de).map(Some),
811 None => Err(DeserializerError::new(
812 None,
813 parser::ErrorKind::UnexpectedEof,
814 )),
815 })
816 }
817 }
818
819 impl<'a, 'de> Drop for SequenceDeserializer<'a, 'de> {
820 fn drop(&mut self) {
821 if !self.ended {
822 let mut levels = 1;
823 loop {
824 if matches!(self.de.parser.peek(), None | Some(Err(_))) {
825 break;
826 }
827
828 match self.de.parser.next().expect("just peeked") {
829 Ok(Event {
830 kind: EventKind::EndNested,
831 ..
832 }) => {
833 levels -= 1;
834 if levels == 0 {
835 break;
836 }
837 }
838 Ok(Event {
839 kind: EventKind::BeginNested { .. },
840 ..
841 }) => {
842 levels += 1;
843 }
844 _ => {}
845 }
846 }
847 }
848 }
849 }
850
851 impl<'a, 'de> EnumAccess<'de> for &'a mut Deserializer<'de> {
852 type Error = DeserializerError;
853 type Variant = EnumVariantAccessor<'a, 'de>;
854
855 fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
856 where
857 V: serde::de::DeserializeSeed<'de>,
858 {
859 match self.parser.peek() {
860 Some(Ok(Event {
861 kind: EventKind::Primitive(Primitive::Identifier(_) | Primitive::String(_)),
862 ..
863 })) => Ok((seed.deserialize(&mut *self)?, EnumVariantAccessor::Unit)),
864 Some(Ok(Event {
865 kind:
866 EventKind::BeginNested {
867 name: Some(name), ..
868 },
869 ..
870 })) => {
871 let variant = seed.deserialize(&mut VariantDeserializer(name))?;
872 Ok((variant, EnumVariantAccessor::Nested(self)))
873 }
874 _ => Err(DeserializerError::new(None, ErrorKind::ExpectedEnum)),
875 }
876 }
892 }
893
894 struct VariantDeserializer<'a>(&'a str);
895
896 impl<'a, 'de> serde::Deserializer<'de> for &'a mut VariantDeserializer<'a> {
897 type Error = DeserializerError;
898
899 fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
900 where
901 V: serde::de::Visitor<'de>,
902 {
903 Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
904 }
905
906 fn deserialize_bool<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
907 where
908 V: serde::de::Visitor<'de>,
909 {
910 Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
911 }
912
913 fn deserialize_i8<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
914 where
915 V: serde::de::Visitor<'de>,
916 {
917 Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
918 }
919
920 fn deserialize_i16<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
921 where
922 V: serde::de::Visitor<'de>,
923 {
924 Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
925 }
926
927 fn deserialize_i32<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
928 where
929 V: serde::de::Visitor<'de>,
930 {
931 Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
932 }
933
934 fn deserialize_i64<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
935 where
936 V: serde::de::Visitor<'de>,
937 {
938 Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
939 }
940
941 fn deserialize_u8<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
942 where
943 V: serde::de::Visitor<'de>,
944 {
945 Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
946 }
947
948 fn deserialize_u16<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
949 where
950 V: serde::de::Visitor<'de>,
951 {
952 Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
953 }
954
955 fn deserialize_u32<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
956 where
957 V: serde::de::Visitor<'de>,
958 {
959 Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
960 }
961
962 fn deserialize_u64<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
963 where
964 V: serde::de::Visitor<'de>,
965 {
966 Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
967 }
968
969 fn deserialize_f32<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
970 where
971 V: serde::de::Visitor<'de>,
972 {
973 Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
974 }
975
976 fn deserialize_f64<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
977 where
978 V: serde::de::Visitor<'de>,
979 {
980 Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
981 }
982
983 fn deserialize_char<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
984 where
985 V: serde::de::Visitor<'de>,
986 {
987 Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
988 }
989
990 fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
991 where
992 V: serde::de::Visitor<'de>,
993 {
994 visitor.visit_str(self.0)
995 }
996
997 fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
998 where
999 V: serde::de::Visitor<'de>,
1000 {
1001 visitor.visit_str(self.0)
1002 }
1003
1004 fn deserialize_bytes<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
1005 where
1006 V: serde::de::Visitor<'de>,
1007 {
1008 Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
1009 }
1010
1011 fn deserialize_byte_buf<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
1012 where
1013 V: serde::de::Visitor<'de>,
1014 {
1015 Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
1016 }
1017
1018 fn deserialize_option<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
1019 where
1020 V: serde::de::Visitor<'de>,
1021 {
1022 Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
1023 }
1024
1025 fn deserialize_unit<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
1026 where
1027 V: serde::de::Visitor<'de>,
1028 {
1029 Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
1030 }
1031
1032 fn deserialize_unit_struct<V>(
1033 self,
1034 _name: &'static str,
1035 _visitor: V,
1036 ) -> Result<V::Value, Self::Error>
1037 where
1038 V: serde::de::Visitor<'de>,
1039 {
1040 Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
1041 }
1042
1043 fn deserialize_newtype_struct<V>(
1044 self,
1045 _name: &'static str,
1046 _visitor: V,
1047 ) -> Result<V::Value, Self::Error>
1048 where
1049 V: serde::de::Visitor<'de>,
1050 {
1051 Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
1052 }
1053
1054 fn deserialize_seq<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
1055 where
1056 V: serde::de::Visitor<'de>,
1057 {
1058 Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
1059 }
1060
1061 fn deserialize_tuple<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error>
1062 where
1063 V: serde::de::Visitor<'de>,
1064 {
1065 Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
1066 }
1067
1068 fn deserialize_tuple_struct<V>(
1069 self,
1070 _name: &'static str,
1071 _len: usize,
1072 _visitor: V,
1073 ) -> Result<V::Value, Self::Error>
1074 where
1075 V: serde::de::Visitor<'de>,
1076 {
1077 Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
1078 }
1079
1080 fn deserialize_map<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
1081 where
1082 V: serde::de::Visitor<'de>,
1083 {
1084 Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
1085 }
1086
1087 fn deserialize_struct<V>(
1088 self,
1089 _name: &'static str,
1090 _fields: &'static [&'static str],
1091 _visitor: V,
1092 ) -> Result<V::Value, Self::Error>
1093 where
1094 V: serde::de::Visitor<'de>,
1095 {
1096 Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
1097 }
1098
1099 fn deserialize_enum<V>(
1100 self,
1101 _name: &'static str,
1102 _variants: &'static [&'static str],
1103 _visitor: V,
1104 ) -> Result<V::Value, Self::Error>
1105 where
1106 V: serde::de::Visitor<'de>,
1107 {
1108 Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
1109 }
1110
1111 fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1112 where
1113 V: serde::de::Visitor<'de>,
1114 {
1115 visitor.visit_str(self.0)
1116 }
1117
1118 fn deserialize_ignored_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
1119 where
1120 V: serde::de::Visitor<'de>,
1121 {
1122 Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
1123 }
1124 }
1125
1126 pub enum EnumVariantAccessor<'a, 'de> {
1127 Unit,
1128 Nested(&'a mut Deserializer<'de>),
1129 }
1130
1131 impl<'a, 'de> VariantAccess<'de> for EnumVariantAccessor<'a, 'de> {
1132 type Error = DeserializerError;
1133
1134 fn unit_variant(self) -> Result<(), Self::Error> {
1135 Ok(())
1136 }
1137
1138 fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
1139 where
1140 T: serde::de::DeserializeSeed<'de>,
1141 {
1142 if let EnumVariantAccessor::Nested(deserializer) = self {
1143 let modification = match deserializer.parser.peek() {
1144 Some(Ok(Event {
1145 kind:
1146 EventKind::BeginNested {
1147 kind: Nested::Tuple,
1148 ..
1149 },
1150 ..
1151 })) => {
1152 let _begin = deserializer.parser.next();
1153 Some(deserializer.set_newtype_state(NewtypeState::TupleVariant))
1154 }
1155 Some(Ok(Event {
1156 kind:
1157 EventKind::BeginNested {
1158 kind: Nested::Map, ..
1159 },
1160 ..
1161 })) => Some(deserializer.set_newtype_state(NewtypeState::StructVariant)),
1162 _ => None,
1163 };
1164 let result = deserializer.with_error_context(|de| seed.deserialize(&mut *de))?;
1165 if let Some(modification) = modification {
1166 if deserializer.finish_newtype(modification) == Some(NewtypeState::TupleVariant)
1167 {
1168 drop(SequenceDeserializer::new(&mut *deserializer));
1171 }
1172 }
1173
1174 Ok(result)
1175 } else {
1176 Err(DeserializerError::new(None, ErrorKind::ExpectedTupleStruct))
1177 }
1178 }
1179
1180 fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
1181 where
1182 V: serde::de::Visitor<'de>,
1183 {
1184 if let EnumVariantAccessor::Nested(deserializer) = self {
1185 let nested_event = deserializer
1186 .parser
1187 .next()
1188 .expect("variant access matched Nested")?;
1189 deserializer.with_error_start(nested_event.location.start, |de| {
1190 visitor.visit_seq(SequenceDeserializer::new(de))
1191 })
1192 } else {
1193 Err(DeserializerError::new(None, ErrorKind::ExpectedTupleStruct))
1194 }
1195 }
1196
1197 fn struct_variant<V>(
1198 self,
1199 _fields: &'static [&'static str],
1200 visitor: V,
1201 ) -> Result<V::Value, Self::Error>
1202 where
1203 V: serde::de::Visitor<'de>,
1204 {
1205 if let EnumVariantAccessor::Nested(deserializer) = self {
1206 let nested_event = deserializer
1207 .parser
1208 .next()
1209 .expect("variant access matched Nested")?;
1210 deserializer
1211 .with_error_start(nested_event.location.start, |de| visitor.visit_map(de))
1212 } else {
1213 Err(DeserializerError::new(None, ErrorKind::ExpectedTupleStruct))
1214 }
1215 }
1216 }
1217}
1218
1219#[derive(Debug, Clone, PartialEq)]
1221pub struct Error {
1222 pub location: Range<usize>,
1224 pub kind: ErrorKind,
1226}
1227
1228impl Error {
1229 fn new(location: Range<usize>, kind: impl Into<ErrorKind>) -> Self {
1230 Self {
1231 location,
1232 kind: kind.into(),
1233 }
1234 }
1235}
1236
1237impl From<parser::Error> for Error {
1238 fn from(err: parser::Error) -> Self {
1239 Self {
1240 location: err.location,
1241 kind: err.kind.into(),
1242 }
1243 }
1244}
1245impl serde::ser::StdError for Error {}
1246
1247impl Display for Error {
1248 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1249 write!(
1250 f,
1251 "{} at {}..{}",
1252 self.kind, self.location.start, self.location.end
1253 )
1254 }
1255}
1256
1257#[derive(Debug, Clone, PartialEq)]
1259pub struct DeserializerError {
1260 pub location: Option<Range<usize>>,
1262 pub kind: ErrorKind,
1264}
1265
1266impl DeserializerError {
1267 fn new(location: impl Into<Option<Range<usize>>>, kind: impl Into<ErrorKind>) -> Self {
1268 Self {
1269 location: location.into(),
1270 kind: kind.into(),
1271 }
1272 }
1273}
1274
1275impl serde::de::Error for DeserializerError {
1276 fn custom<T>(msg: T) -> Self
1277 where
1278 T: Display,
1279 {
1280 Self {
1281 location: None,
1282 kind: ErrorKind::Message(msg.to_string()),
1283 }
1284 }
1285}
1286
1287impl serde::ser::StdError for DeserializerError {}
1288
1289impl Display for DeserializerError {
1290 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1291 if let Some(location) = &self.location {
1292 write!(f, "{} at {}..{}", self.kind, location.start, location.end)
1293 } else {
1294 Display::fmt(&self.kind, f)
1295 }
1296 }
1297}
1298
1299impl From<parser::Error> for DeserializerError {
1300 fn from(err: parser::Error) -> Self {
1301 Self {
1302 location: Some(err.location),
1303 kind: err.kind.into(),
1304 }
1305 }
1306}
1307
1308#[derive(Debug, Clone, PartialEq)]
1310#[non_exhaustive]
1311pub enum ErrorKind {
1312 ExpectedInteger,
1314 ExpectedFloat,
1316 ExpectedUnit,
1318 ExpectedBool,
1320 ExpectedOption,
1322 ExpectedChar,
1324 ExpectedString,
1326 ExpectedBytes,
1328 ExpectedSequence,
1330 ExpectedMap,
1332 ExpectedTupleStruct,
1334 ExpectedMapStruct,
1336 ExpectedEnum,
1338 InvalidUtf8,
1341 NameMismatch(&'static str),
1345 SomeCanOnlyContainOneValue,
1348 Parser(parser::ErrorKind),
1350 Message(String),
1352}
1353
1354impl From<parser::ErrorKind> for ErrorKind {
1355 fn from(kind: parser::ErrorKind) -> Self {
1356 Self::Parser(kind)
1357 }
1358}
1359
1360impl From<tokenizer::ErrorKind> for ErrorKind {
1361 fn from(kind: tokenizer::ErrorKind) -> Self {
1362 Self::Parser(kind.into())
1363 }
1364}
1365
1366impl Display for ErrorKind {
1367 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1368 match self {
1369 ErrorKind::Parser(parser) => Display::fmt(parser, f),
1370 ErrorKind::Message(message) => f.write_str(message),
1371 ErrorKind::ExpectedInteger => f.write_str("expected integer"),
1372 ErrorKind::ExpectedFloat => f.write_str("expected float"),
1373 ErrorKind::ExpectedBool => f.write_str("expected bool"),
1374 ErrorKind::ExpectedUnit => f.write_str("expected unit"),
1375 ErrorKind::ExpectedOption => f.write_str("expected option"),
1376 ErrorKind::ExpectedChar => f.write_str("expected char"),
1377 ErrorKind::ExpectedString => f.write_str("expected string"),
1378 ErrorKind::ExpectedBytes => f.write_str("expected bytes"),
1379 ErrorKind::SomeCanOnlyContainOneValue => {
1380 f.write_str("Some(_) can only contain one value")
1381 }
1382 ErrorKind::ExpectedSequence => f.write_str("expected sequence"),
1383 ErrorKind::ExpectedMap => f.write_str("expected map"),
1384 ErrorKind::ExpectedTupleStruct => f.write_str("expected tuple struct"),
1385 ErrorKind::ExpectedMapStruct => f.write_str("expected map struct"),
1386 ErrorKind::ExpectedEnum => f.write_str("expected enum"),
1387 ErrorKind::NameMismatch(name) => write!(f, "name mismatch, expected {name}"),
1388 ErrorKind::InvalidUtf8 => f.write_str("invalid utf-8"),
1389 }
1390 }
1391}
1392
1393impl Config {
1394 pub fn deserialize<'de, T: Deserialize<'de>>(self, source: &'de str) -> Result<T, Error> {
1407 let mut deserializer = Deserializer::new(source, self);
1408 let result = match T::deserialize(&mut deserializer) {
1409 Ok(result) => result,
1410 Err(err) => {
1411 let location = err
1412 .location
1413 .unwrap_or_else(|| deserializer.parser.current_range());
1414 return Err(Error::new(location, err.kind));
1415 }
1416 };
1417 deserializer.ensure_eof()?;
1418 Ok(result)
1419 }
1420
1421 pub fn deserialize_from_slice<'de, T: Deserialize<'de>>(
1434 self,
1435 source: &'de [u8],
1436 ) -> Result<T, Error> {
1437 let source = match alloc::str::from_utf8(source) {
1438 Ok(source) => source,
1439 Err(error) => {
1440 let end = error
1441 .error_len()
1442 .map_or(source.len(), |l| l + error.valid_up_to());
1443 return Err(Error::new(
1444 (error.valid_up_to() + 1)..end,
1445 ErrorKind::InvalidUtf8,
1446 ));
1447 }
1448 };
1449 self.deserialize(source)
1450 }
1451
1452 #[cfg(feature = "std")]
1466 pub fn deserialize_from_reader<T: DeserializeOwned, R: std::io::Read>(
1467 self,
1468 mut reader: R,
1469 ) -> Result<T, Error> {
1470 let mut source = alloc::vec::Vec::new();
1471 reader
1472 .read_to_end(&mut source)
1473 .map_err(|e| Error::new(0..0, ErrorKind::Message(e.to_string())))?;
1474 self.deserialize_from_slice(&source)
1475 }
1476}
1477
1478struct BetterPeekable<T>
1479where
1480 T: Iterator,
1481{
1482 iter: T,
1483 peeked: Option<T::Item>,
1484}
1485
1486impl<T> BetterPeekable<T>
1487where
1488 T: Iterator,
1489{
1490 pub fn new(iter: T) -> Self {
1491 Self { iter, peeked: None }
1492 }
1493
1494 pub fn peek(&mut self) -> Option<&T::Item> {
1495 if self.peeked.is_none() {
1496 self.peeked = self.next();
1497 }
1498
1499 self.peeked.as_ref()
1500 }
1501}
1502
1503impl<T> core::ops::Deref for BetterPeekable<T>
1504where
1505 T: Iterator,
1506{
1507 type Target = T;
1508
1509 fn deref(&self) -> &Self::Target {
1510 &self.iter
1511 }
1512}
1513
1514impl<T> Iterator for BetterPeekable<T>
1515where
1516 T: Iterator,
1517{
1518 type Item = T::Item;
1519
1520 fn next(&mut self) -> Option<Self::Item> {
1521 self.peeked.take().or_else(|| self.iter.next())
1522 }
1523}
1524
1525#[cfg(test)]
1526mod tests {
1527 use serde::{Deserialize, Serialize};
1528
1529 use crate::parser::Config;
1530
1531 #[test]
1532 fn basic_named() {
1533 #[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
1534 struct BasicNamed {
1535 a: u32,
1536 b: i32,
1537 }
1538
1539 let parsed = crate::from_str::<BasicNamed>(r"BasicNamed{ a: 1, b: -1 }").unwrap();
1540 assert_eq!(parsed, BasicNamed { a: 1, b: -1 });
1541 }
1542
1543 #[test]
1544 fn implicit_map() {
1545 #[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
1546 struct BasicNamed {
1547 a: u32,
1548 b: i32,
1549 }
1550 let config = Config::default().allow_implicit_map_at_root(true);
1551 let parsed = config.deserialize::<BasicNamed>("a: 1 b: -1").unwrap();
1552 assert_eq!(parsed, BasicNamed { a: 1, b: -1 });
1553 let parsed = config.deserialize::<BasicNamed>("a: 1, b: -1,").unwrap();
1554 assert_eq!(parsed, BasicNamed { a: 1, b: -1 });
1555 let parsed = config.deserialize::<BasicNamed>("{a: 1, b: -1}").unwrap();
1556 assert_eq!(parsed, BasicNamed { a: 1, b: -1 });
1557 let parsed = config
1558 .deserialize::<BasicNamed>("BasicNamed{a: 1, b: -1}")
1559 .unwrap();
1560 assert_eq!(parsed, BasicNamed { a: 1, b: -1 });
1561 }
1562
1563 #[test]
1564 fn optional() {
1565 #[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
1566 struct BasicNamed {
1567 a: u32,
1568 b: i32,
1569 }
1570
1571 assert_eq!(crate::from_str::<Option<BasicNamed>>("None").unwrap(), None);
1572
1573 let parsed =
1574 crate::from_str::<Option<BasicNamed>>("Some(BasicNamed{ a: 1, b: -1 })").unwrap();
1575 assert_eq!(parsed, Some(BasicNamed { a: 1, b: -1 }));
1576
1577 let parsed = crate::from_str::<Option<BasicNamed>>("BasicNamed{ a: 1, b: -1 }").unwrap();
1578 assert_eq!(parsed, Some(BasicNamed { a: 1, b: -1 }));
1579 }
1580
1581 #[test]
1582 fn error_locality() {
1583 #[derive(Debug, Deserialize)]
1584 #[serde(untagged)]
1585 enum Untagged {
1586 A(#[allow(unused)] u64),
1587 }
1588
1589 let source = r#"[1, "hello"]"#;
1590 let err = crate::from_str::<alloc::vec::Vec<Untagged>>(source).unwrap_err();
1591 assert_eq!(&source[err.location], r#""hello""#);
1592 }
1593
1594 #[test]
1595 fn enums() {
1596 #[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
1597 enum BasicEnums {
1598 Unit,
1599 NewType(u32),
1600 Struct { a: u32 },
1601 Tuple(u32, u32),
1602 }
1603
1604 assert_eq!(
1605 crate::from_str::<BasicEnums>("Unit").unwrap(),
1606 BasicEnums::Unit
1607 );
1608 assert_eq!(
1609 crate::from_str::<BasicEnums>("NewType(1)").unwrap(),
1610 BasicEnums::NewType(1)
1611 );
1612 assert_eq!(
1613 crate::from_str::<BasicEnums>("Struct{ a: 1}").unwrap(),
1614 BasicEnums::Struct { a: 1 }
1615 );
1616 assert_eq!(
1617 crate::from_str::<BasicEnums>("Tuple(1,2)").unwrap(),
1618 BasicEnums::Tuple(1, 2)
1619 );
1620 assert_eq!(
1621 crate::from_str::<BasicEnums>("Tuple(1,2,3)").unwrap(),
1622 BasicEnums::Tuple(1, 2)
1623 );
1624 }
1625}