1
#![allow(clippy::identity_op)]
2

            
3
use alloc::{
4
    format,
5
    string::{String, ToString},
6
    vec::Vec,
7
};
8
use core::{
9
    char::from_u32 as char_from_u32,
10
    str::{self, from_utf8, FromStr, Utf8Error},
11
};
12

            
13
use unicode_ident::{is_xid_continue, is_xid_start};
14

            
15
use crate::{
16
    error::{Error, Position, Result, Span, SpannedError, SpannedResult},
17
    extensions::Extensions,
18
    value::Number,
19
};
20

            
21
48900025
const fn is_int_char(c: char) -> bool {
22
48900025
    c.is_ascii_hexdigit() || c == '_'
23
48900025
}
24

            
25
186225386
const fn is_float_char(c: char) -> bool {
26
186225386
    c.is_ascii_digit() || matches!(c, 'e' | 'E' | '.' | '+' | '-' | '_')
27
186225386
}
28

            
29
10298181
pub fn is_ident_first_char(c: char) -> bool {
30
10298181
    c == '_' || is_xid_start(c)
31
10298181
}
32

            
33
4654783
pub fn is_ident_raw_char(c: char) -> bool {
34
4654783
    matches!(c, '.' | '+' | '-') | is_xid_continue(c)
35
4654783
}
36

            
37
89707748
pub const fn is_whitespace_char(c: char) -> bool {
38
87315028
    matches!(
39
89707748
        c,
40
        ' ' | '\t'
41
            | '\n'
42
            | '\r'
43
            | '\x0B'
44
            | '\x0C'
45
            | '\u{85}'
46
            | '\u{200E}'
47
            | '\u{200F}'
48
            | '\u{2028}'
49
            | '\u{2029}'
50
    )
51
89707748
}
52

            
53
8940
const fn is_string_continuation_whitespace(c: char) -> bool {
54
8940
    matches!(c, ' ' | '\t' | '\n' | '\r')
55
8940
}
56

            
57
#[cfg(feature = "integer128")]
58
pub(crate) type LargeUInt = u128;
59
#[cfg(not(feature = "integer128"))]
60
pub(crate) type LargeUInt = u64;
61
#[cfg(feature = "integer128")]
62
pub(crate) type LargeSInt = i128;
63
#[cfg(not(feature = "integer128"))]
64
pub(crate) type LargeSInt = i64;
65

            
66
pub struct Parser<'a> {
67
    /// Bits set according to the [`Extensions`] enum.
68
    pub exts: Extensions,
69
    src: &'a str,
70
    cursor: ParserCursor,
71
    prev_cursor: ParserCursor,
72
}
73

            
74
#[derive(Copy, Clone)] // GRCOV_EXCL_LINE
75
pub struct ParserCursor {
76
    cursor: usize,
77
    pre_ws_cursor: usize,
78
    last_ws_len: usize,
79
}
80

            
81
enum ParsedAttribute {
82
    None,
83
    Extensions(Extensions),
84
    Ignored,
85
}
86

            
87
const WS_CURSOR_UNCLOSED_LINE: usize = usize::MAX;
88

            
89
impl PartialEq for ParserCursor {
90
8
    fn eq(&self, other: &Self) -> bool {
91
8
        self.cursor == other.cursor
92
8
    }
93
}
94

            
95
impl PartialOrd for ParserCursor {
96
3620
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
97
3620
        self.cursor.partial_cmp(&other.cursor)
98
3620
    }
99
}
100

            
101
/// constructor and parsing utilities
102
impl<'a> Parser<'a> {
103
598325
    pub fn new(src: &'a str) -> SpannedResult<Self> {
104
598325
        let mut parser = Parser {
105
598325
            exts: Extensions::empty(),
106
598325
            src,
107
598325
            cursor: ParserCursor {
108
598325
                cursor: 0,
109
598325
                pre_ws_cursor: 0,
110
598325
                last_ws_len: 0,
111
598325
            },
112
598325
            prev_cursor: ParserCursor {
113
598325
                cursor: 0,
114
598325
                pre_ws_cursor: 0,
115
598325
                last_ws_len: 0,
116
598325
            },
117
598325
        };
118

            
119
598325
        parser.skip_ws().map_err(|e| parser.span_error(e))?;
120

            
121
        // Loop over all document attributes
122
        loop {
123
635766
            match parser.attribute().map_err(|e| parser.span_error(e))? {
124
597462
                ParsedAttribute::None => break,
125
37703
                ParsedAttribute::Extensions(extensions) => {
126
37703
                    parser.exts |= extensions;
127
37703
                }
128
36
                ParsedAttribute::Ignored => {}
129
            }
130

            
131
37739
            parser.skip_ws().map_err(|e| parser.span_error(e))?;
132
        }
133

            
134
597462
        Ok(parser)
135
598325
    }
136

            
137
167825205
    fn set_cursor(&mut self, cursor: ParserCursor) {
138
167825205
        self.cursor = cursor;
139
167825205
    }
140

            
141
113899
    pub fn span_error(&self, code: Error) -> SpannedError {
142
113899
        SpannedError {
143
113899
            code,
144
113899
            span: Span {
145
113899
                start: Position::from_src_end(&self.src[..self.prev_cursor.cursor]),
146
113899
                end: Position::from_src_end(&self.src[..self.cursor.cursor]),
147
113899
            },
148
113899
        }
149
113899
    }
150

            
151
10132
    pub fn is_number_start(&self, c: char) -> bool {
152
10132
        matches!(c, '0'..='9' | '+' | '-' | '.' | 'b') && (c != 'b' || self.src().starts_with("b'"))
153
10132
    }
154

            
155
155538175
    pub fn advance_bytes(&mut self, bytes: usize) {
156
155538175
        self.prev_cursor = self.cursor;
157
155538175
        self.cursor.cursor += bytes;
158
155538175
    }
159

            
160
103091579
    pub fn next_char(&mut self) -> Result<char> {
161
103091579
        let c = self.peek_char_or_eof()?;
162
103091266
        self.cursor.cursor += c.len_utf8();
163
103091266
        Ok(c)
164
103091579
    }
165

            
166
45493
    pub fn skip_next_char(&mut self) {
167
45493
        core::mem::drop(self.next_char());
168
45493
    }
169

            
170
133169779
    pub fn peek_char(&self) -> Option<char> {
171
133169779
        self.src().chars().next()
172
133169779
    }
173

            
174
113712271
    pub fn peek_char_or_eof(&self) -> Result<char> {
175
113712271
        self.peek_char().ok_or(Error::Eof)
176
113712271
    }
177

            
178
342123580
    pub fn check_char(&self, c: char) -> bool {
179
342123580
        self.src().starts_with(c)
180
342123580
    }
181

            
182
500688436
    pub fn check_str(&self, s: &str) -> bool {
183
500688436
        self.src().starts_with(s)
184
500688436
    }
185

            
186
1533296730
    pub fn src(&self) -> &'a str {
187
1533296730
        &self.src[self.cursor.cursor..]
188
1533296730
    }
189

            
190
27754
    pub fn pre_ws_src(&self) -> &'a str {
191
27754
        &self.src[self.cursor.pre_ws_cursor..]
192
27754
    }
193

            
194
142027111
    pub fn consume_str(&mut self, s: &str) -> bool {
195
142027111
        if self.check_str(s) {
196
542817
            self.advance_bytes(s.len());
197

            
198
542817
            true
199
        } else {
200
141484294
            false
201
        }
202
142027111
    }
203

            
204
266172582
    pub fn consume_char(&mut self, c: char) -> bool {
205
266172582
        if self.check_char(c) {
206
10977207
            self.advance_bytes(c.len_utf8());
207

            
208
10977207
            true
209
        } else {
210
255195375
            false
211
        }
212
266172582
    }
213

            
214
76022
    fn consume_all(&mut self, all: &[&str]) -> Result<bool> {
215
76022
        all.iter()
216
190348
            .map(|elem| {
217
190348
                if self.consume_str(elem) {
218
190309
                    self.skip_ws()?;
219

            
220
190309
                    Ok(true)
221
                } else {
222
39
                    Ok(false)
223
                }
224
190348
            })
225
190348
            .try_fold(true, |acc, x| x.map(|x| x && acc))
226
76022
    }
227

            
228
56015323
    pub fn expect_char(&mut self, expected: char, error: Error) -> Result<()> {
229
56015323
        if self.consume_char(expected) {
230
137294
            Ok(())
231
        } else {
232
55878029
            Err(error)
233
        }
234
56015323
    }
235

            
236
    #[must_use]
237
97516938
    pub fn next_chars_while_len(&self, condition: fn(char) -> bool) -> usize {
238
97516938
        self.next_chars_while_from_len(0, condition)
239
97516938
    }
240

            
241
    #[must_use]
242
117198347
    pub fn next_chars_while_from_len(&self, from: usize, condition: fn(char) -> bool) -> usize {
243
117198347
        self.src()[from..]
244
329591378
            .find(|c| !condition(c))
245
117198347
            .unwrap_or(self.src().len() - from)
246
117198347
    }
