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
48236763
const fn is_int_char(c: char) -> bool {
22
48236763
    c.is_ascii_hexdigit() || c == '_'
23
48236763
}
24

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

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

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

            
37
33139496
pub const fn is_whitespace_char(c: char) -> bool {
38
30780560
    matches!(
39
33139496
        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
33139496
}
52

            
53
8820
const fn is_string_continuation_whitespace(c: char) -> bool {
54
8820
    matches!(c, ' ' | '\t' | '\n' | '\r')
55
8820
}
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
3572
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
97
3572
        self.cursor.partial_cmp(&other.cursor)
98
3572
    }
99
}
100

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

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

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

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

            
134
587404
        Ok(parser)
135
588256
    }
136

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

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

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

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

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

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

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

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

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

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

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

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

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

            
198
529663
            true
199
        } else {
200
29306395
            false
201
        }
202
29836058
    }
203

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

            
208
10726704
            true
209
        } else {
210
31063066
            false
211
        }
212
41789770
    }
213

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

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

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

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

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

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

            
259
589164
        for (i, c) in s.char_indices() {
260
589164
            if c == '_' {
261
9846
                continue;
262
579318
            }
263

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

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

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

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

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

            
284
232674
        Ok(num_acc)
285
239003
    }
286

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

            
290
246675
        if num_bytes == 0 {
291
4732
            return Err(Error::ExpectedInteger);
292
241943
        }
293

            
294
241943
        if self.check_char('_') {
295
2940
            return Err(Error::UnderscoreAtBeginning);
296
239003
        }
297

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

            
300
239003
        if sign > 0 {
301
221223
            self.parse_integer_digits(s, base, T::checked_add_ext)
302
        } else {
303
17780
            self.parse_integer_digits(s, base, T::checked_sub_ext)
304
        }
305
246675
    }
306

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

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

            
336
228148
                if !self.consume_char('\'') {
337
294
                    return Err(Error::ExpectedByteLiteral);
338
227854
                }
339

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

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

            
348
113331
        let base = match () {
349
113331
            () if self.consume_str("0b") => 2,
350
110649
            () if self.consume_str("0o") => 8,
351
108849
            () if self.consume_str("0x") => 16,
352
107045
            () => 10,
353
        };
354

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

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

            
361
            #[allow(clippy::never_loop)]
362
            loop {
363
12675
                let (res, suffix_bytes) = if self.consume_ident("i8") {
364
922
                    let suffix_bytes = self.src();
365
922
                    self.set_cursor(int_cursor);
366
922
                    (
367
922
                        self.parse_integer::<i8>(sign, base).map(ParsedInteger::I8),
368
922
                        suffix_bytes,
369
922
                    )
370
11753
                } else if self.consume_ident("i16") {
371
922
                    let suffix_bytes = self.src();
372
922
                    self.set_cursor(int_cursor);
373
922
                    (
374
922
                        self.parse_integer::<i16>(sign, base)
375
922
                            .map(ParsedInteger::I16),
376
922
                        suffix_bytes,
377
922
                    )
378
10831
                } else if self.consume_ident("i32") {
379
1260
                    let suffix_bytes = self.src();
380
1260
                    self.set_cursor(int_cursor);
381
1260
                    (
382
1260
                        self.parse_integer::<i32>(sign, base)
383
1260
                            .map(ParsedInteger::I32),
384
1260
                        suffix_bytes,
385
1260
                    )
386
9571
                } else if self.consume_ident("i64") {
387
922
                    let suffix_bytes = self.src();
388
922
                    self.set_cursor(int_cursor);
389
922
                    (
390
922
                        self.parse_integer::<i64>(sign, base)
391
922
                            .map(ParsedInteger::I64),
392
922
                        suffix_bytes,
393
922
                    )
394
8649
                } else if self.consume_ident("u8") {
395
2388
                    let suffix_bytes = self.src();
396
2388
                    self.set_cursor(int_cursor);
397
2388
                    (
398
2388
                        self.parse_integer::<u8>(sign, base).map(ParsedInteger::U8),
399
2388
                        suffix_bytes,
400
2388
                    )
401
6261
                } else if self.consume_ident("u16") {
402
1220
                    let suffix_bytes = self.src();
403
1220
                    self.set_cursor(int_cursor);
404
1220
                    (
405
1220
                        self.parse_integer::<u16>(sign, base)
406
1220
                            .map(ParsedInteger::U16),
407
1220
                        suffix_bytes,
408
1220
                    )
409
5041
                } else if self.consume_ident("u32") {
410
1252
                    let suffix_bytes = self.src();
411
1252
                    self.set_cursor(int_cursor);
412
1252
                    (
413
1252
                        self.parse_integer::<u32>(sign, base)
414
1252
                            .map(ParsedInteger::U32),
415
1252
                        suffix_bytes,
416
1252
                    )
417
3789
                } else if self.consume_ident("u64") {
418
1220
                    let suffix_bytes = self.src();
419
1220
                    self.set_cursor(int_cursor);
420
1220
                    (
421
1220
                        self.parse_integer::<u64>(sign, base)
422
1220
                            .map(ParsedInteger::U64),
423
1220
                        suffix_bytes,
424
1220
                    )
425
                } else {
426
                    #[cfg(feature = "integer128")]
427
1673
                    if self.consume_ident("i128") {
428
463
                        let suffix_bytes = self.src();
429
463
                        self.set_cursor(int_cursor);
430
463
                        (
431
463
                            self.parse_integer::<i128>(sign, base)
432
463
                                .map(ParsedInteger::I128),
433
463
                            suffix_bytes,
434
463
                        )
435
1210
                    } else if self.consume_ident("u128") {
436
612
                        let suffix_bytes = self.src();
437
612
                        self.set_cursor(int_cursor);
438
612
                        (
439
612
                            self.parse_integer::<u128>(sign, base)
440
612
                                .map(ParsedInteger::U128),
441
612
                            suffix_bytes,
442
612
                        )
443
                    } else {
444
598
                        break;
445
                    }
446
                    #[cfg(not(feature = "integer128"))]
447
                    {
448
896
                        break;
449
                    }
450
                };
451

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

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

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

            
465
1494
            self.set_cursor(int_cursor);
466
100656
        }
