1
use alloc::borrow::Cow;
2
use alloc::string::{String, ToString};
3
use core::fmt::Display;
4
use core::ops::Range;
5

            
6
use serde::de::{DeserializeOwned, EnumAccess, MapAccess, SeqAccess, VariantAccess};
7
use serde::Deserialize;
8

            
9
use crate::parser::{self, Config, Event, EventKind, Name, Nested, Parser, Primitive};
10
use crate::tokenizer::{self, Integer};
11

            
12
/// Deserializes Rsn using Serde.
13
pub struct Deserializer<'de> {
14
    parser: BetterPeekable<Parser<'de>>,
15
    newtype_state: Option<NewtypeState>,
16
}
17

            
18
#[derive(Clone, Copy, Eq, PartialEq)]
19
enum NewtypeState {
20
    StructVariant,
21
    TupleVariant,
22
}
23

            
24
impl<'de> Deserializer<'de> {
25
    /// Returns a deserializer for `source` with the given `configuration`.
26
    ///
27
    /// `Config::include_comments` will always be disabled, regardless of the
28
    /// value set in `configuration`.
29
    #[must_use]
30
45
    pub fn new(source: &'de str, configuration: Config) -> Self {
31
45
        Self {
32
45
            parser: BetterPeekable::new(Parser::new(source, configuration.include_comments(false))),
33
45
            newtype_state: None,
34
45
        }
35
45
    }
36

            
37
    /// Checks that this deserializer has consumed all of the input.
38
    ///
39
    /// # Errors
40
    ///
41
    /// Returns [`parser::ErrorKind::TrailingData`] if there is any data left
42
    /// unparsed.
43
44
    pub fn ensure_eof(mut self) -> Result<(), Error> {
44
44
        match self.parser.next() {
45
44
            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
44
    }
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
1164
    fn with_error_context<T>(
87
1164
        &mut self,
88
1164
        f: impl FnOnce(&mut Self) -> Result<T, DeserializerError>,
89
1164
    ) -> Result<T, DeserializerError> {
90
1164
        let error_start = self.parser.current_offset();
91
1164
        self.with_error_start(error_start, f)
92
1164
    }
93

            
94
1444
    fn with_error_start<T>(
95
1444
        &mut self,
96
1444
        error_start: usize,
97
1444
        f: impl FnOnce(&mut Self) -> Result<T, DeserializerError>,
98
1444
    ) -> Result<T, DeserializerError> {
99
1444
        match f(&mut *self) {
100
1440
            Ok(result) => Ok(result),
101
4
            Err(mut err) => {
102
4
                if err.location.is_none() {
103
1
                    err.location = Some(error_start..self.parser.current_offset());
104
3
                }
105
4
                Err(err)
106
            }
107
        }
108
1444
    }
109

            
110
10
    fn set_newtype_state(&mut self, state: NewtypeState) -> NewtypeStateModification {
111
10
        let old_state = self.newtype_state.replace(state);
112
10
        NewtypeStateModification(old_state)
113
10
    }
114

            
115
10
    fn finish_newtype(&mut self, modification: NewtypeStateModification) -> Option<NewtypeState> {
116
10
        core::mem::replace(&mut self.newtype_state, modification.0)
117
10
    }
118
}
119

            
120
#[must_use]
121
#[derive(Copy, Clone)]
122
struct NewtypeStateModification(Option<NewtypeState>);
123

            
124
macro_rules! deserialize_int_impl {
125
    ($de_name:ident, $visit_name:ident, $conv_name:ident) => {
126
190
        fn $de_name<V>(self, visitor: V) -> Result<V::Value, Self::Error>
127
190
        where
128
190
            V: serde::de::Visitor<'de>,
129
190
        {
130
190
            self.with_error_context(|de| match de.parser.next().transpose()? {
131
                Some(Event {
132
190
                    kind: EventKind::Primitive(Primitive::Integer(value)),
133
190
                    location,
134
190
                }) => visitor.$visit_name(value.$conv_name().ok_or_else(|| {
135
                    DeserializerError::new(location, tokenizer::ErrorKind::IntegerTooLarge)
136
190
                })?),
137
                Some(evt) => Err(DeserializerError::new(
138
                    evt.location,
139
                    ErrorKind::ExpectedInteger,
140
                )),
141
                None => Err(DeserializerError::new(None, ErrorKind::ExpectedInteger)),
142
190
            })
143
190
        }
144
    };
145
}
146

            
147
impl<'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
11
    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
171
11
    where
172
11
        V: serde::de::Visitor<'de>,
173
11
    {
174
11
        self.with_error_context(|de| {
175
11
            let Some(event) = de.parser.next().transpose()? else {
176
                return visitor.visit_unit();
177
            };
178
11
            match event.kind {
179
4
                EventKind::BeginNested { name, kind } => match kind {
180
2
                    // Check for Some(), and ensure that this isn't a raw identifier
181
2
                    // by checking the original token's length.
182
2
                    Nested::Tuple
183
2
                        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
2
                            de.parser.peek(),
203
                            Some(Ok(Event {
204
                                kind: EventKind::EndNested,
205
                                ..
206
                            }))
207
                        ) {
208
2
                            de.parser.next();
209
2
                            visitor.visit_unit()
210
                        } else {
211
                            visitor.visit_seq(sealed::SequenceDeserializer::new(de))
212
                        }
213
                    }
214
2
                    Nested::Map => visitor.visit_map(de),
215
                },
216
7
                EventKind::Primitive(primitive) => match primitive {
217
1
                    Primitive::Bool(v) => visitor.visit_bool(v),
218
3
                    Primitive::Integer(v) =>
219
3
                    {
220
3
                        #[allow(clippy::cast_possible_truncation)]
221
3
                        match v {
222
3
                            Integer::Usize(usize) => match usize::BITS {
223
3
                                0..=16 => visitor.visit_u16(usize as u16),
224
3
                                17..=32 => visitor.visit_u32(usize as u32),
225
3
                                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
1
                    Primitive::String(v) => match v {
249
1
                        Cow::Borrowed(v) => visitor.visit_borrowed_str(v),
250
                        Cow::Owned(v) => visitor.visit_string(v),
251
                    },
252
2
                    Primitive::Identifier(v) => {
253
2
                        // The tokenizer will have tokenized `r#None` to `None`, so
254
2
                        // we must check the length of the original source to verify
255
2
                        // this isn't a raw identifier.
256
2
                        if v == "None" && event.location.end - event.location.start == 4 {
257
                            visitor.visit_none()
258
                        } else {
259
2
                            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
11
        })
271
11
    }
272

            
273
20
    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
274
20
    where
275
20
        V: serde::de::Visitor<'de>,
276
20
    {
277
20
        self.with_error_context(|de| match de.parser.next().transpose()? {
278
            Some(Event {
279
20
                kind: EventKind::Primitive(Primitive::Bool(value)),
280
20
                ..
281
20
            }) => 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
20
        })
292
20
    }
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
3
    fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
302
3
    where
303
3
        V: serde::de::Visitor<'de>,
304
3
    {
305
3
        self.with_error_context(|de| match de.parser.next().transpose()? {
306
            Some(Event {
307
3
                kind: EventKind::Primitive(Primitive::Float(value)),
308
3
                ..
309
3
            }) => 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
3
        })
320
3
    }
321

            
322
14
    fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
323
14
    where
324
14
        V: serde::de::Visitor<'de>,
325
14
    {
326
14
        self.with_error_context(|de| match de.parser.next().transpose()? {
327
            Some(Event {
328
14
                kind: EventKind::Primitive(Primitive::Char(value)),
329
14
                ..
330
14
            }) => 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
14
        })
337
14
    }
338

            
339
261
    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
340
261
    where
341
261
        V: serde::de::Visitor<'de>,
342
261
    {
343
261
        self.with_error_context(|de| match de.parser.next().transpose()? {
344
            Some(Event {
345
238
                kind: EventKind::Primitive(Primitive::Identifier(str)),
346
238
                ..
347
238
            }) => visitor.visit_borrowed_str(str),
348
            Some(Event {
349
23
                kind: EventKind::Primitive(Primitive::String(str)),
350
23
                ..
351
23
            }) => match str {
352
19
                Cow::Borrowed(str) => visitor.visit_borrowed_str(str),
353
4
                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
261
        })
381
261
    }
382

            
383
23
    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
384
23
    where
385
23
        V: serde::de::Visitor<'de>,
386
23
    {
387
23
        self.with_error_context(|de| de.deserialize_str(visitor))
388
23
    }
389

            
390
14
    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
391
14
    where
392
14
        V: serde::de::Visitor<'de>,
393
14
    {
394
14
        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
14
                kind: EventKind::Primitive(Primitive::Bytes(bytes)),
408
14
                ..
409
14
            }) => match bytes {
410
10
                Cow::Borrowed(bytes) => visitor.visit_borrowed_bytes(bytes),
411
4
                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
14
        })
419
14
    }
420

            
421
14
    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
422
14
    where
423
14
        V: serde::de::Visitor<'de>,
424
14
    {
425
14
        self.deserialize_bytes(visitor)
426
14
    }
427

            
428
6
    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
429
6
    where
430
6
        V: serde::de::Visitor<'de>,
431
6
    {
432
6
        self.with_error_context(|de| match de.parser.peek() {
433
            Some(Ok(Event {
434
2
                kind: EventKind::Primitive(Primitive::Identifier(str)),
435
2
                ..
436
2
            })) if *str == "None" => {
437
2
                de.parser.next();
438
2
                visitor.visit_none()
439
            }
440
            Some(Ok(Event {
441
                kind:
442
                    EventKind::BeginNested {
443
3
                        name: Some(Name { name: "Some", .. }),
444
                        kind: Nested::Tuple,
445
                    },
446
                ..
447
            })) => {
448
3
                de.parser.next();
449
3
                let result = visitor.visit_some(&mut *de)?;
450
3
                match de.parser.next().transpose()? {
451
                    Some(Event {
452
                        kind: EventKind::EndNested,
453
                        ..
454
3
                    }) => 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
1
            _ => visitor.visit_some(de),
464
6
        })
465
6
    }
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
9
    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
499
9
    where
500
9
        V: serde::de::Visitor<'de>,
501
9
    {
502
9
        self.with_error_context(|de| match de.parser.next().transpose()? {
503
            Some(Event {
504
9
                kind: EventKind::BeginNested { kind, .. },
505
9
                location,
506
            }) => {
507
9
                if !matches!(kind, Nested::Tuple | Nested::List) {
508
                    return Err(DeserializerError::new(
509
                        location,
510
                        ErrorKind::ExpectedSequence,
511
                    ));
512
9
                }
513
9

            
514
9
                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
9
        })
525
9
    }
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
2
    fn deserialize_tuple_struct<V>(
535
2
        self,
536
2
        struct_name: &'static str,
537
2
        _len: usize,
538
2
        visitor: V,
539
2
    ) -> Result<V::Value, Self::Error>
540
2
    where
541
2
        V: serde::de::Visitor<'de>,
542
2
    {
543
2
        let is_parsing_newtype_tuple =
544
2
            matches!(self.newtype_state, Some(NewtypeState::TupleVariant));
545
2
        let next_token_is_nested_tuple = matches!(
546
2
            self.parser.peek(),
547
            Some(Ok(Event {
548
                kind: EventKind::BeginNested {
549
                    kind: Nested::Tuple,
550
                    ..
551
                },
552
                ..
553
            }))
554
        );
555
2
        self.with_error_context(|de| {
556
2
            if is_parsing_newtype_tuple {
557
2
                if next_token_is_nested_tuple {
558
                    // We have a multi-nested newtype situation here, and to enable
559
                    // parsing the `)` easily, we need to "take over" by erasing the
560
                    // current newtype state.
561
1
                    de.parser.next();
562
1
                    return visitor.visit_seq(sealed::SequenceDeserializer::new(de));
563
1
                }
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
1
            visitor.visit_seq(sealed::SequenceDeserializer::new(de))
600
2
        })
601
2
    }
602

            
603
2
    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
604
2
    where
605
2
        V: serde::de::Visitor<'de>,
606
2
    {
607
2
        self.with_error_context(|de| match de.parser.next().transpose()? {
608
            Some(Event {
609
2
                kind: EventKind::BeginNested { kind, .. },
610
2
                location,
611
2
            }) => {
612
2
                if kind != Nested::Map {
613
                    return Err(DeserializerError::new(location, ErrorKind::ExpectedMap));
614
2
                }
615
2

            
616
2
                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
2
        })
627
2
    }
628

            
629
24
    fn deserialize_struct<V>(
630
24
        self,
631
24
        struct_name: &'static str,
632
24
        _fields: &'static [&'static str],
633
24
        visitor: V,
634
24
    ) -> Result<V::Value, Self::Error>
635
24
    where
636
24
        V: serde::de::Visitor<'de>,
637
24
    {
638
24
        self.with_error_context(|de| {
639
24
            match de.parser.next().transpose()? {
640
                Some(Event {
641
24
                    kind: EventKind::BeginNested { name, kind },
642
24
                    location,
643
24
                }) => {
644
24
                    if name.map_or(false, |name| name != struct_name)
645
1
                        && !matches!(de.newtype_state, Some(NewtypeState::StructVariant))
646
                    {
647
                        return Err(DeserializerError::new(
648
                            location,
649
                            ErrorKind::NameMismatch(struct_name),
650
                        ));
651
24
                    }
652
24

            
653
24
                    if kind != Nested::Map {
654
                        return Err(DeserializerError::new(
655
                            location,
656
                            ErrorKind::ExpectedMapStruct,
657
                        ));
658
24
                    }
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
24
            visitor.visit_map(de)
675
24
        })
676
24
    }
677

            
678
17
    fn deserialize_enum<V>(
679
17
        self,
680
17
        _name: &'static str,
681
17
        _variants: &'static [&'static str],
682
17
        visitor: V,
683
17
    ) -> Result<V::Value, Self::Error>
684
17
    where
685
17
        V: serde::de::Visitor<'de>,
686
17
    {
687
17
        self.with_error_context(|de| visitor.visit_enum(de))
688
17
    }
689

            
690
238
    fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
691
238
    where
692
238
        V: serde::de::Visitor<'de>,
693
238
    {
694
238
        self.with_error_context(|de| de.deserialize_str(visitor))
695
238
    }
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

            
739
impl<'de> MapAccess<'de> for Deserializer<'de> {
740
    type Error = DeserializerError;
741

            
742
272
    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
743
272
    where
744
272
        K: serde::de::DeserializeSeed<'de>,
745
272
    {
746
272
        self.with_error_context(|de| match de.parser.peek() {
747
            Some(Ok(Event {
748
                kind: EventKind::EndNested,
749
                ..
750
            })) => {
751
31
                de.parser.next();
752
31
                Ok(None)
753
            }
754
241
            Some(Ok(evt)) => {
755
241
                let error_start = evt.location.start;
756
241
                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
272
        })
764
272
    }
765

            
766
241
    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
767
241
    where
768
241
        V: serde::de::DeserializeSeed<'de>,
769
241
    {
770
241
        seed.deserialize(&mut *self)
771
241
    }
772
}
773

            
774
mod 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
31
        pub(crate) fn new(de: &'a mut Deserializer<'de>) -> Self {
786
31
            Self { de, ended: false }
787
31
        }
788
    }
789

            
790
    impl<'a, 'de> SeqAccess<'de> for SequenceDeserializer<'a, 'de> {
791
        type Error = DeserializerError;
792

            
793
41
        fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
794
41
        where
795
41
            T: serde::de::DeserializeSeed<'de>,
796
41
        {
797
41
            self.de.with_error_context(|de| match de.parser.peek() {
798
                Some(Ok(Event {
799
                    kind: EventKind::EndNested,
800
                    ..
801
                })) => {
802
8
                    de.parser.next();
803
8
                    self.ended = true;
804
8
                    Ok(None)
805
                }
806
33
                Some(Ok(evt)) => {
807
33
                    let error_start = evt.location.start;
808
33
                    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
41
            })
816
41
        }
817
    }
818

            
819
    impl<'a, 'de> Drop for SequenceDeserializer<'a, 'de> {
820
31
        fn drop(&mut self) {
821
31
            if !self.ended {
822
15
                let mut levels = 1;
823
                loop {
824
16
                    if matches!(self.de.parser.peek(), None | Some(Err(_))) {
825
1
                        break;
826
15
                    }
827
15

            
828
15
                    match self.de.parser.next().expect("just peeked") {
829
                        Ok(Event {
830
                            kind: EventKind::EndNested,
831
                            ..
832
                        }) => {
833
14
                            levels -= 1;
834
14
                            if levels == 0 {
835
14
                                break;
836
                            }
837
                        }
838
                        Ok(Event {
839
                            kind: EventKind::BeginNested { .. },
840
                            ..
841
                        }) => {
842
                            levels += 1;
843
                        }
844
1
                        _ => {}
845
                    }
846
                }
847
16
            }
848
31
        }
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
17
        fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
856
17
        where
857
17
            V: serde::de::DeserializeSeed<'de>,
858
17
        {
859
17
            match self.parser.peek() {
860
                Some(Ok(Event {
861
                    kind: EventKind::Primitive(Primitive::Identifier(_) | Primitive::String(_)),
862
                    ..
863
3
                })) => Ok((seed.deserialize(&mut *self)?, EnumVariantAccessor::Unit)),
864
                Some(Ok(Event {
865
                    kind:
866
                        EventKind::BeginNested {
867
14
                            name: Some(name), ..
868
                        },
869
                    ..
870
                })) => {
871
14
                    let variant = seed.deserialize(&mut VariantDeserializer(name))?;
872
14
                    Ok((variant, EnumVariantAccessor::Nested(self)))
873
                }
874
                _ => Err(DeserializerError::new(None, ErrorKind::ExpectedEnum)),
875
            }
876
            // match &self.0 {
877
            //     Value::Identifier(_) | Value::String(_) => {}
878
            //     Value::Named(named) => {
879
            //         let variant =
880
            //             seed.deserialize(ValueDeserializer(&Value::String(named.name.clone())))?;
881

            
882
            //         let accessor = match &named.contents {
883
            //             StructContents::Map(map) => EnumVariantAccessor::Map(map),
884
            //             StructContents::Tuple(list) => EnumVariantAccessor::Tuple(list),
885
            //         };
886

            
887
            //         Ok((variant, accessor))
888
            //     }
889
            //     _ => Err(FromValueError::Expected(ExpectedKind::Enum)),
890
            // }
891
17
        }
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>,
        {
            visitor.visit_str(self.0)
        }

            
        fn deserialize_bytes<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
        where
            V: serde::de::Visitor<'de>,
        {
            Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
        }

            
        fn deserialize_byte_buf<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
        where
            V: serde::de::Visitor<'de>,
        {
            Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
        }

            
        fn deserialize_option<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
        where
            V: serde::de::Visitor<'de>,
        {
            Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
        }

            
        fn deserialize_unit<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
        where
            V: serde::de::Visitor<'de>,
        {
            Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
        }

            
        fn deserialize_unit_struct<V>(
            self,
            _name: &'static str,
            _visitor: V,
        ) -> Result<V::Value, Self::Error>
        where
            V: serde::de::Visitor<'de>,
        {
            Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
        }

            
        fn deserialize_newtype_struct<V>(
            self,
            _name: &'static str,
            _visitor: V,
        ) -> Result<V::Value, Self::Error>
        where
            V: serde::de::Visitor<'de>,
        {
            Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
        }

            
        fn deserialize_seq<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
        where
            V: serde::de::Visitor<'de>,
        {
            Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
        }

            
        fn deserialize_tuple<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error>
        where
            V: serde::de::Visitor<'de>,
        {
            Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
        }

            
        fn deserialize_tuple_struct<V>(
            self,
            _name: &'static str,
            _len: usize,
            _visitor: V,
        ) -> Result<V::Value, Self::Error>
        where
            V: serde::de::Visitor<'de>,
        {
            Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
        }

            
        fn deserialize_map<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
        where
            V: serde::de::Visitor<'de>,
        {
            Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
        }

            
        fn deserialize_struct<V>(
            self,
            _name: &'static str,
            _fields: &'static [&'static str],
            _visitor: V,
        ) -> Result<V::Value, Self::Error>
        where
            V: serde::de::Visitor<'de>,
        {
            Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
        }

            
        fn deserialize_enum<V>(
            self,
            _name: &'static str,
            _variants: &'static [&'static str],
            _visitor: V,
        ) -> Result<V::Value, Self::Error>
        where
            V: serde::de::Visitor<'de>,
        {
            Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
        }

            
14
        fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
14
        where
14
            V: serde::de::Visitor<'de>,
14
        {
14
            visitor.visit_str(self.0)
14
        }

            
        fn deserialize_ignored_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
        where
            V: serde::de::Visitor<'de>,
        {
            Err(DeserializerError::new(None, ErrorKind::ExpectedEnum))
        }
    }

            
    pub enum EnumVariantAccessor<'a, 'de> {
        Unit,
        Nested(&'a mut Deserializer<'de>),
    }

            
    impl<'a, 'de> VariantAccess<'de> for EnumVariantAccessor<'a, 'de> {
        type Error = DeserializerError;

            
4
        fn unit_variant(self) -> Result<(), Self::Error> {
4
            Ok(())
4
        }

            
8
        fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
8
        where
8
            T: serde::de::DeserializeSeed<'de>,
8
        {
8
            if let EnumVariantAccessor::Nested(deserializer) = self {
8
                let modification = match deserializer.parser.peek() {
                    Some(Ok(Event {
                        kind:
                            EventKind::BeginNested {
                                kind: Nested::Tuple,
                                ..
                            },
                        ..
                    })) => {
7
                        let _begin = deserializer.parser.next();
7
                        Some(deserializer.set_newtype_state(NewtypeState::TupleVariant))
                    }
                    Some(Ok(Event {
                        kind:
                            EventKind::BeginNested {
                                kind: Nested::Map, ..
                            },
                        ..
1
                    })) => Some(deserializer.set_newtype_state(NewtypeState::StructVariant)),
                    _ => None,
                };
8
                let result = deserializer.with_error_context(|de| seed.deserialize(&mut *de))?;
8
                if let Some(modification) = modification {
8
                    if deserializer.finish_newtype(modification) == Some(NewtypeState::TupleVariant)
7
                    {
7
                        // SequenceDeserializer has a loop in its drop to eat the
7
                        // remaining events until the end
7
                        drop(SequenceDeserializer::new(&mut *deserializer));
7
                    }
                }

            
8
                Ok(result)
            } else {
                Err(DeserializerError::new(None, ErrorKind::ExpectedTupleStruct))
            }
8
        }

            
3
        fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
3
        where
3
            V: serde::de::Visitor<'de>,
3
        {
3
            if let EnumVariantAccessor::Nested(deserializer) = self {
3
                let nested_event = deserializer
3
                    .parser
3
                    .next()
3
                    .expect("variant access matched Nested")?;
3
                deserializer.with_error_start(nested_event.location.start, |de| {
3
                    visitor.visit_seq(SequenceDeserializer::new(de))
3
                })
            } else {
                Err(DeserializerError::new(None, ErrorKind::ExpectedTupleStruct))
            }
3
        }

            
3
        fn struct_variant<V>(
3
            self,
3
            _fields: &'static [&'static str],
3
            visitor: V,
3
        ) -> Result<V::Value, Self::Error>
3
        where
3
            V: serde::de::Visitor<'de>,
3
        {
3
            if let EnumVariantAccessor::Nested(deserializer) = self {
3
                let nested_event = deserializer
3
                    .parser
3
                    .next()
3
                    .expect("variant access matched Nested")?;
3
                deserializer
3
                    .with_error_start(nested_event.location.start, |de| visitor.visit_map(de))
            } else {
                Err(DeserializerError::new(None, ErrorKind::ExpectedTupleStruct))
            }
3
        }
    }
}

            
/// A deserialization error.
#[derive(Debug, Clone, PartialEq)]
pub struct Error {
    /// The offset of bytes in the source when the error occurred.
    pub location: Range<usize>,
    /// The kind of error that occurred.
    pub kind: ErrorKind,
}

            
impl Error {
1
    fn new(location: Range<usize>, kind: impl Into<ErrorKind>) -> Self {
1
        Self {
1
            location,
1
            kind: kind.into(),
1
        }
1
    }
}

            
impl From<parser::Error> for Error {
    fn from(err: parser::Error) -> Self {
        Self {
            location: err.location,
            kind: err.kind.into(),
        }
    }
}
impl serde::ser::StdError for Error {}

            
impl Display for Error {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "{} at {}..{}",
            self.kind, self.location.start, self.location.end
        )
    }
}

            
/// An error that arose while deserializing Rsn.
#[derive(Debug, Clone, PartialEq)]
pub struct DeserializerError {
    /// The location of the error, if available.
    pub location: Option<Range<usize>>,
    /// The kind of error that occurred.
    pub kind: ErrorKind,
}

            
impl DeserializerError {
    fn new(location: impl Into<Option<Range<usize>>>, kind: impl Into<ErrorKind>) -> Self {
        Self {
            location: location.into(),
            kind: kind.into(),
        }
    }
}

            
impl serde::de::Error for DeserializerError {
7
    fn custom<T>(msg: T) -> Self
7
    where
7
        T: Display,
7
    {
7
        Self {
7
            location: None,
7
            kind: ErrorKind::Message(msg.to_string()),
7
        }
7
    }
}

            
impl serde::ser::StdError for DeserializerError {}

            
impl Display for DeserializerError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        if let Some(location) = &self.location {
            write!(f, "{} at {}..{}", self.kind, location.start, location.end)
        } else {
            Display::fmt(&self.kind, f)
        }
    }
}

            
impl From<parser::Error> for DeserializerError {
    fn from(err: parser::Error) -> Self {
        Self {
            location: Some(err.location),
            kind: err.kind.into(),
        }
    }
}

            
/// The kind of a deserialization error.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum ErrorKind {
    /// An integer was expected.
    ExpectedInteger,
    /// A floating point number was expected.
    ExpectedFloat,
    /// A unit type was expected.
    ExpectedUnit,
    /// A boolean literal was expected.
    ExpectedBool,
    /// An option was expected.
    ExpectedOption,
    /// A character literal was expected.
    ExpectedChar,
    /// A string literal was expected.
    ExpectedString,
    /// A byte string literal was expected.
    ExpectedBytes,
    /// A sequence (list) was expected.
    ExpectedSequence,
    /// A map was expected.
    ExpectedMap,
    /// A structure containing a tuple was expected.
    ExpectedTupleStruct,
    /// A structure containing named fields was expected.
    ExpectedMapStruct,
    /// An enumerated value was expected.
    ExpectedEnum,
    /// Invalid UTF-8 was encountered in the input or while decoding escaped
    /// characters.
    InvalidUtf8,
    /// The name of a type did not match what was expected.
    ///
    /// The `&str` parameter is the name that was expected.
    NameMismatch(&'static str),
    /// `Some(_)` can only contain one value but more than one value was
    /// encountered.
    SomeCanOnlyContainOneValue,
    /// An Rsn parsing error.
    Parser(parser::ErrorKind),
    /// An error from deserializing Serde.
    Message(String),
}

            
impl From<parser::ErrorKind> for ErrorKind {
    fn from(kind: parser::ErrorKind) -> Self {
        Self::Parser(kind)
    }
}

            
impl From<tokenizer::ErrorKind> for ErrorKind {
    fn from(kind: tokenizer::ErrorKind) -> Self {
        Self::Parser(kind.into())
    }
}

            
impl Display for ErrorKind {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            ErrorKind::Parser(parser) => Display::fmt(parser, f),
            ErrorKind::Message(message) => f.write_str(message),
            ErrorKind::ExpectedInteger => f.write_str("expected integer"),
            ErrorKind::ExpectedFloat => f.write_str("expected float"),
            ErrorKind::ExpectedBool => f.write_str("expected bool"),
            ErrorKind::ExpectedUnit => f.write_str("expected unit"),
            ErrorKind::ExpectedOption => f.write_str("expected option"),
            ErrorKind::ExpectedChar => f.write_str("expected char"),
            ErrorKind::ExpectedString => f.write_str("expected string"),
            ErrorKind::ExpectedBytes => f.write_str("expected bytes"),
            ErrorKind::SomeCanOnlyContainOneValue => {
                f.write_str("Some(_) can only contain one value")
            }
            ErrorKind::ExpectedSequence => f.write_str("expected sequence"),
            ErrorKind::ExpectedMap => f.write_str("expected map"),
            ErrorKind::ExpectedTupleStruct => f.write_str("expected tuple struct"),
            ErrorKind::ExpectedMapStruct => f.write_str("expected map struct"),
            ErrorKind::ExpectedEnum => f.write_str("expected enum"),
            ErrorKind::NameMismatch(name) => write!(f, "name mismatch, expected {name}"),
            ErrorKind::InvalidUtf8 => f.write_str("invalid utf-8"),
        }
    }
}

            
impl Config {
    /// Deserializes `T` from `source` using this configuration.
    ///
    /// ```rust
    /// let deserialized: Vec<usize> = rsn::parser::Config::default()
    ///     .deserialize("[1, 2, 3]")
    ///     .unwrap();
    /// assert_eq!(deserialized, vec![1, 2, 3]);
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if `source` cannot be deserialized as `T`.
43
    pub fn deserialize<'de, T: Deserialize<'de>>(self, source: &'de str) -> Result<T, Error> {
43
        let mut deserializer = Deserializer::new(source, self);
43
        let result = match T::deserialize(&mut deserializer) {
42
            Ok(result) => result,
1
            Err(err) => {
1
                let location = err
1
                    .location
1
                    .unwrap_or_else(|| deserializer.parser.current_range());
1
                return Err(Error::new(location, err.kind));
            }
        };
42
        deserializer.ensure_eof()?;
42
        Ok(result)
43
    }

            
    /// Deserializes `T` from `source` using this configuration.
    ///
    /// ```rust
    /// let deserialized: Vec<usize> = rsn::parser::Config::default()
    ///     .deserialize_from_slice(b"[1, 2, 3]")
    ///     .unwrap();
    /// assert_eq!(deserialized, vec![1, 2, 3]);
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if `source` cannot be deserialized as `T`.
    pub fn deserialize_from_slice<'de, T: Deserialize<'de>>(
        self,
        source: &'de [u8],
    ) -> Result<T, Error> {
        let source = match alloc::str::from_utf8(source) {
            Ok(source) => source,
            Err(error) => {
                let end = error
                    .error_len()
                    .map_or(source.len(), |l| l + error.valid_up_to());
                return Err(Error::new(
                    (error.valid_up_to() + 1)..end,
                    ErrorKind::InvalidUtf8,
                ));
            }
        };
        self.deserialize(source)
    }

            
    /// Deserializes `T` from `reader` using this configuration.
    ///
    /// ```rust
    /// let deserialized: Vec<usize> = rsn::parser::Config::default()
    ///     .deserialize_from_reader(&b"[1, 2, 3]"[..])
    ///     .unwrap();
    /// assert_eq!(deserialized, vec![1, 2, 3]);
    /// ```
    ///
    /// # Errors
    ///
    /// Returns any errors encountered while reading from `reader` or if
    /// `reader` cannot be deserialized as `T`.
    #[cfg(feature = "std")]
    pub fn deserialize_from_reader<T: DeserializeOwned, R: std::io::Read>(
        self,
        mut reader: R,
    ) -> Result<T, Error> {
        let mut source = alloc::vec::Vec::new();
        reader
            .read_to_end(&mut source)
            .map_err(|e| Error::new(0..0, ErrorKind::Message(e.to_string())))?;
        self.deserialize_from_slice(&source)
    }
}

            
struct BetterPeekable<T>
where
    T: Iterator,
{
    iter: T,
    peeked: Option<T::Item>,
}

            
impl<T> BetterPeekable<T>
where
    T: Iterator,
{
45
    pub fn new(iter: T) -> Self {
45
        Self { iter, peeked: None }
45
    }

            
432
    pub fn peek(&mut self) -> Option<&T::Item> {
432
        if self.peeked.is_none() {
421
            self.peeked = self.next();
421
        }

            
432
        self.peeked.as_ref()
432
    }
}

            
impl<T> core::ops::Deref for BetterPeekable<T>
where
    T: Iterator,
{
    type Target = T;

            
1352
    fn deref(&self) -> &Self::Target {
1352
        &self.iter
1352
    }
}

            
impl<T> Iterator for BetterPeekable<T>
where
    T: Iterator,
{
    type Item = T::Item;

            
1185
    fn next(&mut self) -> Option<Self::Item> {
1185
        self.peeked.take().or_else(|| self.iter.next())
1185
    }
}

            
#[cfg(test)]
mod tests {
    use serde::{Deserialize, Serialize};

            
    use crate::parser::Config;

            
    #[test]
1
    fn basic_named() {
3
        #[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
        struct BasicNamed {
            a: u32,
            b: i32,
        }

            
1
        let parsed = crate::from_str::<BasicNamed>(r"BasicNamed{ a: 1, b: -1 }").unwrap();
1
        assert_eq!(parsed, BasicNamed { a: 1, b: -1 });
1
    }

            
    #[test]
1
    fn implicit_map() {
12
        #[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
        struct BasicNamed {
            a: u32,
            b: i32,
        }
1
        let config = Config::default().allow_implicit_map_at_root(true);
1
        let parsed = config.deserialize::<BasicNamed>("a: 1 b: -1").unwrap();
1
        assert_eq!(parsed, BasicNamed { a: 1, b: -1 });
1
        let parsed = config.deserialize::<BasicNamed>("a: 1, b: -1,").unwrap();
1
        assert_eq!(parsed, BasicNamed { a: 1, b: -1 });
1
        let parsed = config.deserialize::<BasicNamed>("{a: 1, b: -1}").unwrap();
1
        assert_eq!(parsed, BasicNamed { a: 1, b: -1 });
1
        let parsed = config
1
            .deserialize::<BasicNamed>("BasicNamed{a: 1, b: -1}")
1
            .unwrap();
1
        assert_eq!(parsed, BasicNamed { a: 1, b: -1 });
1
    }

            
    #[test]
1
    fn optional() {
6
        #[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
        struct BasicNamed {
            a: u32,
            b: i32,
        }

            
1
        assert_eq!(crate::from_str::<Option<BasicNamed>>("None").unwrap(), None);

            
1
        let parsed =
1
            crate::from_str::<Option<BasicNamed>>("Some(BasicNamed{ a: 1, b: -1 })").unwrap();
1
        assert_eq!(parsed, Some(BasicNamed { a: 1, b: -1 }));

            
1
        let parsed = crate::from_str::<Option<BasicNamed>>("BasicNamed{ a: 1, b: -1 }").unwrap();
1
        assert_eq!(parsed, Some(BasicNamed { a: 1, b: -1 }));
1
    }

            
    #[test]
1
    fn error_locality() {
        #[derive(Debug, Deserialize)]
        #[serde(untagged)]
        enum Untagged {
            A(#[allow(unused)] u64),
        }

            
1
        let source = r#"[1, "hello"]"#;
1
        let err = crate::from_str::<alloc::vec::Vec<Untagged>>(source).unwrap_err();
1
        assert_eq!(&source[err.location], r#""hello""#);
1
    }

            
    #[test]
1
    fn enums() {
14
        #[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
        enum BasicEnums {
            Unit,
            NewType(u32),
            Struct { a: u32 },
            Tuple(u32, u32),
        }

            
1
        assert_eq!(
1
            crate::from_str::<BasicEnums>("Unit").unwrap(),
1
            BasicEnums::Unit
1
        );
1
        assert_eq!(
1
            crate::from_str::<BasicEnums>("NewType(1)").unwrap(),
1
            BasicEnums::NewType(1)
1
        );
1
        assert_eq!(
1
            crate::from_str::<BasicEnums>("Struct{ a: 1}").unwrap(),
1
            BasicEnums::Struct { a: 1 }
1
        );
1
        assert_eq!(
1
            crate::from_str::<BasicEnums>("Tuple(1,2)").unwrap(),
1
            BasicEnums::Tuple(1, 2)
1
        );
1
        assert_eq!(
1
            crate::from_str::<BasicEnums>("Tuple(1,2,3)").unwrap(),
1
            BasicEnums::Tuple(1, 2)
1
        );
1
    }
}