247
}
248

            
249
/// actual parsing of ron tokens
250
impl<'a> Parser<'a> {
251
243440
    fn parse_integer_digits<T: Num>(
252
243440
        &mut self,
253
243440
        s: &str,
254
243440
        base: u8,
255
243440
        f: fn(&mut T, u8) -> bool,
256
243440
    ) -> Result<T> {
257
243440
        let mut num_acc = T::from_u8(0);
258

            
259
598343
        for (i, c) in s.char_indices() {
260
598343
            if c == '_' {
261
9978
                continue;
262
588365
            }
263

            
264
588365
            if num_acc.checked_mul_ext(base) {
265
902
                self.advance_bytes(s.len());
266
902
                return Err(Error::IntegerOutOfBounds);
267
587463
            }
268

            
269
587463
            let digit = Self::decode_hex(c)?;
270

            
271
587463
            if digit >= base {
272
2086
                self.advance_bytes(i);
273
2086
                return Err(Error::InvalidIntegerDigit { digit: c, base });
274
585377
            }
275

            
276
585377
            if f(&mut num_acc, digit) {
277
3427
                self.advance_bytes(s.len());
278
3427
                return Err(Error::IntegerOutOfBounds);
279
581950
            }
280
        }
281

            
282
237025
        self.advance_bytes(s.len());
283

            
284
237025
        Ok(num_acc)
285
243440
    }
286

            
287
251216
    fn parse_integer<T: Num>(&mut self, sign: i8, base: u8) -> Result<T> {
288
251216
        let num_bytes = self.next_chars_while_len(is_int_char);
289

            
290
251216
        if num_bytes == 0 {
291
4796
            return Err(Error::ExpectedInteger);
292
246420
        }
293

            
294
246420
        if self.check_char('_') {
295
2980
            return Err(Error::UnderscoreAtBeginning);
296
243440
        }
297

            
298
243440
        let s = &self.src()[..num_bytes];
299

            
300
243440
        if sign > 0 {
301
225419
            self.parse_integer_digits(s, base, T::checked_add_ext)
302
        } else {
303
18021
            self.parse_integer_digits(s, base, T::checked_sub_ext)
304
        }
305
251216
    }
306

            
307
    #[allow(clippy::too_many_lines)]
308
348179
    pub fn integer<T: Integer>(&mut self) -> Result<T> {
309
348179
        let src_backup = self.src();
310

            
311
348179
        let is_negative = match self.peek_char_or_eof()? {
312
            '+' => {
313
28
                self.skip_next_char();
314
28
                false
315
            }
316
            '-' => {
317
5335
                self.skip_next_char();
318
5335
                true
319
            }
320
232146
            'b' if self.consume_str("b'") => {
321
                // Parse a byte literal
322
232146
                let byte = match self.next_char()? {
323
203236
                    '\\' => match self.parse_escape(EscapeEncoding::Binary, true)? {
324
                        // we know that this byte is an ASCII character
325
202640
                        EscapeCharacter::Ascii(b) => b,
326
                        EscapeCharacter::Utf8(_) => {
327
298
                            return Err(Error::InvalidEscape(
328
298
                                "Unexpected Unicode escape in byte literal",
329
298
                            ))
330
                        }
331
                    },
332
28910
                    b if b.is_ascii() => b as u8,
333
298
                    _ => return Err(Error::ExpectedByteLiteral),
334
                };
335

            
336
231252
                if !self.consume_char('\'') {
337
298
                    return Err(Error::ExpectedByteLiteral);
338
230954
                }
339

            
340
230954
                let bytes_ron = &src_backup[..src_backup.len() - self.src().len()];
341

            
342
230954
                return T::try_from_parsed_integer(ParsedInteger::U8(byte), bytes_ron);
343
            }
344
110670
            _ => false,
345
        };
346
116033
        let sign = if is_negative { -1 } else { 1 };
347

            
348
116033
        let base = match () {
349
116033
            () if self.consume_str("0b") => 2,
350
113315
            () if self.consume_str("0o") => 8,
351
111491
            () if self.consume_str("0x") => 16,
352
109663
            () => 10,
353
        };
354

            
355
116033
        let num_bytes = self.next_chars_while_len(is_int_char);
356

            
357
116033
        if self.src()[num_bytes..].starts_with(['i', 'u']) {
358
12841
            let int_cursor = self.cursor;
359
12841
            self.advance_bytes(num_bytes);
360

            
361
            #[allow(clippy::never_loop)]
362
            loop {
363
12841
                let (res, suffix_bytes) = if self.consume_ident("i8") {
364
934
                    let suffix_bytes = self.src();
365
934
                    self.set_cursor(int_cursor);
366
934
                    (
367
934
                        self.parse_integer::<i8>(sign, base).map(ParsedInteger::I8),
368
934
                        suffix_bytes,
369
934
                    )
370
11907
                } else if self.consume_ident("i16") {
371
934
                    let suffix_bytes = self.src();
372
934
                    self.set_cursor(int_cursor);
373
934
                    (
374
934
                        self.parse_integer::<i16>(sign, base)
375
934
                            .map(ParsedInteger::I16),
376
934
                        suffix_bytes,
377
934
                    )
378
10973
                } else if self.consume_ident("i32") {
379
1276
                    let suffix_bytes = self.src();
380
1276
                    self.set_cursor(int_cursor);
381
1276
                    (
382
1276
                        self.parse_integer::<i32>(sign, base)
383
1276
                            .map(ParsedInteger::I32),
384
1276
                        suffix_bytes,
385
1276
                    )
386
9697
                } else if self.consume_ident("i64") {
387
934
                    let suffix_bytes = self.src();
388
934
                    self.set_cursor(int_cursor);
389
934
                    (
390
934
                        self.parse_integer::<i64>(sign, base)
391
934
                            .map(ParsedInteger::I64),
392
934
                        suffix_bytes,
393
934
                    )
394
8763
                } else if self.consume_ident("u8") {
395
2420
                    let suffix_bytes = self.src();
396
2420
                    self.set_cursor(int_cursor);
397
2420
                    (
398
2420
                        self.parse_integer::<u8>(sign, base).map(ParsedInteger::U8),
399
2420
                        suffix_bytes,
400
2420
                    )
401
6343
                } else if self.consume_ident("u16") {
402
1236
                    let suffix_bytes = self.src();
403
1236
                    self.set_cursor(int_cursor);
404
1236
                    (
405
1236
                        self.parse_integer::<u16>(sign, base)
406
1236
                            .map(ParsedInteger::U16),
407
1236
                        suffix_bytes,
408
1236
                    )
409
5107
                } else if self.consume_ident("u32") {
410
1268
                    let suffix_bytes = self.src();
411
1268
                    self.set_cursor(int_cursor);
412
1268
                    (
413
1268
                        self.parse_integer::<u32>(sign, base)
414
1268
                            .map(ParsedInteger::U32),
415
1268
                        suffix_bytes,
416
1268
                    )
417
3839
                } else if self.consume_ident("u64") {
418
1236
                    let suffix_bytes = self.src();
419
1236
                    self.set_cursor(int_cursor);
420
1236
                    (
421
1236
                        self.parse_integer::<u64>(sign, base)
422
1236
                            .map(ParsedInteger::U64),
423
1236
                        suffix_bytes,
424
1236
                    )
425
                } else {
426
                    #[cfg(feature = "integer128")]
427
1695
                    if self.consume_ident("i128") {
428
469
                        let suffix_bytes = self.src();
429
469
                        self.set_cursor(int_cursor);
430
469
                        (
431
469
                            self.parse_integer::<i128>(sign, base)
432
469
                                .map(ParsedInteger::I128),
433
469
                            suffix_bytes,
434
469
                        )
435
1226
                    } else if self.consume_ident("u128") {
436
620
                        let suffix_bytes = self.src();
437
620
                        self.set_cursor(int_cursor);
438
620
                        (
439
620
                            self.parse_integer::<u128>(sign, base)
440
620
                                .map(ParsedInteger::U128),
441
620
                            suffix_bytes,
442
620
                        )
443
                    } else {
444
606
                        break;
445
                    }
446
                    #[cfg(not(feature = "integer128"))]
447
                    {
448
908
                        break;
449
                    }
450
                };
451

            
452
11021
                if !matches!(
453
1963
                    &res,
454
                    Err(Error::UnderscoreAtBeginning | Error::InvalidIntegerDigit { .. })
455
11021
                ) {
456
11021
                    // Advance past the number suffix
457
11021
                    self.skip_identifier();
458
11021
                }
459

            
460
11327
                let integer_ron = &src_backup[..src_backup.len() - suffix_bytes.len()];
461

            
462
11327
                return res.and_then(|parsed| T::try_from_parsed_integer(parsed, integer_ron));
463
            }
464

            
465
1514
            self.set_cursor(int_cursor);
466
103192
        }
467

            
468
104706
        T::parse(self, sign, base)
469
348179
    }
470

            
471
    /// Check whether [`Parser::any_number`] has a number literal to parse at
472
    /// the cursor. The `inf` and `NaN` literals start with a letter, so they
473
    /// are not covered by [`Parser::is_number_start`].
474
8642
    pub fn check_any_number_start(&mut self) -> bool {
475
8642
        match self.peek_char() {
476
            None => false,
477
8642
            Some(c) => {
478
8642
                self.is_number_start(c)
479
6556
                    || self.check_ident("inf")
480
5662
                    || self.check_ident("inff32")
481
5364
                    || self.check_ident("inff64")
482
5066
                    || self.check_ident("NaN")
483
4172
                    || self.check_ident("NaNf32")
484
3874
                    || self.check_ident("NaNf64")
485
            }
486
        }
487
8642
    }
488

            
489
9578987
    pub fn any_number(&mut self) -> Result<Number> {
490
9578987
        if self.consume_ident("inf") || self.consume_ident("inff32") {
491
1196
            return Ok(Number::F32(crate::value::F32(core::f32::INFINITY)));
492
9577791
        } else if self.consume_ident("inff64") {
493
298
            return Ok(Number::F64(crate::value::F64(core::f64::INFINITY)));
494
9577493
        } else if self.consume_ident("NaN") || self.consume_ident("NaNf32") {
495
1196
            return Ok(Number::F32(crate::value::F32(core::f32::NAN)));
496
9576297
        } else if self.consume_ident("NaNf64") {
497
298
            return Ok(Number::F64(crate::value::F64(core::f64::NAN)));
498
9575999
        }
499

            
500
9575999
        if self.next_bytes_is_float() {
501
9251482
            return match self.float::<ParsedFloat>()? {
502
5412
                ParsedFloat::F32(v) => Ok(Number::F32(v.into())),
503
9246070
                ParsedFloat::F64(v) => Ok(Number::F64(v.into())),
504
            };
505
324517
        }
506

            
507
324517
        let backup_cursor = self.cursor;
508

            
509
324517
        let (integer_err, integer_cursor) = match self.integer::<ParsedInteger>() {
510
320905
            Ok(integer) => {
511
320905
                return match integer {
512
906
                    ParsedInteger::I8(v) => Ok(Number::I8(v)),
513
600
                    ParsedInteger::I16(v) => Ok(Number::I16(v)),
514
600
                    ParsedInteger::I32(v) => Ok(Number::I32(v)),
515
600
                    ParsedInteger::I64(v) => Ok(Number::I64(v)),
516
                    #[cfg(feature = "integer128")]
517
598
                    ParsedInteger::I128(v) => Ok(Number::I128(v)),
518
314603
                    ParsedInteger::U8(v) => Ok(Number::U8(v)),
519
902
                    ParsedInteger::U16(v) => Ok(Number::U16(v)),
520
600
                    ParsedInteger::U32(v) => Ok(Number::U32(v)),
521
600
                    ParsedInteger::U64(v) => Ok(Number::U64(v)),
522
                    #[cfg(feature = "integer128")]
523
896
                    ParsedInteger::U128(v) => Ok(Number::U128(v)),
524
                }
525
            }
526
3612
            Err(err) => (err, self.cursor),
527
        };
528

            
529
3612
        self.set_cursor(backup_cursor);
530

            
531
        // Fall-back to parse an out-of-range integer as a float
532
3612
        match self.float::<ParsedFloat>() {
533
3008
            Ok(ParsedFloat::F32(v)) if self.cursor >= integer_cursor => Ok(Number::F32(v.into())),
534
604
            Ok(ParsedFloat::F64(v)) if self.cursor >= integer_cursor => Ok(Number::F64(v.into())),
535
            _ => {
536
                // Return the more precise integer error
537
1341
                self.set_cursor(integer_cursor);
538
1341
                Err(integer_err)
539
            }
540
        }
541
9578987
    }
542

            
543
33228
    pub fn bool(&mut self) -> Result<bool> {
544
33228
        if self.consume_ident("true") {
545
18546
            Ok(true)
546
14682
        } else if self.consume_ident("false") {
547
14646
            Ok(false)
548
        } else {
549
36
            Err(Error::ExpectedBoolean)
550
        }
551
33228
    }
552

            
553
55930401
    pub fn char(&mut self) -> Result<char> {
554
55930401
        self.expect_char('\'', Error::ExpectedChar)?;
555

            
556
52972
        let c = self.next_char()?;
557

            
558
52972
        let c = if c == '\\' {
559
4184
            match self.parse_escape(EscapeEncoding::Utf8, true)? {
560
                // we know that this byte is an ASCII character
561
1800
                EscapeCharacter::Ascii(b) => char::from(b),
562
1192
                EscapeCharacter::Utf8(c) => c,
563
            }
564
        } else {
565
48788
            c
566
        };
567

            
568
51780
        self.expect_char('\'', Error::ExpectedChar)?;
569

            
570
51780
        Ok(c)
571
55930401
    }
572

            
573
9689324
    pub fn comma(&mut self) -> Result<bool> {
574
9689324
        self.skip_ws()?;
575

            
576
9689324
        if self.consume_char(',') {
577
9497320
            self.skip_ws()?;
578

            
579
9497320
            Ok(true)
580
        } else {
581
192004
            Ok(false)
582
        }
583
9689324
    }
584

            
585
    /// Only returns true if the char after `ident` cannot belong
586
    /// to an identifier.
587
212093437
    pub fn check_ident(&mut self, ident: &str) -> bool {
588
212093437
        self.check_str(ident) && !self.check_ident_other_char(ident.len())
589
212093437
    }
590

            
591
322345
    fn check_ident_other_char(&self, index: usize) -> bool {
592
322345
        self.src()[index..]
593
322345
            .chars()
594
322345
            .next()
595
322345
            .map_or(false, is_xid_continue)
596
322345
    }
597

            
598
    /// Check which type of struct we are currently parsing. The parsing state
599
    ///  is only changed in case of an error, to provide a better position.
600
    ///
601
    /// [`NewtypeMode::NoParensMeanUnit`] detects (tuple) structs by a leading
602
    ///  opening bracket and reports a unit struct otherwise.
603
    /// [`NewtypeMode::InsideNewtype`] skips an initial check for unit structs,
604
    ///  and means that any leading opening bracket is not considered to open
605
    ///  a (tuple) struct but to be part of the structs inner contents.
606
    ///
607
    /// [`TupleMode::ImpreciseTupleOrNewtype`] only performs a cheap, O(1),
608
    ///  single-identifier lookahead check to distinguish tuple structs from
609
    ///  non-tuple structs.
610
    /// [`TupleMode::DifferentiateNewtype`] performs an expensive, O(N), look-
611
    ///  ahead over the entire next value tree, which can span the entirety of
612
    ///  the remaining document in the worst case.
613
141778
    pub fn check_struct_type(
614
141778
        &mut self,
615
141778
        newtype: NewtypeMode,
616
141778
        tuple: TupleMode,
617
141778
    ) -> Result<StructType> {
618
141778
        fn check_struct_type_inner(
619
141778
            parser: &mut Parser,
620
141778
            newtype: NewtypeMode,
621
141778
            tuple: TupleMode,
622
141778
        ) -> Result<StructType> {
623
141778
            if matches!(newtype, NewtypeMode::NoParensMeanUnit) && !parser.consume_char('(') {
624
13116
                return Ok(StructType::Unit);
625
128662
            }
626

            
627
128662
            parser.skip_ws()?;
628

            
629
            // Check for `Ident()`, which could be
630
            // - a zero-field struct or tuple (variant)
631
            // - an unwrapped newtype around a unit
632
128658
            if matches!(newtype, NewtypeMode::NoParensMeanUnit) && parser.check_char(')') {
633
894
                return Ok(StructType::EmptyTuple);
634
127764
            }
635

            
636
127764
            if parser.skip_identifier().is_some() {
637
107164
                parser.skip_ws()?;
638

            
639
107164
                match parser.peek_char() {
640
                    // Definitely a struct with named fields
641
43980
                    Some(':') => return Ok(StructType::Named),
642
                    // Definitely a tuple-like struct with fields
643
                    Some(',') => {
644
4478
                        parser.skip_next_char();
645
4478
                        parser.skip_ws()?;
646
4478
                        if parser.check_char(')') {
647
                            // A one-element tuple could be a newtype
648
                            return Ok(StructType::NewtypeTuple);
649
4478
                        }
650
                        // Definitely a tuple struct with more than one field
651
4478
                        return Ok(StructType::NonNewtypeTuple);
652
                    }
653
                    // Either a newtype or a tuple struct
654
1192
                    Some(')') => return Ok(StructType::NewtypeTuple),
655
                    // Something else, let's investigate further
656
57514
                    Some(_) | None => (),
657
                };
658
20600
            }
659

            
660
78114
            if matches!(tuple, TupleMode::ImpreciseTupleOrNewtype) {
661
42935
                return Ok(StructType::AnyTuple);
662
35179
            }
663

            
664
35179
            let mut braces = 1_usize;
665
35179
            let mut more_than_one = false;
666

            
667
            // Skip ahead to see if the value is followed by another value
668
55911997
            while braces > 0 {
669
                // Skip spurious braces in comments, strings, and characters
670
55877429
                parser.skip_ws()?;
671
55877429
                let cursor_backup = parser.cursor;
672
55877429
                if parser.char().is_err() {
673
55877429
                    parser.set_cursor(cursor_backup);
674
55877429
                }
675
55877429
                let cursor_backup = parser.cursor;
676
55877429
                match parser.string() {
677
1192
                    Ok(_) => (),
678
                    // prevent quadratic complexity backtracking for unterminated string
679
                    Err(err @ (Error::ExpectedStringEnd | Error::Eof)) => return Err(err),
680
55876237
                    Err(_) => parser.set_cursor(cursor_backup),
681
                }
682
55877429
                let cursor_backup = parser.cursor;
683
                // we have already checked for strings, which subsume base64 byte strings
684
55877429
                match parser.byte_string_no_base64() {
685
894
                    Ok(_) => (),
686
                    // prevent quadratic complexity backtracking for unterminated byte string
687
                    Err(err @ (Error::ExpectedStringEnd | Error::Eof)) => return Err(err),
688
55876535
                    Err(_) => parser.set_cursor(cursor_backup),
689
                }
690

            
691
55877429
                let c = parser.next_char()?;
692
55877414
                if matches!(c, '(' | '[' | '{') {
693
18630081
                    braces += 1;
694
37247333
                } else if matches!(c, ')' | ']' | '}') {
695
18664649
                    braces -= 1;
696
18664649
                } else if c == ',' && braces == 1 {
697
596
                    parser.skip_ws()?;
698
596
                    more_than_one = !parser.check_char(')');
699
596
                    break;
700
18582088
                }
701
            }
702

            
703
35164
            if more_than_one {
704
298
                Ok(StructType::NonNewtypeTuple)
705
            } else {
706
34866
                Ok(StructType::NewtypeTuple)
707
            }
708
141778
        }
709

            
710
        // Create a temporary working copy
711
141778
        let backup_cursor = self.cursor;
712

            
713
141778
        let result = check_struct_type_inner(self, newtype, tuple);
714

            
715
141778
        if result.is_ok() {
716
141759
            // Revert the parser to before the struct type check
717
141759
            self.set_cursor(backup_cursor);
718
141759
        }
719

            
720
141778
        result
721
141778
    }
722

            
723
    /// Only returns true if the char after `ident` cannot belong
724
    /// to an identifier.
725
202124884
    pub fn consume_ident(&mut self, ident: &str) -> bool {
726
202124884
        if self.check_ident(ident) {
727
171924
            self.advance_bytes(ident.len());
728

            
729
171924
            true
730
        } else {
731
201952960
            false
732
        }
733
202124884
    }
734

            
735
90382
    pub fn consume_struct_name(&mut self, ident: &'static str) -> Result<bool> {
736
90382
        if self.check_ident("") {
737
71865
            if self.exts.contains(Extensions::EXPLICIT_STRUCT_NAMES) {
738
894
                return Err(Error::ExpectedStructName(ident.to_string()));
739
70971
            }
740

            
741
70971
            return Ok(false);
742
18517
        }
743

            
744
18517
        let found_ident = match self.identifier() {
745
16431
            Ok(maybe_ident) => maybe_ident,
746
1490
            Err(Error::SuggestRawIdentifier(found_ident)) if found_ident == ident => {
747
298
                return Err(Error::SuggestRawIdentifier(found_ident))
748
            }
749
1788
            Err(_) => return Err(Error::ExpectedNamedStructLike(ident)),
750
        };
751

            
752
16431
        if ident.is_empty() {
753
328
            return Err(Error::ExpectedNamedStructLike(ident));
754
16103
        }
755

            
756
16103
        if found_ident != ident {
757
1800
            return Err(Error::ExpectedDifferentStructName {
758
1800
                expected: ident,
759
1800
                found: String::from(found_ident),
760
1800
            });
761
14303
        }
762

            
763
14303
        Ok(true)
764
90382
    }
765

            
766
    /// Parse a document attribute at the current cursor position.
767
635766
    fn attribute(&mut self) -> Result<ParsedAttribute> {
768
635766
        if !self.check_char('#') {
769
597462
            return Ok(ParsedAttribute::None);
770
38304
        }
771

            
772
38304
        if !self.consume_all(&["#", "!", "["])? {
773
12
            return Err(Error::ExpectedAttribute);
774
38292
        }
775

            
776
38292
        self.skip_ws()?;
777
38292
        if self.consume_ident("enable") {
778
38256
            self.skip_ws()?;
779
38256
            if !self.consume_str("(") {
780
                return Err(Error::ExpectedAttribute);
781
38256
            }
782

            
783
38256
            self.skip_ws()?;
784
38256
            let extensions = self.extension_list()?;
785
37718
            self.skip_ws()?;
786

            
787
37718
            if self.consume_all(&[")", "]"])? {
788
37703
                Ok(ParsedAttribute::Extensions(extensions))
789
            } else {
790
15
                Err(Error::ExpectedAttributeEnd)
791
            }
792
36
        } else if self.consume_ident("type") || self.consume_ident("schema") {
793
36
            self.skip_ws()?;
794
36
            if !self.consume_str("=") {
795
                return Err(Error::ExpectedAttribute);
796
36
            }
797

            
798
36
            self.skip_ws()?;
799
36
            self.string()?;
800
36
            self.skip_ws()?;
801

            
802
36
            if self.consume_str("]") {
803
36
                Ok(ParsedAttribute::Ignored)
804
            } else {
805
                Err(Error::ExpectedAttributeEnd)
806
            }
807
        } else {
808
            Err(Error::ExpectedAttribute)
809
        }
810
635766
    }
811

            
812
    /// Returns the extensions bit mask.
813
38256
    fn extension_list(&mut self) -> Result<Extensions> {
814
38256
        let mut extensions = Extensions::empty();
815

            
816
        loop {
817
38554
            let ident = self.identifier()?;
818
38554
            let extension = Extensions::from_ident(ident)
819
38554
                .ok_or_else(|| Error::NoSuchExtension(ident.into()))?;
820

            
821
38539
            extensions |= extension;
822

            
823
38539
            let comma = self.comma()?;
824

            
825
            // If we have no comma but another item, return an error
826
38539
            if !comma && self.check_ident_other_char(0) {
827
523
                return Err(Error::ExpectedComma);
828
38016
            }
829

            
830
            // If there's no comma, assume the list ended.
831
            // If there is, it might be a trailing one, thus we only
832
            // continue the loop if we get an ident char.
833
38016
            if !comma || !self.check_ident_other_char(0) {
834
37718
                break;
835
298
            }
836
        }
837

            
838
37718
        Ok(extensions)
839
38256
    }
840

            
841
9255999
    pub fn float<T: Float>(&mut self) -> Result<T> {
842
        const F32_SUFFIX: &str = "f32";
843
        const F64_SUFFIX: &str = "f64";
844

            
845
55533874
        for (literal, value_f32, value_f64) in &[
846
9255999
            ("inf", f32::INFINITY, f64::INFINITY),
847
9255999
            ("+inf", f32::INFINITY, f64::INFINITY),
848
9255999
            ("-inf", f32::NEG_INFINITY, f64::NEG_INFINITY),
849
9255999
            ("NaN", f32::NAN, f64::NAN),
850
9255999
            ("+NaN", f32::NAN, f64::NAN),
851
9255999
            ("-NaN", -f32::NAN, -f64::NAN),
852
9255999
        ] {
853
55533874
            if self.consume_ident(literal) {
854
96
                return T::parse(literal);
855
55533778
            }
856

            
857
55533778
            if let Some(suffix) = self.src().strip_prefix(literal) {
858
1236
                if let Some(post_suffix) = suffix.strip_prefix(F32_SUFFIX) {
859
616
                    if !post_suffix.chars().next().map_or(false, is_xid_continue) {
860
612
                        let float_ron = &self.src()[..literal.len() + F32_SUFFIX.len()];
861
612
                        self.advance_bytes(literal.len() + F32_SUFFIX.len());
862
612
                        return T::try_from_parsed_float(ParsedFloat::F32(*value_f32), float_ron);
863
4
                    }
864
620
                }
865

            
866
624
                if let Some(post_suffix) = suffix.strip_prefix(F64_SUFFIX) {
867
616
                    if !post_suffix.chars().next().map_or(false, is_xid_continue) {
868
612
                        let float_ron = &self.src()[..literal.len() + F64_SUFFIX.len()];
869
612
                        self.advance_bytes(literal.len() + F64_SUFFIX.len());
870
612
                        return T::try_from_parsed_float(ParsedFloat::F64(*value_f64), float_ron);
871
4
                    }
872
8
                }
873
55532542
            }
874
        }
875

            
876
9254679
        let raw_bytes = self.next_chars_while_len(is_float_char);
877
9254679
        let src = &self.src()[..raw_bytes];
878
9254679
        let num_bytes = src.find("..").unwrap_or(raw_bytes);
879

            
880
9254679
        if num_bytes == 0 {
881
46
            return Err(Error::ExpectedFloat);
882
9254633
        }
883

            
884
9254633
        if self.check_char('_') {
885
4
            return Err(Error::UnderscoreAtBeginning);
886
9254629
        }
887

            
888
9254629
        let mut f = String::with_capacity(num_bytes);
889
9254629
        let mut allow_underscore = false;
890

            
891
83416265
        for (i, c) in self.src()[..num_bytes].char_indices() {
892
808
            match c {
893
800
                '_' if allow_underscore => continue,
894
                '_' => {
895
8
                    self.advance_bytes(i);
896
8
                    return Err(Error::FloatUnderscore);
897
                }
898
74161133
                '0'..='9' | 'e' | 'E' => allow_underscore = true,
899
9251965
                '.' => allow_underscore = false,
900
2359
                _ => (),
901
            }
902

            
903
            // we know that the byte is an ASCII character here
904
83415457
            f.push(c);
905
        }
906

            
907
9254621
        if self.src()[num_bytes..].starts_with('f') {
908
2122
            let backup_cursor = self.cursor;
909
2122
            self.advance_bytes(num_bytes);
910

            
911
            #[allow(clippy::never_loop)]
912
            loop {
913
2122
                let res = if self.consume_ident(F32_SUFFIX) {
914
1208
                    f32::from_str(&f).map(ParsedFloat::F32)
915
914
                } else if self.consume_ident(F64_SUFFIX) {
916
612
                    f64::from_str(&f).map(ParsedFloat::F64)
917
                } else {
918
302
                    break;
919
                };
920

            
921
1820
                let parsed = if let Ok(parsed) = res {
922
1812
                    parsed
923
                } else {
924
8
                    self.set_cursor(backup_cursor);
925
8
                    return Err(Error::ExpectedFloat);
926
                };
927

            
928
1812
                let float_ron = &self.src[backup_cursor.cursor..self.cursor.cursor];
929

            
930
1812
                return T::try_from_parsed_float(parsed, float_ron);
931
            }
932

            
933
302
            self.set_cursor(backup_cursor);
934
9252499
        }
935

            
936
9252801
        let value = T::parse(&f)?;
937

            
938
9252781
        self.advance_bytes(num_bytes);
939

            
940
9252781
        Ok(value)
941
9255999
    }
942

            
943
9991575
    pub fn skip_identifier(&mut self) -> Option<&'a str> {
944
        #[allow(clippy::nonminimal_bool)]
945
9991575
        if self.check_str("b\"") // byte string
946
9990077
            || self.check_str("b'") // byte literal
947
9760319
            || self.check_str("br#") // raw byte string
948
9759425
            || self.check_str("br\"") // raw byte string
949
9758531
            || self.check_str("r\"") // raw string
950
9757935
            || self.check_str("r#\"") // raw string
951
9757637
            || self.check_str("r##") // raw string
952
9757339
            || false
953
        {
954
234236
            return None;
955
9757339
        }
956

            
957
9757339
        if self.check_str("r#") {
958
            // maybe a raw identifier
959
12
            let len = self.next_chars_while_from_len(2, is_ident_raw_char);
960
12
            if len > 0 {
961
4
                let ident = &self.src()[2..2 + len];
962
4
                self.advance_bytes(2 + len);
963
4
                return Some(ident);
964
8
            }
965
8
            return None;
966
9757327
        }
967

            
968
9757327
        if let Some(c) = self.peek_char() {
969
            // maybe a normal identifier
970
9755837
            if is_ident_first_char(c) {
971
205229
                let len =
972
205229
                    c.len_utf8() + self.next_chars_while_from_len(c.len_utf8(), is_xid_continue);
973
205229
                let ident = &self.src()[..len];
974
205229
                self.advance_bytes(len);
975
205229
                return Some(ident);
976
9550608
            }
977
1490
        }
978

            
979
9552098
        None
980
9991575
    }