467

            
468
102150
        T::parse(self, sign, base)
469
342361
    }
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
7644
    pub fn check_any_number_start(&mut self) -> bool {
475
7644
        match self.peek_char() {
476
            None => false,
477
7644
            Some(c) => {
478
7644
                self.is_number_start(c)
479
5880
                    || self.check_ident("inf")
480
4998
                    || self.check_ident("inff32")
481
4704
                    || self.check_ident("inff64")
482
4410
                    || self.check_ident("NaN")
483
3528
                    || self.check_ident("NaNf32")
484
3234
                    || self.check_ident("NaNf64")
485
            }
486
        }
487
7644
    }
488

            
489
9449237
    pub fn any_number(&mut self) -> Result<Number> {
490
9449237
        if self.consume_ident("inf") || self.consume_ident("inff32") {
491
1180
            return Ok(Number::F32(crate::value::F32(core::f32::INFINITY)));
492
9448057
        } else if self.consume_ident("inff64") {
493
294
            return Ok(Number::F64(crate::value::F64(core::f64::INFINITY)));
494
9447763
        } else if self.consume_ident("NaN") || self.consume_ident("NaNf32") {
495
1180
            return Ok(Number::F32(crate::value::F32(core::f32::NAN)));
496
9446583
        } else if self.consume_ident("NaNf64") {
497
294
            return Ok(Number::F64(crate::value::F64(core::f64::NAN)));
498
9446289
        }
499

            
500
9446289
        if self.next_bytes_is_float() {
501
9127302
            return match self.float::<ParsedFloat>()? {
502
5340
                ParsedFloat::F32(v) => Ok(Number::F32(v.into())),
503
9121962
                ParsedFloat::F64(v) => Ok(Number::F64(v.into())),
504
            };
505
318987
        }
506

            
507
318987
        let backup_cursor = self.cursor;
508

            
509
318987
        let (integer_err, integer_cursor) = match self.integer::<ParsedInteger>() {
510
315423
            Ok(integer) => {
511
315423
                return match integer {
512
894
                    ParsedInteger::I8(v) => Ok(Number::I8(v)),
513
592
                    ParsedInteger::I16(v) => Ok(Number::I16(v)),
514
592
                    ParsedInteger::I32(v) => Ok(Number::I32(v)),
515
592
                    ParsedInteger::I64(v) => Ok(Number::I64(v)),
516
                    #[cfg(feature = "integer128")]
517
590
                    ParsedInteger::I128(v) => Ok(Number::I128(v)),
518
309205
                    ParsedInteger::U8(v) => Ok(Number::U8(v)),
519
890
                    ParsedInteger::U16(v) => Ok(Number::U16(v)),
520
592
                    ParsedInteger::U32(v) => Ok(Number::U32(v)),
521
592
                    ParsedInteger::U64(v) => Ok(Number::U64(v)),
522
                    #[cfg(feature = "integer128")]
523
884
                    ParsedInteger::U128(v) => Ok(Number::U128(v)),
524
                }
525
            }
526
3564
            Err(err) => (err, self.cursor),
527
        };
528

            
529
3564
        self.set_cursor(backup_cursor);
530

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

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

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

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

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

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

            
570
51086
        Ok(c)
571
72005
    }
572

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

            
576
9555457
        if self.consume_char(',') {
577
9368671
            self.skip_ws()?;
578

            
579
9368671
            Ok(true)
580
        } else {
581
186786
            Ok(false)
582
        }
583
9555457
    }
584

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

            
591
315973
    fn check_ident_other_char(&self, index: usize) -> bool {
592
315973
        self.src()[index..]
593
315973
            .chars()
594
315973
            .next()
595
315973
            .map_or(false, is_xid_continue)
596
315973
    }
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
82546
    pub fn check_struct_type(
614
82546
        &mut self,
615
82546
        newtype: NewtypeMode,
616
82546
        tuple: TupleMode,
617
82546
    ) -> Result<StructType> {
618
82546
        fn check_struct_type_inner(
619
82546
            parser: &mut Parser,
620
82546
            newtype: NewtypeMode,
621
82546
            tuple: TupleMode,
622
82546
        ) -> Result<StructType> {
623
82546
            if matches!(newtype, NewtypeMode::NoParensMeanUnit) && !parser.consume_char('(') {
624
12940
                return Ok(StructType::Unit);
625
69606
            }
626

            
627
69606
            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
69602
            if matches!(newtype, NewtypeMode::NoParensMeanUnit) && parser.check_char(')') {
633
882
                return Ok(StructType::EmptyTuple);
634
68720
            }
635

            
636
68720
            if parser.skip_identifier().is_some() {
637
48984
                parser.skip_ws()?;
638

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

            
660
20324
            if matches!(tuple, TupleMode::ImpreciseTupleOrNewtype) {
661
13841
                return Ok(StructType::AnyTuple);
662
6483
            }
663

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

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

            
691
19743
                let c = parser.next_char()?;
692
19728
                if matches!(c, '(' | '[' | '{') {
693
1485
                    braces += 1;
694
18243
                } else if matches!(c, ')' | ']' | '}') {
695
7365
                    braces -= 1;
696
10893
                } else if c == ',' && braces == 1 {
697
588
                    parser.skip_ws()?;
698
588
                    more_than_one = !parser.check_char(')');
699
588
                    break;
700
10290
                }
701
            }
702

            
703
6468
            if more_than_one {
704
294
                Ok(StructType::NonNewtypeTuple)
705
            } else {
706
6174
                Ok(StructType::NewtypeTuple)
707
            }
708
82546
        }
709

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

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

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

            
720
82546
        result
721
82546
    }
722

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

            
729
168740
            true
730
        } else {
731
198707785
            false
732
        }
733
198876525
    }
734

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

            
741
70021
            return Ok(false);
742
17977
        }
743

            
744
17977
        let found_ident = match self.identifier() {
745
15919
            Ok(maybe_ident) => maybe_ident,
746
1470
            Err(Error::SuggestRawIdentifier(found_ident)) if found_ident == ident => {
747
294
                return Err(Error::SuggestRawIdentifier(found_ident))
748
            }
749
1764
            Err(_) => return Err(Error::ExpectedNamedStructLike(ident)),
750
        };
751

            
752
15919
        if ident.is_empty() {
753
324
            return Err(Error::ExpectedNamedStructLike(ident));
754
15595
        }
755

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

            
763
13819
        Ok(true)
764
88880
    }
765

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

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

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

            
783
36862
            self.skip_ws()?;
784
36862
            let extensions = self.extension_list()?;
785
36331
            self.skip_ws()?;
786

            
787
36331
            if self.consume_all(&[")", "]"])? {
788
36316
                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
624314
    }
811

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

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

            
821
37141
            extensions |= extension;
822

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

            
825
            // If we have no comma but another item, return an error