981

            
982
337024
    pub fn identifier(&mut self) -> Result<&'a str> {
983
337024
        let first = self.peek_char_or_eof()?;
984
337024
        if !is_ident_first_char(first) {
985
2396
            if is_ident_raw_char(first) {
986
1192
                let ident_bytes = self.next_chars_while_len(is_ident_raw_char);
987
1192
                return Err(Error::SuggestRawIdentifier(
988
1192
                    self.src()[..ident_bytes].into(),
989
1192
                ));
990
1204
            }
991

            
992
1204
            return Err(Error::ExpectedIdentifier);
993
334628
        }
994

            
995
        // If the next 2-3 bytes signify the start of a (raw) (byte) string
996
        //  literal, return an error.
997
        #[allow(clippy::nonminimal_bool)]
998
334628
        if self.check_str("b\"") // byte string
999
334330
            || self.check_str("b'") // byte literal
334032
            || self.check_str("br#") // raw byte string
333734
            || self.check_str("br\"") // raw byte string
333436
            || self.check_str("r\"") // raw string
333138
            || self.check_str("r#\"") // raw string
332840
            || self.check_str("r##") // raw string
332542
            || false
        {
2086
            return Err(Error::ExpectedIdentifier);
332542
        }
332542
        let length = if self.check_str("r#") {
7776
            let cursor_backup = self.cursor;
7776
            self.advance_bytes(2);
            // Note: it's important to check this before advancing forward, so that
            // the value-type deserializer can fall back to parsing it differently.
7776
            if !matches!(self.peek_char(), Some(c) if is_ident_raw_char(c)) {
596
                self.set_cursor(cursor_backup);
596
                return Err(Error::ExpectedIdentifier);
7180
            }
7180
            self.next_chars_while_len(is_ident_raw_char)
324766
        } else if first == 'r' {
596
            let std_ident_length = self.next_chars_while_len(is_xid_continue);
596
            let raw_ident_length = self.next_chars_while_len(is_ident_raw_char);
596
            if raw_ident_length > std_ident_length {
298
                return Err(Error::SuggestRawIdentifier(
298
                    self.src()[..raw_ident_length].into(),
298
                ));
298
            }
298
            std_ident_length
        } else {
324170
            let std_ident_length = first.len_utf8()
324170
                + self.next_chars_while_from_len(first.len_utf8(), is_xid_continue);
324170
            let raw_ident_length = self.next_chars_while_len(is_ident_raw_char);
324170
            if raw_ident_length > std_ident_length {
894
                return Err(Error::SuggestRawIdentifier(
894
                    self.src()[..raw_ident_length].into(),
894
                ));
323276
            }
323276
            std_ident_length
        };