826
37141
            if !comma && self.check_ident_other_char(0) {
827
516
                return Err(Error::ExpectedComma);
828
36625
            }
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
36625
            if !comma || !self.check_ident_other_char(0) {
834
36331
                break;
835
294
            }
836
        }
837

            
838
36331
        Ok(extensions)
839
36862
    }
840

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
933
298
            self.set_cursor(backup_cursor);
934
9128315
        }
935

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

            
938
9128593
        self.advance_bytes(num_bytes);
939

            
940
9128593
        Ok(value)
941
9131771
    }
942

            
943
9741629
    pub fn skip_identifier(&mut self) -> Option<&'a str> {
944
        #[allow(clippy::nonminimal_bool)]
945
9741629
        if self.check_str("b\"") // byte string
946
9740151
            || self.check_str("b'") // byte literal
947
9513477
            || self.check_str("br#") // raw byte string
948
9512595
            || self.check_str("br\"") // raw byte string
949
9511713
            || self.check_str("r\"") // raw string
950
9511125
            || self.check_str("r#\"") // raw string
951
9510831
            || self.check_str("r##") // raw string
952
9510537
            || false
953
        {
954
231092
            return None;
955
9510537
        }
956

            
957
9510537
        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
9510525
        }
967

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

            
979
9393310
        None
980
9741629
    }
981

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

            
992
1188
            return Err(Error::ExpectedIdentifier);
993
326030
        }
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
326030
        if self.check_str("b\"") // byte string
999
325736
            || self.check_str("b'") // byte literal
325442
            || self.check_str("br#") // raw byte string
325148
            || self.check_str("br\"") // raw byte string
324854
            || self.check_str("r\"") // raw string
324560
            || self.check_str("r#\"") // raw string
324266
            || self.check_str("r##") // raw string
323972
            || false
        {
2058
            return Err(Error::ExpectedIdentifier);
323972
        }
323972
        let length = if self.check_str("r#") {
7672
            let cursor_backup = self.cursor;
7672
            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.
7672
            if !matches!(self.peek_char(), Some(c) if is_ident_raw_char(c)) {
588
                self.set_cursor(cursor_backup);
588
                return Err(Error::ExpectedIdentifier);
7084
            }
7084
            self.next_chars_while_len(is_ident_raw_char)
316300
        } else if first == 'r' {
588
            let std_ident_length = self.next_chars_while_len(is_xid_continue);
588
            let raw_ident_length = self.next_chars_while_len(is_ident_raw_char);
588
            if raw_ident_length > std_ident_length {
294
                return Err(Error::SuggestRawIdentifier(
294
                    self.src()[..raw_ident_length].into(),
294
                ));
294
            }
294
            std_ident_length
        } else {
315712
            let std_ident_length = first.len_utf8()
315712
                + self.next_chars_while_from_len(first.len_utf8(), is_xid_continue);
315712
            let raw_ident_length = self.next_chars_while_len(is_ident_raw_char);
315712
            if raw_ident_length > std_ident_length {
882
                return Err(Error::SuggestRawIdentifier(
882
                    self.src()[..raw_ident_length].into(),
882
                ));
314830
            }
314830
            std_ident_length
        };
322208
        let ident = &self.src()[..length];
322208
        self.advance_bytes(length);
322208
        Ok(ident)
328394
    }
9446293
    pub fn next_bytes_is_float(&mut self) -> bool {
9446293
        if let Some(c) = self.peek_char() {
9446289
            let skip = match c {
5374
                '+' | '-' => 1,
9440915
                _ => 0,
            };
9446289
            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.
9446289
            let valid_float_len = self.src()[skip..][..raw_float_len]
9446289
                .find("..")
9446289
                .map_or(raw_float_len, |i| i.min(raw_float_len));
9446289
            let valid_int_len = self.next_chars_while_from_len(skip, is_int_char);
9446289
            valid_float_len > valid_int_len
        } else {
4
            false
        }
9446293
    }
31249104
    pub fn skip_ws(&mut self) -> Result<()> {
31249104
        if (self.cursor.last_ws_len != WS_CURSOR_UNCLOSED_LINE)
31248512
            && ((self.cursor.pre_ws_cursor + self.cursor.last_ws_len) < self.cursor.cursor)
20742467
        {
20742467
            // the last whitespace is disjoint from this one, we need to track a new one
20742467
            self.cursor.pre_ws_cursor = self.cursor.cursor;
20742467
        }
31249104
        if self.src().is_empty() {
474104
            return Ok(());
30775000
        }
        loop {
30804702
            self.advance_bytes(self.next_chars_while_len(is_whitespace_char));
30804702
            match self.skip_comment()? {
30772934
                None => break,
                Some(Comment::UnclosedLine) => {
1180
                    self.cursor.last_ws_len = WS_CURSOR_UNCLOSED_LINE;
1180
                    return Ok(());
                }
29702
                Some(Comment::ClosedLine | Comment::Block) => continue,
            }
        }
30772934
        self.cursor.last_ws_len = self.cursor.cursor - self.cursor.pre_ws_cursor;
30772934
        Ok(())
31249104
    }
18816
    pub fn has_unclosed_line_comment(&self) -> bool {
18816
        self.src().is_empty() && self.cursor.last_ws_len == WS_CURSOR_UNCLOSED_LINE
18816
    }
10044
    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
10044
        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),
            }
10036
        } 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 {
10024
            self.byte_string_no_base64()
        }
10044
    }
29767
    pub fn byte_string_no_base64(&mut self) -> Result<ParsedByteStr<'a>> {
29767
        if self.consume_str("b\"") {
6790
            self.escaped_byte_string()
22977
        } else if self.consume_str("br") {
4116
            self.raw_byte_string()
        } else {
18861
            Err(Error::ExpectedByteString)
        }
29767
    }
6790
    fn escaped_byte_string(&mut self) -> Result<ParsedByteStr<'a>> {
6790
        match self.escaped_byte_buf(EscapeEncoding::Binary) {
6202
            Ok((bytes, advance)) => {
6202
                self.advance_bytes(advance);
6202
                Ok(bytes)
            }
588
            Err(err) => Err(err),
        }
6790
    }
4116
    fn raw_byte_string(&mut self) -> Result<ParsedByteStr<'a>> {
4116
        match self.raw_byte_buf() {
3528
            Ok((bytes, advance)) => {
3528
                self.advance_bytes(advance);
3528
                Ok(bytes)
            }
294
            Err(Error::ExpectedString) => Err(Error::ExpectedByteString),
294
            Err(err) => Err(err),
        }
4116
    }
117755
    pub fn string(&mut self) -> Result<ParsedStr<'a>> {
117755
        if self.consume_char('"') {
93832
            self.escaped_string()
23923
        } else if self.consume_char('r') {
3580
            self.raw_string()
        } else {
20343
            Err(Error::ExpectedString)
        }
117755
    }
93840
    fn escaped_string(&mut self) -> Result<ParsedStr<'a>> {
93840
        match self.escaped_byte_buf(EscapeEncoding::Utf8) {
91179
            Ok((bytes, advance)) => {
91179
                let string = ParsedStr::try_from_bytes(bytes).map_err(Error::from)?;
91179
                self.advance_bytes(advance);
91179
                Ok(string)
            }
2661
            Err(err) => Err(err),
        }
93840
    }
3592
    fn raw_string(&mut self) -> Result<ParsedStr<'a>> {
3592
        match self.raw_byte_buf() {
3000
            Ok((bytes, advance)) => {
3000
                let string = ParsedStr::try_from_bytes(bytes).map_err(Error::from)?;
3000
                self.advance_bytes(advance);
3000
                Ok(string)
            }
592
            Err(err) => Err(err),
        }
3592
    }
100630
    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
100630
        let str_end = self.src().find('"').ok_or(Error::ExpectedStringEnd)?;
99733
        let escape = self.src()[..str_end].find('\\');