330754
        let ident = &self.src()[..length];
330754
        self.advance_bytes(length);
330754
        Ok(ident)
337024
    }
9576003
    pub fn next_bytes_is_float(&mut self) -> bool {
9576003
        if let Some(c) = self.peek_char() {
9575999
            let skip = match c {
5446
                '+' | '-' => 1,
9570553
                _ => 0,
            };
9575999
            let raw_float_len = self.next_chars_while_from_len(skip, is_float_char);
            // Trim at ".." to avoid treating range operators as float chars.
            //
            // Only search within the float-char run: the result is clamped to
            // `raw_float_len` anyway, so a match at or beyond it cannot change the
            // outcome. Searching the whole remaining input made this O(remaining)
            // per number, i.e. quadratic in the number count for documents that
            // contain no ".." at all (every number then scanned to EOF).
            //
            // A ".." cannot straddle the end of the run: that would require
            // `src[raw_float_len] == '.'`, but '.' is a float char and would have
            // been part of the run. `any_number` above already uses this same
            // bounded-slice form.
9575999
            let valid_float_len = self.src()[skip..][..raw_float_len]
9575999
                .find("..")
9575999
                .map_or(raw_float_len, |i| i.min(raw_float_len));
9575999
            let valid_int_len = self.next_chars_while_from_len(skip, is_int_char);
9575999
            valid_float_len > valid_int_len
        } else {
4
            false
        }
9576003
    }