99733
        if let Some(escape) = escape {
            // Now check if escaping is used inside the string
16504
            let mut i = escape;
16504
            let mut s = self.src().as_bytes()[..i].to_vec();
            loop {
45600108
                self.advance_bytes(i + 1);
45600108
                if !self.consume_string_continuation() {
45597756
                    match self.parse_escape(encoding, false)? {
45583342
                        EscapeCharacter::Ascii(c) => s.push(c),
12062
                        EscapeCharacter::Utf8(c) => match c.len_utf8() {
11466
                            1 => s.push(c as u8),
596
                            len => {
596
                                let start = s.len();
596
                                s.extend(core::iter::repeat(0).take(len));
596
                                c.encode_utf8(&mut s[start..]);
596
                            }
                        },
                    }
2352
                }
                // 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.
45597756
                let next = self
45597756
                    .src()
45597756
                    .find(['"', '\\'])
45597756
                    .ok_or(Error::ExpectedStringEnd)?;
45597756
                s.extend_from_slice(&self.src().as_bytes()[..next]);
                // `next` indexes an ASCII byte, so byte indexing is valid here.
45597756
                if self.src().as_bytes()[next] == b'\\' {
45583604
                    i = next;
45583604
                } else {
                    // Advance to the end of the string + 1 for the `"`.
14152
                    break Ok((ParsedByteStr::Allocated(s), next + 1));
                }
            }
        } else {
83229
            let s = &self.src().as_bytes()[..str_end];
            // Advance by the number of bytes of the string + 1 for the `"`.
83229
            Ok((ParsedByteStr::Slice(s), str_end + 1))
        }
100630
    }
    /// 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.
45600108
    fn consume_string_continuation(&mut self) -> bool {
45600108
        let line_ending_len = if self.check_str("\r\n") {
588
            2
45599520
        } else if self.check_char('\n') {
1764
            1
        } else {
45597756
            return false;
        };
2352
        self.advance_bytes(line_ending_len);
2352
        let whitespace = self.next_chars_while_len(is_string_continuation_whitespace);
2352
        self.advance_bytes(whitespace);
2352
        true
45600108
    }
7708
    fn raw_byte_buf(&mut self) -> Result<(ParsedByteStr<'a>, usize)> {
14816
        let num_hashes = self.next_chars_while_len(|c| c == '#');
7708
        let hashes = &self.src()[..num_hashes];
7708
        self.advance_bytes(num_hashes);
7708
        self.expect_char('"', Error::ExpectedString)?;
7116
        let ending = ["\"", hashes].concat();
7116
        let i = self.src().find(&ending).ok_or(Error::ExpectedStringEnd)?;
6528
        let s = &self.src().as_bytes()[..i];
        // Advance by the number of bytes of the byte string
        // + `num_hashes` + 1 for the `"`.
6528
        Ok((ParsedByteStr::Slice(s), i + num_hashes + 1))
7708
    }
207982
    fn decode_ascii_escape(&mut self) -> Result<u8> {
207982
        let mut n = 0;
207982
        for _ in 0..2 {
415964
            n <<= 4;
415964
            let byte = self.next_char()?;
415964
            let decoded = Self::decode_hex(byte)?;
415376
            n |= decoded;
        }
207394
        Ok(n)
207982
    }
    #[inline]
1015560
    fn decode_hex(c: char) -> Result<u8> {
1015560
        if !c.is_ascii() {
294
            return Err(Error::InvalidEscape("Non-hex digit found"));
1015266
        }
        // c is an ASCII character that can be losslessly cast to u8
1015266
        match c as u8 {
1014972
            c @ b'0'..=b'9' => Ok(c - b'0'),
116488
            c @ b'a'..=b'f' => Ok(10 + c - b'a'),
59976
            c @ b'A'..=b'F' => Ok(10 + c - b'A'),
294
            _ => Err(Error::InvalidEscape("Non-hex digit found")),
        }
1015560
    }
45802392
    fn parse_escape(&mut self, encoding: EscapeEncoding, is_char: bool) -> Result<EscapeCharacter> {
45802392
        let c = match self.next_char()? {
894
            '\'' => EscapeCharacter::Ascii(b'\''),
3846
            '"' => EscapeCharacter::Ascii(b'"'),
2940
            '\\' => EscapeCharacter::Ascii(b'\\'),
45573234
            'n' => EscapeCharacter::Ascii(b'\n'),
588
            'r' => EscapeCharacter::Ascii(b'\r'),
588
            't' => EscapeCharacter::Ascii(b'\t'),
1764
            '0' => EscapeCharacter::Ascii(b'\0'),
            'x' => {
                // Fast exit for ascii escape in byte string
204720
                let b: u8 = self.decode_ascii_escape()?;
204132
                if let EscapeEncoding::Binary = encoding {
201184
                    return Ok(EscapeCharacter::Ascii(b));
2948
                }
                // Fast exit for ascii character in UTF-8 string
2948
                let mut bytes = [b, 0, 0, 0];
2948
                if let Ok(Some(c)) = from_utf8(&bytes[..=0]).map(|s| s.chars().next()) {
882
                    return Ok(EscapeCharacter::Utf8(c));
2066
                }
2066
                if is_char {
                    // Character literals are not allowed to use multiple byte
                    //  escapes to build a unicode character
294
                    return Err(Error::InvalidEscape(
294
                        "Not a valid byte-escaped Unicode character",
294
                    ));
1772
                }
                // UTF-8 character needs up to four bytes and we have already
                //  consumed one, so at most three to go
4434
                for i in 1..4 {
4434
                    if !self.consume_str(r"\x") {
1176
                        return Err(Error::InvalidEscape(
1176
                            "Not a valid byte-escaped Unicode character",
1176
                        ));
3258
                    }
3258
                    bytes[i] = self.decode_ascii_escape()?;
                    // Check if we now have a valid UTF-8 character
3258
                    if let Ok(Some(c)) = from_utf8(&bytes[..=i]).map(|s| s.chars().next()) {
302
                        return Ok(EscapeCharacter::Utf8(c));
2956
                    }
                }
294
                return Err(Error::InvalidEscape(
294
                    "Not a valid byte-escaped Unicode character",
294
                ));
            }
            'u' => {
12642
                self.expect_char('{', Error::InvalidEscape("Missing { in Unicode escape"))?;
12642
                let mut bytes: u32 = 0;
12642
                let mut num_digits = 0;
33810
                while num_digits < 6 {
33810
                    let byte = self.peek_char_or_eof()?;
33810
                    if byte == '}' {
12642
                        break;
21168
                    }
21168
                    self.skip_next_char();
21168
                    num_digits += 1;
21168
                    let byte = Self::decode_hex(byte)?;
21168
                    bytes <<= 4;
21168
                    bytes |= u32::from(byte);
                }
12642
                if num_digits == 0 {
294
                    return Err(Error::InvalidEscape(
294
                        "Expected 1-6 digits, got 0 digits in Unicode escape",
294
                    ));
12348
                }
12348
                self.expect_char(
                    '}',
12348
                    Error::InvalidEscape("No } at the end of Unicode escape"),
                )?;
12348
                let c = char_from_u32(bytes).ok_or(Error::InvalidEscape(
12348
                    "Not a valid Unicode-escaped character",
12348
                ))?;
12348
                EscapeCharacter::Utf8(c)
            }
1176
            _ => return Err(Error::InvalidEscape("Unknown escape character")),
        };
45596202
        Ok(c)
45802392
    }