87791721
    pub fn skip_ws(&mut self) -> Result<()> {
87791721
        if (self.cursor.last_ws_len != WS_CURSOR_UNCLOSED_LINE)
87791121
            && ((self.cursor.pre_ws_cursor + self.cursor.last_ws_len) < self.cursor.cursor)
77056057
        {
77056057
            // the last whitespace is disjoint from this one, we need to track a new one
77056057
            self.cursor.pre_ws_cursor = self.cursor.cursor;
77056057
        }
87791721
        if self.src().is_empty() {
482328
            return Ok(());
87309393
        }
        loop {
87339498
            self.advance_bytes(self.next_chars_while_len(is_whitespace_char));
87339498
            match self.skip_comment()? {
87307299
                None => break,
                Some(Comment::UnclosedLine) => {
1196
                    self.cursor.last_ws_len = WS_CURSOR_UNCLOSED_LINE;
1196
                    return Ok(());
                }
30105
                Some(Comment::ClosedLine | Comment::Block) => continue,
            }
        }
87307299
        self.cursor.last_ws_len = self.cursor.cursor - self.cursor.pre_ws_cursor;
87307299
        Ok(())
87791721
    }
19072
    pub fn has_unclosed_line_comment(&self) -> bool {
19072
        self.src().is_empty() && self.cursor.last_ws_len == WS_CURSOR_UNCLOSED_LINE
19072
    }
10180
    pub fn byte_string(&mut self) -> Result<ParsedByteStr<'a>> {
16
        fn expected_byte_string_found_base64(
16
            base64_str: &ParsedStr,
16
            byte_str: &ParsedByteStr,
16
        ) -> Error {
16
            let byte_str = match &byte_str {
16
                ParsedByteStr::Allocated(b) => b.as_slice(),
                ParsedByteStr::Slice(b) => b,
            }
16
            .iter()
120
            .flat_map(|c| core::ascii::escape_default(*c))
16
            .map(char::from)
16
            .collect::<String>();
16
            let base64_str = match &base64_str {
                ParsedStr::Allocated(s) => s.as_str(),
16
                ParsedStr::Slice(s) => s,
            };
16
            Error::InvalidValueForType {
16
                expected: format!("the Rusty byte string b\"{}\"", byte_str),
16
                found: format!("the ambiguous base64 string {:?}", base64_str),
16
            }
16
        }
        // FIXME @juntyr: remove in v0.13, since only byte_string_no_base64 will
        //                be used
10180
        if self.consume_char('"') {
8
            let base64_str = self.escaped_string()?;
8
            let base64_result = ParsedByteStr::try_from_base64(&base64_str);
8
            match base64_result {
8
                Some(byte_str) => Err(expected_byte_string_found_base64(&base64_str, &byte_str)),
                None => Err(Error::ExpectedByteString),
            }
10172
        } else if self.consume_char('r') {
12
            let base64_str = self.raw_string()?;
12
            let base64_result = ParsedByteStr::try_from_base64(&base64_str);
12
            match base64_result {
8
                Some(byte_str) => Err(expected_byte_string_found_base64(&base64_str, &byte_str)),
4
                None => Err(Error::ExpectedByteString),
            }
        } else {
10160
            self.byte_string_no_base64()
        }
10180
    }
55887589
    pub fn byte_string_no_base64(&mut self) -> Result<ParsedByteStr<'a>> {
55887589
        if self.consume_str("b\"") {
6882
            self.escaped_byte_string()
55880707
        } else if self.consume_str("br") {
4172
            self.raw_byte_string()
        } else {
55876535
            Err(Error::ExpectedByteString)
        }
55887589
    }
6882
    fn escaped_byte_string(&mut self) -> Result<ParsedByteStr<'a>> {
6882
        match self.escaped_byte_buf(EscapeEncoding::Binary) {
6286
            Ok((bytes, advance)) => {
6286
                self.advance_bytes(advance);
6286
                Ok(bytes)
            }
596
            Err(err) => Err(err),
        }
6882
    }
4172
    fn raw_byte_string(&mut self) -> Result<ParsedByteStr<'a>> {
4172
        match self.raw_byte_buf() {
3576
            Ok((bytes, advance)) => {
3576
                self.advance_bytes(advance);
3576
                Ok(bytes)
            }
298
            Err(Error::ExpectedString) => Err(Error::ExpectedByteString),
298
            Err(err) => Err(err),
        }
4172
    }
55978558
    pub fn string(&mut self) -> Result<ParsedStr<'a>> {
55978558
        if self.consume_char('"') {
96893
            self.escaped_string()
55881665
        } else if self.consume_char('r') {
3628
            self.raw_string()
        } else {
55878037
            Err(Error::ExpectedString)
        }
55978558
    }