30804702
    fn skip_comment(&mut self) -> Result<Option<Comment>> {
30804702
        if self.consume_char('/') {
31768
            match self.next_char()? {
                '/' => {
130968
                    let bytes = self.next_chars_while_len(|c| c != '\n');
8824
                    self.advance_bytes(bytes);
8824
                    if self.src().is_empty() {
1180
                        Ok(Some(Comment::UnclosedLine))
                    } else {
7644
                        Ok(Some(Comment::ClosedLine))
                    }
                }
                '*' => {
22650
                    let mut level = 1;
52352
                    while level > 0 {
205538
                        let bytes = self.next_chars_while_len(|c| !matches!(c, '/' | '*'));
30294
                        if self.src().is_empty() {
298
                            return Err(Error::UnclosedBlockComment);
29996
                        }
29996
                        self.advance_bytes(bytes);
                        // check whether / or * and take action
29996
                        if self.consume_str("/*") {
2058
                            level += 1;
27938
                        } else if self.consume_str("*/") {
24116
                            level -= 1;
24116
                        } else {
3822
                            self.next_char().map_err(|_| Error::UnclosedBlockComment)?;
                        }
                    }
22058
                    Ok(Some(Comment::Block))
                }
294
                c => Err(Error::UnexpectedChar(c)),
            }
        } else {
30772934
            Ok(None)
        }
30804702
    }
}
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 {
1394691
            fn from_u8(x: u8) -> Self {
77050
                x as $ty
1394691
            }
579318
            fn checked_mul_ext(&mut self, x: u8) -> bool {
579318
                match self.checked_mul(Self::from_u8(x)) {
578428
                    Some(n) => {
578428
                        *self = n;
578428
                        false
                    }
890
                    None => true,
                }
579318
            }
477710
            fn checked_add_ext(&mut self, x: u8) -> bool {
477710
                match self.checked_add(Self::from_u8(x)) {
477269
                    Some(n) => {
477269
                        *self = n;
477269
                        false
                    }
441
                    None => true,
                }
477710
            }
98660
            fn checked_sub_ext(&mut self, x: u8) -> bool {
98660
                match self.checked_sub(Self::from_u8(x)) {
95720
                    Some(n) => {
95720
                        *self = n;
95720
                        false
                    }
2940
                    None => true,
                }
98660
            }
        }
    };
    ($($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 {
118347
            fn parse(parser: &mut Parser, sign: i8, base: u8) -> Result<Self> {
118347
                parser.parse_integer(sign, base)
118347
            }
34986
            fn try_from_parsed_integer(parsed: ParsedInteger, ron: &str) -> Result<Self> {
34986
                match parsed {
12936
                    ParsedInteger::$wrap(v) => Ok(v),
                    _ => Err(Error::InvalidValueForType {
22050
                        expected: format!(
                            "a{} {}-bit {}signed integer",
22050
                            if <$ty>::BITS == 8 { "n" } else { "n" },
                            <$ty>::BITS,
22050
                            if <$ty>::MIN == 0 { "un" } else { "" },
                        ),
22050
                        found: String::from(ron),
                    }),
                }
34986
            }
        }
    };
    ($($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 {
84522
    fn parse(parser: &mut Parser, sign: i8, base: u8) -> Result<Self> {
84522
        if sign < 0 {
2108
            let signed = parser.parse_integer::<LargeSInt>(-1, base)?;
614
            return if let Ok(x) = i8::try_from(signed) {
306
                Ok(ParsedInteger::I8(x))
308
            } else if let Ok(x) = i16::try_from(signed) {
4
                Ok(ParsedInteger::I16(x))
304
            } 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")]
298
                if let Ok(x) = i64::try_from(signed) {
2
                    Ok(ParsedInteger::I64(x))
                } else {
296
                    Ok(ParsedInteger::I128(signed))
                }
            };
82414
        }
82414
        let unsigned = parser.parse_integer::<LargeUInt>(1, base)?;
81667
        if let Ok(x) = u8::try_from(unsigned) {
80767
            Ok(ParsedInteger::U8(x))
900
        } else if let Ok(x) = u16::try_from(unsigned) {
302
            Ok(ParsedInteger::U16(x))
598
        } 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")]
592
            if let Ok(x) = u64::try_from(unsigned) {
2
                Ok(ParsedInteger::U64(x))
            } else {
590
                Ok(ParsedInteger::U128(unsigned))
            }
        }
84522
    }
233142
    fn try_from_parsed_integer(parsed: ParsedInteger, _ron: &str) -> Result<Self> {
233142
        Ok(parsed)
233142
    }
}
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 {
37323
            fn parse(float: &str) -> Result<Self> {
37323
                <$ty>::from_str(float).map_err(|_| Error::ExpectedFloat)
37323
            }
4116
            fn try_from_parsed_float(parsed: ParsedFloat, ron: &str) -> Result<Self> {
4116
                match parsed {
3528
                    ParsedFloat::$wrap(v) => Ok(v),
588
                    _ => Err(Error::InvalidValueForType {
588
                        expected: format!(
588
                            "a {}-bit floating point number", $bits,
588
                        ),
588
                        found: String::from(ron),
588
                    }),
                }
4116
            }
        }
    };
    ($($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 {
9127926
    fn parse(float: &str) -> Result<Self> {
9127926
        let value = f64::from_str(float).map_err(|_| Error::ExpectedFloat)?;
        #[allow(clippy::cast_possible_truncation)]
9127926
        if value.total_cmp(&f64::from(value as f32)).is_eq() {
6544
            Ok(ParsedFloat::F32(value as f32))
        } else {
9121382
            Ok(ParsedFloat::F64(value))
        }
9127926
    }
2940
    fn try_from_parsed_float(parsed: ParsedFloat, _ron: &str) -> Result<Self> {
2940
        Ok(parsed)
2940
    }
}
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> {
94179
    pub fn try_from_bytes(bytes: ParsedByteStr<'a>) -> Result<Self, Utf8Error> {
94179
        match bytes {
10604
            ParsedByteStr::Allocated(byte_buf) => Ok(ParsedStr::Allocated(
10604
                String::from_utf8(byte_buf).map_err(|e| e.utf8_error())?,
            )),
83575
            ParsedByteStr::Slice(bytes) => Ok(ParsedStr::Slice(from_utf8(bytes)?)),
        }
94179
    }
}
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
    }
}