96901
    fn escaped_string(&mut self) -> Result<ParsedStr<'a>> {
96901
        match self.escaped_byte_buf(EscapeEncoding::Utf8) {
94204
            Ok((bytes, advance)) => {
94204
                let string = ParsedStr::try_from_bytes(bytes).map_err(Error::from)?;
94204
                self.advance_bytes(advance);
94204
                Ok(string)
            }
2697
            Err(err) => Err(err),
        }
96901
    }
3640
    fn raw_string(&mut self) -> Result<ParsedStr<'a>> {
3640
        match self.raw_byte_buf() {
3040
            Ok((bytes, advance)) => {
3040
                let string = ParsedStr::try_from_bytes(bytes).map_err(Error::from)?;
3040
                self.advance_bytes(advance);
3040
                Ok(string)
            }
600
            Err(err) => Err(err),
        }
3640
    }
103783
    fn escaped_byte_buf(&mut self, encoding: EscapeEncoding) -> Result<(ParsedByteStr<'a>, usize)> {
        // Checking for '"' and '\\' separately is faster than searching for both at the same time
103783
        let str_end = self.src().find('"').ok_or(Error::ExpectedStringEnd)?;
102874
        let escape = self.src()[..str_end].find('\\');
102874
        if let Some(escape) = escape {
            // Now check if escaping is used inside the string
16728
            let mut i = escape;
16728
            let mut s = self.src().as_bytes()[..i].to_vec();
            loop {
46220516
                self.advance_bytes(i + 1);
46220516
                if !self.consume_string_continuation() {
46218132
                    match self.parse_escape(encoding, false)? {
46203522
                        EscapeCharacter::Ascii(c) => s.push(c),
12226
                        EscapeCharacter::Utf8(c) => match c.len_utf8() {
11622
                            1 => s.push(c as u8),
604
                            len => {
604
                                let start = s.len();
604
                                s.extend(core::iter::repeat(0).take(len));
604
                                c.encode_utf8(&mut s[start..]);
604
                            }
                        },
                    }
2384
                }
                // Unlike the non-escaped case above, searching for '"' and '\\'
                // separately is *not* sound here: `find('"')` scans all the way to
                // the closing quote, but the cursor only advances by one escape per
                // iteration, so a string with N escapes rescans the tail N times.
                // Only the first of '"' / '\\' is needed, and scanning just to the
                // nearest delimiter keeps the loop linear.
46218132
                let next = self
46218132
                    .src()
46218132
                    .find(['"', '\\'])
46218132
                    .ok_or(Error::ExpectedStringEnd)?;
46218132
                s.extend_from_slice(&self.src().as_bytes()[..next]);
                // `next` indexes an ASCII byte, so byte indexing is valid here.
46218132
                if self.src().as_bytes()[next] == b'\\' {
46203788
                    i = next;
46203788
                } else {
                    // Advance to the end of the string + 1 for the `"`.
14344
                    break Ok((ParsedByteStr::Allocated(s), next + 1));
                }
            }
        } else {
86146
            let s = &self.src().as_bytes()[..str_end];
            // Advance by the number of bytes of the string + 1 for the `"`.
86146
            Ok((ParsedByteStr::Slice(s), str_end + 1))
        }
103783
    }
    /// Consumes a string continuation after its leading `\`.
    ///
    /// Rust [normalizes CRLF before lexing](https://doc.rust-lang.org/reference/input-format.html#crlf-normalization),
    /// so RON accepts CRLF directly too.
46220516
    fn consume_string_continuation(&mut self) -> bool {
46220516
        let line_ending_len = if self.check_str("\r\n") {
596
            2
46219920
        } else if self.check_char('\n') {
1788
            1
        } else {
46218132
            return false;
        };
2384
        self.advance_bytes(line_ending_len);
2384
        let whitespace = self.next_chars_while_len(is_string_continuation_whitespace);
2384
        self.advance_bytes(whitespace);
2384
        true
46220516
    }
7812
    fn raw_byte_buf(&mut self) -> Result<(ParsedByteStr<'a>, usize)> {
15016
        let num_hashes = self.next_chars_while_len(|c| c == '#');
7812
        let hashes = &self.src()[..num_hashes];
7812
        self.advance_bytes(num_hashes);
7812
        self.expect_char('"', Error::ExpectedString)?;
7212
        let ending = ["\"", hashes].concat();
7212
        let i = self.src().find(&ending).ok_or(Error::ExpectedStringEnd)?;
6616
        let s = &self.src().as_bytes()[..i];
        // Advance by the number of bytes of the byte string
        // + `num_hashes` + 1 for the `"`.
6616
        Ok((ParsedByteStr::Slice(s), i + num_hashes + 1))
7812
    }
210810
    fn decode_ascii_escape(&mut self) -> Result<u8> {
210810
        let mut n = 0;
210810
        for _ in 0..2 {
421620
            n <<= 4;
421620
            let byte = self.next_char()?;
421620
            let decoded = Self::decode_hex(byte)?;
421024
            n |= decoded;
        }
210214
        Ok(n)
210810
    }
    #[inline]
1030539
    fn decode_hex(c: char) -> Result<u8> {
1030539
        if !c.is_ascii() {
298
            return Err(Error::InvalidEscape("Non-hex digit found"));
1030241
        }
        // c is an ASCII character that can be losslessly cast to u8
1030241
        match c as u8 {
1029943
            c @ b'0'..=b'9' => Ok(c - b'0'),
118072
            c @ b'a'..=b'f' => Ok(10 + c - b'a'),
60792
            c @ b'A'..=b'F' => Ok(10 + c - b'A'),
298
            _ => Err(Error::InvalidEscape("Non-hex digit found")),
        }
1030539
    }
46425552
    fn parse_escape(&mut self, encoding: EscapeEncoding, is_char: bool) -> Result<EscapeCharacter> {
46425552
        let c = match self.next_char()? {
906
            '\'' => EscapeCharacter::Ascii(b'\''),
3898
            '"' => EscapeCharacter::Ascii(b'"'),
2980
            '\\' => EscapeCharacter::Ascii(b'\\'),
46193278
            'n' => EscapeCharacter::Ascii(b'\n'),
596
            'r' => EscapeCharacter::Ascii(b'\r'),
596
            't' => EscapeCharacter::Ascii(b'\t'),
1788
            '0' => EscapeCharacter::Ascii(b'\0'),
            'x' => {
                // Fast exit for ascii escape in byte string
207504
                let b: u8 = self.decode_ascii_escape()?;
206908
                if let EscapeEncoding::Binary = encoding {
203920
                    return Ok(EscapeCharacter::Ascii(b));
2988
                }
                // Fast exit for ascii character in UTF-8 string
2988
                let mut bytes = [b, 0, 0, 0];
2988
                if let Ok(Some(c)) = from_utf8(&bytes[..=0]).map(|s| s.chars().next()) {
894
                    return Ok(EscapeCharacter::Utf8(c));
2094
                }
2094
                if is_char {
                    // Character literals are not allowed to use multiple byte
                    //  escapes to build a unicode character
298
                    return Err(Error::InvalidEscape(
298
                        "Not a valid byte-escaped Unicode character",
298
                    ));
1796
                }
                // UTF-8 character needs up to four bytes and we have already
                //  consumed one, so at most three to go
4494
                for i in 1..4 {
4494
                    if !self.consume_str(r"\x") {
1192
                        return Err(Error::InvalidEscape(
1192
                            "Not a valid byte-escaped Unicode character",
1192
                        ));
3302
                    }
3302
                    bytes[i] = self.decode_ascii_escape()?;
                    // Check if we now have a valid UTF-8 character
3302
                    if let Ok(Some(c)) = from_utf8(&bytes[..=i]).map(|s| s.chars().next()) {
306
                        return Ok(EscapeCharacter::Utf8(c));
2996
                    }
                }
298
                return Err(Error::InvalidEscape(
298
                    "Not a valid byte-escaped Unicode character",
298
                ));
            }
            'u' => {
12814
                self.expect_char('{', Error::InvalidEscape("Missing { in Unicode escape"))?;
12814
                let mut bytes: u32 = 0;
12814
                let mut num_digits = 0;
34270
                while num_digits < 6 {
34270
                    let byte = self.peek_char_or_eof()?;
34270
                    if byte == '}' {
12814
                        break;
21456
                    }
21456
                    self.skip_next_char();
21456
                    num_digits += 1;
21456
                    let byte = Self::decode_hex(byte)?;
21456
                    bytes <<= 4;
21456
                    bytes |= u32::from(byte);
                }
12814
                if num_digits == 0 {
298
                    return Err(Error::InvalidEscape(
298
                        "Expected 1-6 digits, got 0 digits in Unicode escape",
298
                    ));
12516
                }
12516
                self.expect_char(
                    '}',
12516
                    Error::InvalidEscape("No } at the end of Unicode escape"),
                )?;
12516
                let c = char_from_u32(bytes).ok_or(Error::InvalidEscape(
12516
                    "Not a valid Unicode-escaped character",
12516
                ))?;
12516
                EscapeCharacter::Utf8(c)
            }
1192
            _ => return Err(Error::InvalidEscape("Unknown escape character")),
        };
46216558
        Ok(c)
46425552
    }
87339498
    fn skip_comment(&mut self) -> Result<Option<Comment>> {
87339498
        if self.consume_char('/') {
32199
            match self.next_char()? {
                '/' => {
132726
                    let bytes = self.next_chars_while_len(|c| c != '\n');
8943
                    self.advance_bytes(bytes);
8943
                    if self.src().is_empty() {
1196
                        Ok(Some(Comment::UnclosedLine))
                    } else {
7747
                        Ok(Some(Comment::ClosedLine))
                    }
                }
                '*' => {
22958
                    let mut level = 1;
53064
                    while level > 0 {
208334
                        let bytes = self.next_chars_while_len(|c| !matches!(c, '/' | '*'));
30706
                        if self.src().is_empty() {
302
                            return Err(Error::UnclosedBlockComment);
30404
                        }
30404
                        self.advance_bytes(bytes);
                        // check whether / or * and take action
30404
                        if self.consume_str("/*") {
2086
                            level += 1;
28318
                        } else if self.consume_str("*/") {
24444
                            level -= 1;
24444
                        } else {
3874
                            self.next_char().map_err(|_| Error::UnclosedBlockComment)?;
                        }
                    }
22358
                    Ok(Some(Comment::Block))
                }
298
                c => Err(Error::UnexpectedChar(c)),
            }
        } else {
87307299
            Ok(None)
        }
87339498
    }
}
enum Comment {
    ClosedLine,
    UnclosedLine,
    Block,
}
pub trait Num {
    fn from_u8(x: u8) -> Self;
    /// Returns `true` on overflow
    fn checked_mul_ext(&mut self, x: u8) -> bool;
    /// Returns `true` on overflow
    fn checked_add_ext(&mut self, x: u8) -> bool;
    /// Returns `true` on overflow
    fn checked_sub_ext(&mut self, x: u8) -> bool;
}
macro_rules! impl_num {
    ($ty:ty) => {
        impl Num for $ty {
1417182
            fn from_u8(x: u8) -> Self {
78094
                x as $ty
1417182
            }
588365
            fn checked_mul_ext(&mut self, x: u8) -> bool {
588365
                match self.checked_mul(Self::from_u8(x)) {
587463
                    Some(n) => {
587463
                        *self = n;
587463
                        false
                    }
902
                    None => true,
                }
588365
            }
485383
            fn checked_add_ext(&mut self, x: u8) -> bool {
485383
                match self.checked_add(Self::from_u8(x)) {
484936
                    Some(n) => {
484936
                        *self = n;
484936
                        false
                    }
447
                    None => true,
                }
485383
            }
99994
            fn checked_sub_ext(&mut self, x: u8) -> bool {
99994
                match self.checked_sub(Self::from_u8(x)) {
97014
                    Some(n) => {
97014
                        *self = n;
97014
                        false
                    }
2980
                    None => true,
                }
99994
            }
        }
    };
    ($($tys:ty)*) => {
        $( impl_num!($tys); )*
    };
}
impl_num! { i8 i16 i32 i64 u8 u16 u32 u64 }
#[cfg(feature = "integer128")]
impl_num! { i128 u128 }
pub trait Integer: Sized {
    fn parse(parser: &mut Parser, sign: i8, base: u8) -> Result<Self>;
    fn try_from_parsed_integer(parsed: ParsedInteger, ron: &str) -> Result<Self>;
}
macro_rules! impl_integer {
    ($wrap:ident($ty:ty)) => {
        impl Integer for $ty {
119952
            fn parse(parser: &mut Parser, sign: i8, base: u8) -> Result<Self> {
119952
                parser.parse_integer(sign, base)
119952
            }
35462
            fn try_from_parsed_integer(parsed: ParsedInteger, ron: &str) -> Result<Self> {
35462
                match parsed {
13112
                    ParsedInteger::$wrap(v) => Ok(v),
                    _ => Err(Error::InvalidValueForType {
22350
                        expected: format!(
                            "a{} {}-bit {}signed integer",
22350
                            if <$ty>::BITS == 8 { "n" } else { "n" },
                            <$ty>::BITS,
22350
                            if <$ty>::MIN == 0 { "un" } else { "" },
                        ),
22350
                        found: String::from(ron),
                    }),
                }
35462
            }
        }
    };
    ($($wraps:ident($tys:ty))*) => {
        $( impl_integer!($wraps($tys)); )*
    };
}
impl_integer! {
    I8(i8) I16(i16) I32(i32) I64(i64)
    U8(u8) U16(u16) U32(u32) U64(u64)
}
#[cfg(feature = "integer128")]
impl_integer! { I128(i128) U128(u128) }
pub enum ParsedInteger {
    I8(i8),
    I16(i16),
    I32(i32),
    I64(i64),
    #[cfg(feature = "integer128")]
    I128(i128),
    U8(u8),
    U16(u16),
    U32(u32),
    U64(u64),
    #[cfg(feature = "integer128")]
    U128(u128),
}
impl Integer for ParsedInteger {
86862
    fn parse(parser: &mut Parser, sign: i8, base: u8) -> Result<Self> {
86862
        if sign < 0 {
2136
            let signed = parser.parse_integer::<LargeSInt>(-1, base)?;
622
            return if let Ok(x) = i8::try_from(signed) {
310
                Ok(ParsedInteger::I8(x))
312
            } else if let Ok(x) = i16::try_from(signed) {
4
                Ok(ParsedInteger::I16(x))
308
            } else if let Ok(x) = i32::try_from(signed) {
4
                Ok(ParsedInteger::I32(x))
            } else {
                #[cfg(not(feature = "integer128"))]
                {
2
                    Ok(ParsedInteger::I64(signed))
                }
                #[cfg(feature = "integer128")]
302
                if let Ok(x) = i64::try_from(signed) {
2
                    Ok(ParsedInteger::I64(x))
                } else {
300
                    Ok(ParsedInteger::I128(signed))
                }
            };
84726
        }
84726
        let unsigned = parser.parse_integer::<LargeUInt>(1, base)?;
83969
        if let Ok(x) = u8::try_from(unsigned) {
83057
            Ok(ParsedInteger::U8(x))
912
        } else if let Ok(x) = u16::try_from(unsigned) {
306
            Ok(ParsedInteger::U16(x))
606
        } else if let Ok(x) = u32::try_from(unsigned) {
4
            Ok(ParsedInteger::U32(x))
        } else {
            #[cfg(not(feature = "integer128"))]
            {
2
                Ok(ParsedInteger::U64(unsigned))
            }
            #[cfg(feature = "integer128")]
600
            if let Ok(x) = u64::try_from(unsigned) {
2
                Ok(ParsedInteger::U64(x))
            } else {
598
                Ok(ParsedInteger::U128(unsigned))
            }
        }
86862
    }
236314
    fn try_from_parsed_integer(parsed: ParsedInteger, _ron: &str) -> Result<Self> {
236314
        Ok(parsed)
236314
    }
}
pub trait Float: Sized {
    fn parse(float: &str) -> Result<Self>;
    fn try_from_parsed_float(parsed: ParsedFloat, ron: &str) -> Result<Self>;
}
macro_rules! impl_float {
    ($wrap:ident($ty:ty: $bits:expr)) => {
        impl Float for $ty {
37827
            fn parse(float: &str) -> Result<Self> {
37827
                <$ty>::from_str(float).map_err(|_| Error::ExpectedFloat)
37827
            }
4172
            fn try_from_parsed_float(parsed: ParsedFloat, ron: &str) -> Result<Self> {
4172
                match parsed {
3576
                    ParsedFloat::$wrap(v) => Ok(v),
596
                    _ => Err(Error::InvalidValueForType {
596
                        expected: format!(
596
                            "a {}-bit floating point number", $bits,
596
                        ),
596
                        found: String::from(ron),
596
                    }),
                }
4172
            }
        }
    };
    ($($wraps:ident($tys:ty: $bits:expr))*) => {
        $( impl_float!($wraps($tys: $bits)); )*
    };
}
impl_float! { F32(f32: 32) F64(f64: 64) }
pub enum ParsedFloat {
    F32(f32),
    F64(f64),
}
impl Float for ParsedFloat {
9252114
    fn parse(float: &str) -> Result<Self> {
9252114
        let value = f64::from_str(float).map_err(|_| Error::ExpectedFloat)?;
        // Casting a NaN with `as` gives an unspecified NaN, and some targets
        // (e.g. riscv64) drop the sign, so build the f32 NaN by hand.
9252114
        if value.is_nan() {
12
            let nan = if value.is_sign_negative() {
8
                -f32::NAN
            } else {
4
                f32::NAN
            };
12
            return Ok(ParsedFloat::F32(nan));
9252102
        }
        #[allow(clippy::cast_possible_truncation)]
9252102
        if value.total_cmp(&f64::from(value as f32)).is_eq() {
6620
            Ok(ParsedFloat::F32(value as f32))
        } else {
9245482
            Ok(ParsedFloat::F64(value))
        }
9252114
    }
2980
    fn try_from_parsed_float(parsed: ParsedFloat, _ron: &str) -> Result<Self> {
2980
        Ok(parsed)
2980
    }
}
pub enum StructType {
    AnyTuple,
    EmptyTuple,
    NewtypeTuple,
    NonNewtypeTuple,
    Named,
    Unit,
}
#[derive(Copy, Clone)] // GRCOV_EXCL_LINE
pub enum NewtypeMode {
    NoParensMeanUnit,
    InsideNewtype,
}
#[derive(Copy, Clone)] // GRCOV_EXCL_LINE
pub enum TupleMode {
    ImpreciseTupleOrNewtype,
    DifferentiateNewtype,
}
pub enum ParsedStr<'a> {
    Allocated(String),
    Slice(&'a str),
}
pub enum ParsedByteStr<'a> {
    Allocated(Vec<u8>),
    Slice(&'a [u8]),
}
impl<'a> ParsedStr<'a> {
97244
    pub fn try_from_bytes(bytes: ParsedByteStr<'a>) -> Result<Self, Utf8Error> {
97244
        match bytes {
10748
            ParsedByteStr::Allocated(byte_buf) => Ok(ParsedStr::Allocated(
10748
                String::from_utf8(byte_buf).map_err(|e| e.utf8_error())?,
            )),
86496
            ParsedByteStr::Slice(bytes) => Ok(ParsedStr::Slice(from_utf8(bytes)?)),
        }
97244
    }
}
impl<'a> ParsedByteStr<'a> {
20
    pub fn try_from_base64(str: &ParsedStr<'a>) -> Option<Self> {
        // Adapted from MIT licensed Jenin Sutradhar's base 64 decoder
        // https://github.com/JeninSutradhar/base64-Rust-Encoder-Decoder/blob/ee1fb08cbb78024ec8cf5e786815acb239169f02/src/lib.rs#L84-L128
20
        fn try_decode_base64(str: &str) -> Option<Vec<u8>> {
            const CHARSET: &[u8; 64] =
                b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
            const PADDING: u8 = b'=';
            // fast reject for missing padding
20
            if (str.len() % 4) != 0 {
4
                return None;
16
            }
16
            let bstr_no_padding = str.trim_end_matches(char::from(PADDING)).as_bytes();
            // fast reject for excessive padding
16
            if (str.len() - bstr_no_padding.len()) > 2 {
                return None;
16
            }
            // fast reject for extraneous bytes after padding
16
            if bstr_no_padding.contains(&PADDING) {
                return None;
16
            }
            // fast reject for non-ASCII
16
            if !str.is_ascii() {
                return None;
16
            }
16
            let mut collected_bits = 0_u8;
16
            let mut byte_buffer = 0_u16;
16
            let mut bytes = bstr_no_padding.iter().copied();
16
            let mut binary = Vec::new();
            'decodeloop: loop {
304
                while collected_bits < 8 {
184
                    if let Some(nextbyte) = bytes.next() {
                        #[allow(clippy::cast_possible_truncation)]
5424
                        if let Some(idx) = CHARSET.iter().position(|&x| x == nextbyte) {
168
                            byte_buffer |= ((idx & 0b0011_1111) as u16) << (10 - collected_bits);
168
                            collected_bits += 6;
168
                        } else {
                            return None;
                        }
                    } else {
16
                        break 'decodeloop;
                    }
                }
120
                binary.push(((0b1111_1111_0000_0000 & byte_buffer) >> 8) as u8);
120
                byte_buffer &= 0b0000_0000_1111_1111;
120
                byte_buffer <<= 8;
120
                collected_bits -= 8;
            }
16
            if usize::from(collected_bits) != ((str.len() - bstr_no_padding.len()) * 2) {
                return None;
16
            }
16
            Some(binary)
20
        }
20
        let base64_str = match str {
            ParsedStr::Allocated(string) => string.as_str(),
20
            ParsedStr::Slice(str) => str,
        };
20
        try_decode_base64(base64_str).map(ParsedByteStr::Allocated)
20
    }
}
#[derive(Copy, Clone)] // GRCOV_EXCL_LINE
enum EscapeEncoding {
    Binary,
    Utf8,
}
enum EscapeCharacter {
    Ascii(u8),
    Utf8(char),
}
#[cfg(test)]
mod tests {
    use super::*;
    #[test]
4
    fn decode_x10() {
4
        let mut bytes = Parser::new("10").unwrap();
4
        assert_eq!(bytes.decode_ascii_escape(), Ok(b'\x10'));
4
    }
    #[test]
4
    fn track_prior_ws() {
        const SOURCE: &str = "   /*hey*/ 42       /*bye*/ 24  ";
4
        let mut bytes = Parser::new(SOURCE).unwrap();
4
        assert_eq!(bytes.src(), "42       /*bye*/ 24  ");
4
        assert_eq!(bytes.pre_ws_src(), SOURCE);
4
        bytes.skip_ws().unwrap();
4
        assert_eq!(bytes.src(), "42       /*bye*/ 24  ");
4
        assert_eq!(bytes.pre_ws_src(), SOURCE);
4
        assert_eq!(bytes.integer::<u8>().unwrap(), 42);
4
        assert_eq!(bytes.src(), "       /*bye*/ 24  ");
4
        assert_eq!(bytes.pre_ws_src(), SOURCE);
4
        bytes.skip_ws().unwrap();
4
        bytes.skip_ws().unwrap();
4
        assert_eq!(bytes.src(), "24  ");
4
        assert_eq!(bytes.pre_ws_src(), "       /*bye*/ 24  ");
4
        let mut bytes = Parser::new("42").unwrap();
4
        bytes.skip_ws().unwrap();
4
        bytes.skip_ws().unwrap();
4
        assert_eq!(bytes.src(), "42");
4
        assert_eq!(bytes.pre_ws_src(), "42");
4
        assert_eq!(bytes.integer::<u8>().unwrap(), 42);
4
        bytes.skip_ws().unwrap();
4
        bytes.skip_ws().unwrap();
4
        assert_eq!(bytes.src(), "");
4
        assert_eq!(bytes.pre_ws_src(), "");
4
        let mut bytes = Parser::new("  42  ").unwrap();
4
        bytes.skip_ws().unwrap();
4
        bytes.skip_ws().unwrap();
4
        assert_eq!(bytes.src(), "42  ");
4
        assert_eq!(bytes.pre_ws_src(), "  42  ");
4
        assert_eq!(bytes.integer::<u8>().unwrap(), 42);
4
        bytes.skip_ws().unwrap();
4
        bytes.skip_ws().unwrap();
4
        assert_eq!(bytes.src(), "");
4
        assert_eq!(bytes.pre_ws_src(), "  ");
4
        let mut bytes = Parser::new("  42  //").unwrap();
4
        bytes.skip_ws().unwrap();
4
        bytes.skip_ws().unwrap();
4
        assert_eq!(bytes.src(), "42  //");
4
        assert_eq!(bytes.pre_ws_src(), "  42  //");
4
        assert_eq!(bytes.integer::<u8>().unwrap(), 42);
4
        bytes.skip_ws().unwrap();
4
        bytes.skip_ws().unwrap();
4
        assert_eq!(bytes.src(), "");
4
        assert_eq!(bytes.pre_ws_src(), "  //");
4
    }
    #[test]
4
    fn parser_cursor_eq_cmp() {
4
        assert!(
4
            ParserCursor {
4
                cursor: 42,
4
                pre_ws_cursor: 42,
4
                last_ws_len: 42
4
            } == ParserCursor {
4
                cursor: 42,
4
                pre_ws_cursor: 24,
4
                last_ws_len: 24
4
            }
        );
4
        assert!(
4
            ParserCursor {
4
                cursor: 42,
4
                pre_ws_cursor: 42,
4
                last_ws_len: 42
4
            } != ParserCursor {
4
                cursor: 24,
4
                pre_ws_cursor: 42,
4
                last_ws_len: 42
4
            }
        );
4
        assert!(
4
            ParserCursor {
4
                cursor: 42,
4
                pre_ws_cursor: 42,
4
                last_ws_len: 42
4
            } < ParserCursor {
4
                cursor: 43,
4
                pre_ws_cursor: 24,
4
                last_ws_len: 24
4
            }
        );
4
        assert!(
4
            ParserCursor {
4
                cursor: 42,
4
                pre_ws_cursor: 42,
4
                last_ws_len: 42
4
            } > ParserCursor {
4
                cursor: 41,
4
                pre_ws_cursor: 24,
4
                last_ws_len: 24
4
            }
        );
4
    }
    #[test]
4
    fn empty_src_is_not_a_float() {
4
        assert!(!Parser::new("").unwrap().next_bytes_is_float());
4
    }
    #[test]
4
    fn base64_deprecation_error() {
4
        let err = crate::from_str::<bytes::Bytes>("\"SGVsbG8gcm9uIQ==\"").unwrap_err();
4
        assert_eq!(
            err,
4
            SpannedError {
4
                code: Error::InvalidValueForType {
4
                    expected: String::from("the Rusty byte string b\"Hello ron!\""),
4
                    found: String::from("the ambiguous base64 string \"SGVsbG8gcm9uIQ==\"")
4
                },
4
                span: Span {
4
                    start: Position { line: 1, col: 2 },
4
                    end: Position { line: 1, col: 19 },
4
                }
4
            }
        );
4
        let err = crate::from_str::<bytes::Bytes>("r\"SGVsbG8gcm9uIQ==\"").unwrap_err();
4
        assert_eq!(format!("{}", err.code), "Expected the Rusty byte string b\"Hello ron!\" but found the ambiguous base64 string \"SGVsbG8gcm9uIQ==\" instead");
4
        assert_eq!(
4
            crate::from_str::<bytes::Bytes>("\"invalid=\"").unwrap_err(),
4
            SpannedError {
4
                code: Error::InvalidValueForType {
4
                    expected: String::from("the Rusty byte string b\"\\x8a{\\xda\\x96\\'\""),
4
                    found: String::from("the ambiguous base64 string \"invalid=\"")
4
                },
4
                span: Span {
4
                    start: Position { line: 1, col: 2 },
4
                    end: Position { line: 1, col: 11 },
4
                }
4
            }
        );
4
        assert_eq!(
4
            crate::from_str::<bytes::Bytes>("r\"invalid=\"").unwrap_err(),
4
            SpannedError {
4
                code: Error::InvalidValueForType {
4
                    expected: String::from("the Rusty byte string b\"\\x8a{\\xda\\x96\\'\""),
4
                    found: String::from("the ambiguous base64 string \"invalid=\"")
4
                },
4
                span: Span {
4
                    start: Position { line: 1, col: 3 },
4
                    end: Position { line: 1, col: 12 },
4
                }
4
            }
        );
4
        assert_eq!(
4
            crate::from_str::<bytes::Bytes>("r\"invalid\"").unwrap_err(),
            SpannedError {
                code: Error::ExpectedByteString,
                span: Span {
                    start: Position { line: 1, col: 3 },
                    end: Position { line: 1, col: 11 },
                }
            }
        );
4
    }
}