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

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

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

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

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

            
53
9300
const fn is_string_continuation_whitespace(c: char) -> bool {
54
9300
    matches!(c, ' ' | '\t' | '\n' | '\r')
55
9300
}
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
    /// Set if the document starts with global attributes, like
70
    /// `#![type = ".."]`, that do not affect parsing.
71
    pub(crate) global_attributes: bool,
72
    src: &'a str,
73
    cursor: ParserCursor,
74
    prev_cursor: ParserCursor,
75
}
76

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

            
84
enum ParsedAttribute {
85
    None,
86
    Extensions(Extensions),
87
    Ignored,
88
}
89

            
90
const WS_CURSOR_UNCLOSED_LINE: usize = usize::MAX;
91

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

            
98
impl PartialOrd for ParserCursor {
99
5624
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
100
5624
        self.cursor.partial_cmp(&other.cursor)
101
5624
    }
102
}
103

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

            
123
690126
        parser.skip_ws().map_err(|e| parser.span_error(e))?;
124

            
125
        // Loop over all document attributes
126
        loop {
127
738370
            match parser.attribute().map_err(|e| parser.span_error(e))? {
128
689230
                ParsedAttribute::None => break,
129
46658
                ParsedAttribute::Extensions(extensions) => {
130
46658
                    parser.exts |= extensions;
131
46658
                }
132
1896
                ParsedAttribute::Ignored => {
133
1896
                    parser.global_attributes = true;
134
1896
                }
135
            }
136

            
137
48554
            parser.skip_ws().map_err(|e| parser.span_error(e))?;
138
        }
139

            
140
689230
        Ok(parser)
141
690126
    }
142

            
143
184909760
    fn set_cursor(&mut self, cursor: ParserCursor) {
144
184909760
        self.cursor = cursor;
145
184909760
    }
146

            
147
134132
    pub fn span_error(&self, code: Error) -> SpannedError {
148
134132
        SpannedError {
149
134132
            code,
150
134132
            span: Span {
151
134132
                start: Position::from_src_end(&self.src[..self.prev_cursor.cursor]),
152
134132
                end: Position::from_src_end(&self.src[..self.cursor.cursor]),
153
134132
            },
154
134132
        }
155
134132
    }
156

            
157
17360
    pub fn is_number_start(&self, c: char) -> bool {
158
17360
        matches!(c, '0'..='9' | '+' | '-' | '.' | 'b') && (c != 'b' || self.src().starts_with("b'"))
159
17360
    }
160

            
161
228758939
    pub fn advance_bytes(&mut self, bytes: usize) {
162
228758939
        self.prev_cursor = self.cursor;
163
228758939
        self.cursor.cursor += bytes;
164
228758939
    }
165

            
166
115004289
    pub fn next_char(&mut self) -> Result<char> {
167
115004289
        let c = self.peek_char_or_eof()?;
168
115003654
        self.cursor.cursor += c.len_utf8();
169
115003654
        Ok(c)
170
115004289
    }
171

            
172
64604
    pub fn skip_next_char(&mut self) {
173
64604
        core::mem::drop(self.next_char());
174
64604
    }
175

            
176
146525624
    pub fn peek_char(&self) -> Option<char> {
177
146525624
        self.src().chars().next()
178
146525624
    }
179

            
180
126182082
    pub fn peek_char_or_eof(&self) -> Result<char> {
181
126182082
        self.peek_char().ok_or(Error::Eof)
182
126182082
    }
183

            
184
433178746
    pub fn check_char(&self, c: char) -> bool {
185
433178746
        self.src().starts_with(c)
186
433178746
    }
187

            
188
520228299
    pub fn check_str(&self, s: &str) -> bool {
189
520228299
        self.src().starts_with(s)
190
520228299
    }
191

            
192
1879913574
    pub fn src(&self) -> &'a str {
193
1879913574
        &self.src[self.cursor.cursor..]
194
1879913574
    }
195

            
196
50260
    pub fn pre_ws_src(&self) -> &'a str {
197
50260
        &self.src[self.cursor.pre_ws_cursor..]
198
50260
    }
199

            
200
    /// Whether no source has been consumed before the last whitespace,
201
    /// i.e. whether we are at the start of the top-level value.
202
41850
    pub fn is_at_start(&self) -> bool {
203
41850
        self.cursor.pre_ws_cursor == 0
204
41850
    }
205

            
206
147697832
    pub fn consume_str(&mut self, s: &str) -> bool {
207
147697832
        if self.check_str(s) {
208
623201
            self.advance_bytes(s.len());
209

            
210
623201
            true
211
        } else {
212
147074631
            false
213
        }
214
147697832
    }
215

            
216
346256515
    pub fn consume_char(&mut self, c: char) -> bool {
217
346256515
        if self.check_char(c) {
218
11756769
            self.advance_bytes(c.len_utf8());
219

            
220
11756769
            true
221
        } else {
222
334499746
            false
223
        }
224
346256515
    }
225

            
226
    /// Consumes a unit `()`, which may contain whitespace and comments
227
    /// between the parentheses. Does not change state if it fails.
228
10303981
    pub fn consume_unit(&mut self) -> Result<bool> {
229
10303981
        let backup_cursor = self.cursor;
230
10303981
        let backup_prev_cursor = self.prev_cursor;
231

            
232
10303981
        if self.consume_char('(') {
233
129739
            self.skip_ws()?;
234

            
235
129425
            if self.consume_char(')') {
236
                // Errors for the unit should span all of it, like for `()`
237
28548
                self.prev_cursor = backup_cursor;
238

            
239
28548
                return Ok(true);
240
100877
            }
241
10174242
        }
242

            
243
10275119
        self.set_cursor(backup_cursor);
244
10275119
        self.prev_cursor = backup_prev_cursor;
245

            
246
10275119
        Ok(false)
247
10303981
    }
248

            
249
95813
    fn consume_all(&mut self, all: &[&str]) -> Result<bool> {
250
95813
        all.iter()
251
240766
            .map(|elem| {
252
240766
                if self.consume_str(elem) {
253
240727
                    self.skip_ws()?;
254

            
255
240727
                    Ok(true)
256
                } else {
257
39
                    Ok(false)
258
                }
259
240766
            })
260
240766
            .try_fold(true, |acc, x| x.map(|x| x && acc))
261
95813
    }
262

            
263
58305063
    pub fn expect_char(&mut self, expected: char, error: Error) -> Result<()> {
264
58305063
        if self.consume_char(expected) {
265
166684
            Ok(())
266
        } else {
267
58138379
            Err(error)
268
        }
269
58305063
    }
270

            
271
    #[must_use]
272
160274478
    pub fn next_chars_while_len(&self, condition: fn(char) -> bool) -> usize {
273
160274478
        self.next_chars_while_from_len(0, condition)
274
160274478
    }
275

            
276
    #[must_use]
277
180844211
    pub fn next_chars_while_from_len(&self, from: usize, condition: fn(char) -> bool) -> usize {
278
180844211
        self.src()[from..]
279
401855985
            .find(|c| !condition(c))
280
180844211
            .unwrap_or(self.src().len() - from)
281
180844211
    }
282
}
283

            
284
/// actual parsing of ron tokens
285
impl<'a> Parser<'a> {
286
276263
    fn parse_integer_digits<T: Num>(
287
276263
        &mut self,
288
276263
        s: &str,
289
276263
        base: u8,
290
276263
        f: fn(&mut T, u8) -> bool,
291
276263
    ) -> Result<T> {
292
276263
        let mut num_acc = T::from_u8(0);
293

            
294
645018
        for (i, c) in s.char_indices() {
295
645018
            if c == '_' {
296
10374
                continue;
297
634644
            }
298

            
299
634644
            if num_acc.checked_mul_ext(base) {
300
938
                self.advance_bytes(s.len());
301
938
                return Err(Error::IntegerOutOfBounds);
302
633706
            }
303

            
304
633706
            let digit = Self::decode_hex(c)?;
305

            
306
633706
            if digit >= base {
307
3100
                self.advance_bytes(i);
308
3100
                return Err(Error::InvalidIntegerDigit { digit: c, base });
309
630606
            }
310

            
311
630606
            if f(&mut num_acc, digit) {
312
3565
                self.advance_bytes(s.len());
313
3565
                return Err(Error::IntegerOutOfBounds);
314
627041
            }
315
        }
316

            
317
268660
        self.advance_bytes(s.len());
318

            
319
268660
        Ok(num_acc)
320
276263
    }
321

            
322
285281
    fn parse_integer<T: Num>(&mut self, sign: i8, base: u8) -> Result<T> {
323
285281
        let num_bytes = self.next_chars_while_len(is_int_char);
324

            
325
285281
        if num_bytes == 0 {
326
5918
            return Err(Error::ExpectedInteger);
327
279363
        }
328

            
329
279363
        if self.check_char('_') {
330
3100
            return Err(Error::UnderscoreAtBeginning);
331
276263
        }
332

            
333
276263
        let s = &self.src()[..num_bytes];
334

            
335
276263
        if sign > 0 {
336
256355
            self.parse_integer_digits(s, base, T::checked_add_ext)
337
        } else {
338
19908
            self.parse_integer_digits(s, base, T::checked_sub_ext)
339
        }
340
285281
    }
341

            
342
    #[allow(clippy::too_many_lines)]
343
385035
    pub fn integer<T: Integer>(&mut self) -> Result<T> {
344
385035
        let src_backup = self.src();
345

            
346
385035
        let is_negative = match self.peek_char_or_eof()? {
347
            '+' => {
348
28
                self.skip_next_char();
349
28
                false
350
            }
351
            '-' => {
352
7096
                self.skip_next_char();
353
7096
                true
354
            }
355
244594
            'b' if self.consume_str("b'") => {
356
                // Parse a byte literal
357
244594
                let byte = match self.next_char()? {
358
212040
                    '\\' => match self.parse_escape(EscapeEncoding::Binary, true)? {
359
                        // we know that this byte is an ASCII character
360
211420
                        EscapeCharacter::Ascii(b) => b,
361
                        EscapeCharacter::Utf8(_) => {
362
310
                            return Err(Error::InvalidEscape(
363
310
                                "Unexpected Unicode escape in byte literal",
364
310
                            ))
365
                        }
366
                    },
367
                    // an apostrophe must be escaped, so `b''` and `b'''` are not byte literals
368
1860
                    '\'' => return Err(Error::ExpectedByteLiteral),
369
30694
                    b if b.is_ascii() => b as u8,
370
310
                    _ => return Err(Error::ExpectedByteLiteral),
371
                };
372

            
373
241804
                if !self.consume_char('\'') {
374
310
                    return Err(Error::ExpectedByteLiteral);
375
241494
                }
376

            
377
241494
                let bytes_ron = &src_backup[..src_backup.len() - self.src().len()];
378

            
379
241494
                return T::try_from_parsed_integer(ParsedInteger::U8(byte), bytes_ron);
380
            }
381
133317
            _ => false,
382
        };
383
140441
        let sign = if is_negative { -1 } else { 1 };
384

            
385
140441
        let base = match () {
386
140441
            () if self.consume_str("0b") => 2,
387
137615
            () if self.consume_str("0o") => 8,
388
135719
            () if self.consume_str("0x") => 16,
389
133819
            () => 10,
390
        };
391

            
392
140441
        let num_bytes = self.next_chars_while_len(is_int_char);
393

            
394
140441
        if self.src()[num_bytes..].starts_with(['i', 'u']) {
395
13967
            let int_cursor = self.cursor;
396
13967
            self.advance_bytes(num_bytes);
397

            
398
            #[allow(clippy::never_loop)]
399
            loop {
400
13967
                let (res, suffix_bytes) = if self.consume_ident("i8") {
401
970
                    let suffix_bytes = self.src();
402
970
                    self.set_cursor(int_cursor);
403
970
                    (
404
970
                        self.parse_integer::<i8>(sign, base).map(ParsedInteger::I8),
405
970
                        suffix_bytes,
406
970
                    )
407
12997
                } else if self.consume_ident("i16") {
408
970
                    let suffix_bytes = self.src();
409
970
                    self.set_cursor(int_cursor);
410
970
                    (
411
970
                        self.parse_integer::<i16>(sign, base)
412
970
                            .map(ParsedInteger::I16),
413
970
                        suffix_bytes,
414
970
                    )
415
12027
                } else if self.consume_ident("i32") {
416
1328
                    let suffix_bytes = self.src();
417
1328
                    self.set_cursor(int_cursor);
418
1328
                    (
419
1328
                        self.parse_integer::<i32>(sign, base)
420
1328
                            .map(ParsedInteger::I32),
421
1328
                        suffix_bytes,
422
1328
                    )
423
10699
                } else if self.consume_ident("i64") {
424
970
                    let suffix_bytes = self.src();
425
970
                    self.set_cursor(int_cursor);
426
970
                    (
427
970
                        self.parse_integer::<i64>(sign, base)
428
970
                            .map(ParsedInteger::I64),
429
970
                        suffix_bytes,
430
970
                    )
431
9729
                } else if self.consume_ident("u8") {
432
2520
                    let suffix_bytes = self.src();
433
2520
                    self.set_cursor(int_cursor);
434
2520
                    (
435
2520
                        self.parse_integer::<u8>(sign, base).map(ParsedInteger::U8),
436
2520
                        suffix_bytes,
437
2520
                    )
438
7209
                } else if self.consume_ident("u16") {
439
1284
                    let suffix_bytes = self.src();
440
1284
                    self.set_cursor(int_cursor);
441
1284
                    (
442
1284
                        self.parse_integer::<u16>(sign, base)
443
1284
                            .map(ParsedInteger::U16),
444
1284
                        suffix_bytes,
445
1284
                    )
446
5925
                } else if self.consume_ident("u32") {
447
1316
                    let suffix_bytes = self.src();
448
1316
                    self.set_cursor(int_cursor);
449
1316
                    (
450
1316
                        self.parse_integer::<u32>(sign, base)
451
1316
                            .map(ParsedInteger::U32),
452
1316
                        suffix_bytes,
453
1316
                    )
454
4609
                } else if self.consume_ident("u64") {
455
1284
                    let suffix_bytes = self.src();
456
1284
                    self.set_cursor(int_cursor);
457
1284
                    (
458
1284
                        self.parse_integer::<u64>(sign, base)
459
1284
                            .map(ParsedInteger::U64),
460
1284
                        suffix_bytes,
461
1284
                    )
462
                } else {
463
                    #[cfg(feature = "integer128")]
464
2071
                    if self.consume_ident("i128") {
465
487
                        let suffix_bytes = self.src();
466
487
                        self.set_cursor(int_cursor);
467
487
                        (
468
487
                            self.parse_integer::<i128>(sign, base)
469
487
                                .map(ParsedInteger::I128),
470
487
                            suffix_bytes,
471
487
                        )
472
1584
                    } else if self.consume_ident("u128") {
473
644
                        let suffix_bytes = self.src();
474
644
                        self.set_cursor(int_cursor);
475
644
                        (
476
644
                            self.parse_integer::<u128>(sign, base)
477
644
                                .map(ParsedInteger::U128),
478
644
                            suffix_bytes,
479
644
                        )
480
                    } else {
481
940
                        break;
482
                    }
483
                    #[cfg(not(feature = "integer128"))]
484
                    {
485
1254
                        break;
486
                    }
487
                };
488

            
489
11455
                if !matches!(
490
2041
                    &res,
491
                    Err(Error::UnderscoreAtBeginning | Error::InvalidIntegerDigit { .. })
492
11455
                ) {
493
11455
                    // Advance past the number suffix
494
11455
                    self.skip_identifier();
495
11455
                }
496

            
497
11773
                let integer_ron = &src_backup[..src_backup.len() - suffix_bytes.len()];
498

            
499
11773
                return res.and_then(|parsed| T::try_from_parsed_integer(parsed, integer_ron));
500
            }
501

            
502
2194
            self.set_cursor(int_cursor);
503
126474
        }
504

            
505
128668
        T::parse(self, sign, base)
506
385035
    }
507

            
508
    /// Check whether [`Parser::any_number`] has a number literal to parse at
509
    /// the cursor. The `inf` and `NaN` literals start with a letter, so they
510
    /// are not covered by [`Parser::is_number_start`].
511
18600
    pub fn check_any_number_start(&mut self) -> bool {
512
18600
        match self.peek_char() {
513
1240
            None => false,
514
17360
            Some(c) => {
515
17360
                self.is_number_start(c)
516
11780
                    || self.check_ident("inf")
517
9300
                    || self.check_ident("inff32")
518
8990
                    || self.check_ident("inff64")
519
8370
                    || self.check_ident("NaN")
520
6820
                    || self.check_ident("NaNf32")
521
6200
                    || self.check_ident("NaNf64")
522
            }
523
        }
524
18600
    }
525

            
526
9991913
    pub fn any_number(&mut self) -> Result<Number> {
527
9991913
        if self.consume_ident("inf") || self.consume_ident("inff32") {
528
3104
            return Ok(Number::F32(crate::value::F32(core::f32::INFINITY)));
529
9988809
        } else if self.consume_ident("inff64") {
530
930
            return Ok(Number::F64(crate::value::F64(core::f64::INFINITY)));
531
9987879
        } else if self.consume_ident("NaN") || self.consume_ident("NaNf32") {
532
2174
            return Ok(Number::F32(crate::value::F32(core::f32::NAN)));
533
9985705
        } else if self.consume_ident("NaNf64") {
534
310
            return Ok(Number::F64(crate::value::F64(core::f64::NAN)));
535
9985395
        }
536

            
537
9985395
        if self.next_bytes_is_float() {
538
9626192
            return match self.float::<ParsedFloat>()? {
539
8108
                ParsedFloat::F32(v) => Ok(Number::F32(v.into())),
540
9618084
                ParsedFloat::F64(v) => Ok(Number::F64(v.into())),
541
            };
542
359203
        }
543

            
544
359203
        let backup_cursor = self.cursor;
545

            
546
359203
        let (integer_err, integer_cursor) = match self.integer::<ParsedInteger>() {
547
352657
            Ok(integer) => {
548
352657
                return match integer {
549
1562
                    ParsedInteger::I8(v) => Ok(Number::I8(v)),
550
624
                    ParsedInteger::I16(v) => Ok(Number::I16(v)),
551
624
                    ParsedInteger::I32(v) => Ok(Number::I32(v)),
552
624
                    ParsedInteger::I64(v) => Ok(Number::I64(v)),
553
                    #[cfg(feature = "integer128")]
554
622
                    ParsedInteger::I128(v) => Ok(Number::I128(v)),
555
345483
                    ParsedInteger::U8(v) => Ok(Number::U8(v)),
556
938
                    ParsedInteger::U16(v) => Ok(Number::U16(v)),
557
624
                    ParsedInteger::U32(v) => Ok(Number::U32(v)),
558
624
                    ParsedInteger::U64(v) => Ok(Number::U64(v)),
559
                    #[cfg(feature = "integer128")]
560
932
                    ParsedInteger::U128(v) => Ok(Number::U128(v)),
561
                }
562
            }
563
6546
            Err(err) => (err, self.cursor),
564
        };
565

            
566
6546
        self.set_cursor(backup_cursor);
567

            
568
        // Fall-back to parse an out-of-range integer as a float
569
6546
        match self.float::<ParsedFloat>() {
570
4058
            Ok(ParsedFloat::F32(v)) if self.cursor >= integer_cursor => Ok(Number::F32(v.into())),
571
1558
            Ok(ParsedFloat::F64(v)) if self.cursor >= integer_cursor => Ok(Number::F64(v.into())),
572
            _ => {
573
                // Return the more precise integer error
574
2325
                self.set_cursor(integer_cursor);
575
2325
                Err(integer_err)
576
            }
577
        }
578
9991913
    }
579

            
580
39754
    pub fn bool(&mut self) -> Result<bool> {
581
39754
        if self.consume_ident("true") {
582
20144
            Ok(true)
583
19610
        } else if self.consume_ident("false") {
584
19574
            Ok(false)
585
        } else {
586
36
            Err(Error::ExpectedBoolean)
587
        }
588
39754
    }
589

            
590
58199677
    pub fn char(&mut self) -> Result<char> {
591
58199677
        self.expect_char('\'', Error::ExpectedChar)?;
592

            
593
61922
        let c = self.next_char()?;
594

            
595
61922
        let c = if c == '\\' {
596
4972
            match self.parse_escape(EscapeEncoding::Utf8, true)? {
597
                // we know that this byte is an ASCII character
598
2492
                EscapeCharacter::Ascii(b) => char::from(b),
599
1240
                EscapeCharacter::Utf8(c) => c,
600
            }
601
56950
        } else if c == '\'' {
602
            // an apostrophe must be escaped, so `''` and `'''` are not chars
603
2170
            return Err(Error::ExpectedChar);
604
        } else {
605
54780
            c
606
        };
607

            
608
58512
        self.expect_char('\'', Error::ExpectedChar)?;
609

            
610
58512
        Ok(c)
611
58199677
    }
612

            
613
10144221
    pub fn comma(&mut self) -> Result<bool> {
614
10144221
        self.skip_ws()?;
615

            
616
10144221
        if self.consume_char(',') {
617
9898433
            self.skip_ws()?;
618

            
619
9898433
            Ok(true)
620
        } else {
621
245788
            Ok(false)
622
        }
623
10144221
    }
624

            
625
    /// Only returns true if the char after `ident` cannot belong
626
    /// to an identifier.
627
221466164
    pub fn check_ident(&mut self, ident: &str) -> bool {
628
221466164
        self.check_str(ident) && !self.check_ident_other_char(ident.len())
629
221466164
    }
630

            
631
386777
    fn check_ident_other_char(&self, index: usize) -> bool {
632
386777
        self.src()[index..]
633
386777
            .chars()
634
386777
            .next()
635
386777
            .map_or(false, is_xid_continue)
636
386777
    }
637

            
638
    /// Check which type of struct we are currently parsing. The parsing state
639
    ///  is only changed in case of an error, to provide a better position.
640
    ///
641
    /// [`NewtypeMode::NoParensMeanUnit`] detects (tuple) structs by a leading
642
    ///  opening bracket and reports a unit struct otherwise.
643
    /// [`NewtypeMode::InsideNewtype`] skips an initial check for unit structs,
644
    ///  and means that any leading opening bracket is not considered to open
645
    ///  a (tuple) struct but to be part of the structs inner contents.
646
    ///
647
    /// [`TupleMode::ImpreciseTupleOrNewtype`] only performs a cheap, O(1),
648
    ///  single-identifier lookahead check to distinguish tuple structs from
649
    ///  non-tuple structs.
650
    /// [`TupleMode::DifferentiateNewtype`] performs an expensive, O(N), look-
651
    ///  ahead over the entire next value tree, which can span the entirety of
652
    ///  the remaining document in the worst case.
653
169724
    pub fn check_struct_type(
654
169724
        &mut self,
655
169724
        newtype: NewtypeMode,
656
169724
        tuple: TupleMode,
657
169724
    ) -> Result<StructType> {
658
169724
        fn check_struct_type_inner(
659
169724
            parser: &mut Parser,
660
169724
            newtype: NewtypeMode,
661
169724
            tuple: TupleMode,
662
169724
        ) -> Result<StructType> {
663
169724
            if matches!(newtype, NewtypeMode::NoParensMeanUnit) && !parser.consume_char('(') {
664
13024
                return Ok(StructType::Unit);
665
156700
            }
666

            
667
156700
            parser.skip_ws()?;
668

            
669
            // Check for `Ident()`, which could be
670
            // - a zero-field struct or tuple (variant)
671
            // - an unwrapped newtype around a unit
672
156700
            if matches!(newtype, NewtypeMode::NoParensMeanUnit) && parser.check_char(')') {
673
930
                return Ok(StructType::EmptyTuple);
674
155770
            }
675

            
676
155770
            if parser.skip_identifier().is_some() {
677
116052
                parser.skip_ws()?;
678

            
679
116052
                match parser.peek_char() {
680
                    // Definitely a struct with named fields
681
50634
                    Some(':') => return Ok(StructType::Named),
682
                    // Definitely a tuple-like struct with fields
683
                    Some(',') => {
684
3728
                        parser.skip_next_char();
685
3728
                        parser.skip_ws()?;
686
3728
                        if parser.check_char(')') {
687
                            // A one-element tuple could be a newtype
688
                            return Ok(StructType::NewtypeTuple);
689
3728
                        }
690
                        // Definitely a tuple struct with more than one field
691
3728
                        return Ok(StructType::NonNewtypeTuple);
692
                    }
693
                    // Either a newtype or a tuple struct
694
1240
                    Some(')') => return Ok(StructType::NewtypeTuple),
695
                    // Something else, let's investigate further
696
60450
                    Some(_) | None => (),
697
                };
698
39718
            }
699

            
700
100168
            if matches!(tuple, TupleMode::ImpreciseTupleOrNewtype) {
701
53343
                return Ok(StructType::AnyTuple);
702
46825
            }
703

            
704
46825
            let mut braces = 1_usize;
705
46825
            let mut more_than_one = false;
706

            
707
            // Skip ahead to see if the value is followed by another value
708
58181465
            while braces > 0 {
709
                // Skip spurious braces in comments, strings, and characters
710
58139615
                parser.skip_ws()?;
711
58139615
                let cursor_backup = parser.cursor;
712
58139615
                if parser.char().is_err() {
713
58137755
                    parser.set_cursor(cursor_backup);
714
58137755
                }
715
58139615
                let cursor_backup = parser.cursor;
716
58139615
                match parser.string() {
717
3410
                    Ok(_) => (),
718
                    // not a string, so backtrack
719
58134965
                    Err(Error::ExpectedString) => parser.set_cursor(cursor_backup),
720
                    // prevent quadratic complexity backtracking for malformed string,
721
                    // e.g. with an invalid escape or without a terminating quote
722
1240
                    Err(err) => return Err(err),
723
                }
724
58138375
                let cursor_backup = parser.cursor;
725
                // we have already checked for strings, which subsume base64 byte strings
726
58138375
                match parser.byte_string_no_base64() {
727
2790
                    Ok(_) => (),
728
                    // not a byte string, so backtrack
729
58134345
                    Err(Error::ExpectedByteString) => parser.set_cursor(cursor_backup),
730
                    // prevent quadratic complexity backtracking for malformed byte string,
731
                    // e.g. with an invalid escape or without a terminating quote
732
1240
                    Err(err) => return Err(err),
733
                }
734

            
735
                // Skip whitespace and comments directly after a skipped literal,
736
                // otherwise e.g. the `/*,*/` in `("a"/*,*/)` would be read as a comma
737
58137135
                parser.skip_ws()?;
738
58137135
                let c = parser.next_char()?;
739
58137120
                if matches!(c, '(' | '[' | '{') {
740
19380285
                    braces += 1;
741
38756835
                } else if matches!(c, ')' | ']' | '}') {
742
19422135
                    braces -= 1;
743
19422135
                } else if c == ',' && braces == 1 {
744
2480
                    parser.skip_ws()?;
745
2480
                    more_than_one = !parser.check_char(')');
746
2480
                    break;
747
19332220
                }
748
            }
749

            
750
44330
            if more_than_one {
751
930
                Ok(StructType::NonNewtypeTuple)
752
            } else {
753
43400
                Ok(StructType::NewtypeTuple)
754
            }
755
169724
        }
756

            
757
        // Create a temporary working copy
758
169724
        let backup_cursor = self.cursor;
759

            
760
169724
        let result = check_struct_type_inner(self, newtype, tuple);
761

            
762
169724
        if result.is_ok() {
763
167229
            // Revert the parser to before the struct type check
764
167229
            self.set_cursor(backup_cursor);
765
167229
        }
766

            
767
169724
        result
768
169724
    }
769

            
770
    /// Only returns true if the char after `ident` cannot belong
771
    /// to an identifier.
772
211006989
    pub fn consume_ident(&mut self, ident: &str) -> bool {
773
211006989
        if self.check_ident(ident) {
774
202934
            self.advance_bytes(ident.len());
775

            
776
202934
            true
777
        } else {
778
210804055
            false
779
        }
780
211006989
    }
781

            
782
107132
    pub fn consume_struct_name(&mut self, ident: &'static str) -> Result<bool> {
783
107132
        if self.check_ident("") {
784
87385
            if self.exts.contains(Extensions::EXPLICIT_STRUCT_NAMES) {
785
930
                return Err(Error::ExpectedStructName(ident.to_string()));
786
86455
            }
787

            
788
86455
            return Ok(false);
789
19747
        }
790

            
791
19747
        let found_ident = match self.identifier() {
792
17577
            Ok(maybe_ident) => maybe_ident,
793
1550
            Err(Error::SuggestRawIdentifier(found_ident)) if found_ident == ident => {
794
310
                return Err(Error::SuggestRawIdentifier(found_ident))
795
            }
796
1860
            Err(_) => return Err(Error::ExpectedNamedStructLike(ident)),
797
        };
798

            
799
17577
        if ident.is_empty() {
800
340
            return Err(Error::ExpectedNamedStructLike(ident));
801
17237
        }
802

            
803
17237
        if found_ident != ident {
804
1872
            return Err(Error::ExpectedDifferentStructName {
805
1872
                expected: ident,
806
1872
                found: String::from(found_ident),
807
1872
            });
808
15365
        }
809

            
810
15365
        Ok(true)
811
107132
    }
812

            
813
    /// Parse a document attribute at the current cursor position.
814
738370
    fn attribute(&mut self) -> Result<ParsedAttribute> {
815
738370
        if !self.check_char('#') {
816
689230
            return Ok(ParsedAttribute::None);
817
49140
        }
818

            
819
49140
        if !self.consume_all(&["#", "!", "["])? {
820
12
            return Err(Error::ExpectedAttribute);
821
49128
        }
822

            
823
49128
        self.skip_ws()?;
824
49128
        if self.consume_ident("enable") {
825
47232
            self.skip_ws()?;
826
47232
            if !self.consume_str("(") {
827
                return Err(Error::ExpectedAttribute);
828
47232
            }
829

            
830
47232
            self.skip_ws()?;
831
47232
            let extensions = self.extension_list()?;
832
46673
            self.skip_ws()?;
833

            
834
46673
            if self.consume_all(&[")", "]"])? {
835
46658
                Ok(ParsedAttribute::Extensions(extensions))
836
            } else {
837
15
                Err(Error::ExpectedAttributeEnd)
838
            }
839
1896
        } else if self.consume_ident("type") || self.consume_ident("schema") {
840
1896
            self.skip_ws()?;
841
1896
            if !self.consume_str("=") {
842
                return Err(Error::ExpectedAttribute);
843
1896
            }
844

            
845
1896
            self.skip_ws()?;
846
1896
            self.string()?;
847
1896
            self.skip_ws()?;
848

            
849
1896
            if self.consume_str("]") {
850
1896
                Ok(ParsedAttribute::Ignored)
851
            } else {
852
                Err(Error::ExpectedAttributeEnd)
853
            }
854
        } else {
855
            Err(Error::ExpectedAttribute)
856
        }
857
738370
    }
858

            
859
    /// Returns the extensions bit mask.
860
47232
    fn extension_list(&mut self) -> Result<Extensions> {
861
47232
        let mut extensions = Extensions::empty();
862

            
863
        loop {
864
47542
            let ident = self.identifier()?;
865
47542
            let extension = Extensions::from_ident(ident)
866
47542
                .ok_or_else(|| Error::NoSuchExtension(ident.into()))?;
867

            
868
47527
            extensions |= extension;
869

            
870
47527
            let comma = self.comma()?;
871

            
872
            // If we have no comma but another item, return an error
873
47527
            if !comma && self.check_ident_other_char(0) {
874
544
                return Err(Error::ExpectedComma);
875
46983
            }
876

            
877
            // If there's no comma, assume the list ended.
878
            // If there is, it might be a trailing one, thus we only
879
            // continue the loop if we get an ident char.
880
46983
            if !comma || !self.check_ident_other_char(0) {
881
46673
                break;
882
310
            }
883
        }
884

            
885
46673
        Ok(extensions)
886
47232
    }
887

            
888
9633759
    pub fn float<T: Float>(&mut self) -> Result<T> {
889
        const F32_SUFFIX: &str = "f32";
890
        const F64_SUFFIX: &str = "f64";
891

            
892
57798470
        for (literal, value_f32, value_f64) in &[
893
9633759
            ("inf", f32::INFINITY, f64::INFINITY),
894
9633759
            ("+inf", f32::INFINITY, f64::INFINITY),
895
9633759
            ("-inf", f32::NEG_INFINITY, f64::NEG_INFINITY),
896
9633759
            ("NaN", f32::NAN, f64::NAN),
897
9633759
            ("+NaN", f32::NAN, f64::NAN),
898
9633759
            ("-NaN", -f32::NAN, -f64::NAN),
899
9633759
        ] {
900
57798470
            if self.consume_ident(literal) {
901
1042
                return T::parse(literal);
902
57797428
            }
903

            
904
57797428
            if let Some(suffix) = self.src().strip_prefix(literal) {
905
1300
                if let Some(post_suffix) = suffix.strip_prefix(F32_SUFFIX) {
906
648
                    if !post_suffix.chars().next().map_or(false, is_xid_continue) {
907
644
                        let float_ron = &self.src()[..literal.len() + F32_SUFFIX.len()];
908
644
                        self.advance_bytes(literal.len() + F32_SUFFIX.len());
909
644
                        return T::try_from_parsed_float(ParsedFloat::F32(*value_f32), float_ron);
910
4
                    }
911
652
                }
912

            
913
656
                if let Some(post_suffix) = suffix.strip_prefix(F64_SUFFIX) {
914
648
                    if !post_suffix.chars().next().map_or(false, is_xid_continue) {
915
644
                        let float_ron = &self.src()[..literal.len() + F64_SUFFIX.len()];
916
644
                        self.advance_bytes(literal.len() + F64_SUFFIX.len());
917
644
                        return T::try_from_parsed_float(ParsedFloat::F64(*value_f64), float_ron);
918
4
                    }
919
8
                }
920
57796128
            }
921
        }
922

            
923
9631429
        let raw_bytes = self.next_chars_while_len(is_float_char);
924
9631429
        let src = &self.src()[..raw_bytes];
925
9631429
        let num_bytes = src.find("..").unwrap_or(raw_bytes);
926

            
927
9631429
        if num_bytes == 0 {
928
976
            return Err(Error::ExpectedFloat);
929
9630453
        }
930

            
931
9630453
        if self.check_char('_') {
932
4
            return Err(Error::UnderscoreAtBeginning);
933
9630449
        }
934

            
935
9630449
        let mut f = String::with_capacity(num_bytes);
936
9630449
        let mut allow_underscore = false;
937

            
938
86599377
        for (i, c) in self.src()[..num_bytes].char_indices() {
939
832
            match c {
940
824
                '_' if allow_underscore => continue,
941
                '_' => {
942
8
                    self.advance_bytes(i);
943
8
                    return Err(Error::FloatUnderscore);
944
                }
945
76968725
                '0'..='9' | 'e' | 'E' => allow_underscore = true,
946
9626103
                '.' => allow_underscore = false,
947
3717
                _ => (),
948
            }
949

            
950
            // we know that the byte is an ASCII character here
951
86598545
            f.push(c);
952
        }
953

            
954
9630441
        if self.src()[num_bytes..].starts_with('f') {
955
2214
            let backup_cursor = self.cursor;
956
2214
            self.advance_bytes(num_bytes);
957

            
958
            #[allow(clippy::never_loop)]
959
            loop {
960
2214
                let res = if self.consume_ident(F32_SUFFIX) {
961
1260
                    f32::from_str(&f).map(ParsedFloat::F32)
962
954
                } else if self.consume_ident(F64_SUFFIX) {
963
640
                    f64::from_str(&f).map(ParsedFloat::F64)
964
                } else {
965
314
                    break;
966
                };
967

            
968
1900
                let parsed = if let Ok(parsed) = res {
969
1892
                    parsed
970
                } else {
971
8
                    self.set_cursor(backup_cursor);
972
8
                    return Err(Error::ExpectedFloat);
973
                };
974

            
975
1892
                let float_ron = &self.src[backup_cursor.cursor..self.cursor.cursor];
976

            
977
1892
                return T::try_from_parsed_float(parsed, float_ron);
978
            }
979

            
980
314
            self.set_cursor(backup_cursor);
981
9628227
        }
982

            
983
9628541
        let value = T::parse(&f)?;
984

            
985
9628521
        self.advance_bytes(num_bytes);
986

            
987
9628521
        Ok(value)
988
9633759
    }
989

            
990
10469313
    pub fn skip_identifier(&mut self) -> Option<&'a str> {
991
        #[allow(clippy::nonminimal_bool)]
992
10469313
        if self.check_str("b\"") // byte string
993
10460315
            || self.check_str("b'") // byte literal
994
10219755
            || self.check_str("br#") // raw byte string
995
10218825
            || self.check_str("br\"") // raw byte string
996
10217895
            || self.check_str("r\"") // raw string
997
10217275
            || self.check_str("r#\"") // raw string
998
10216655
            || self.check_str("r##") // raw string
999
10216345
            || false
        {
252968
            return None;
10216345
        }
10216345
        if self.check_str("r#") {
            // maybe a raw identifier
942
            let len = self.next_chars_while_from_len(2, is_ident_raw_char);
942
            if len > 0 {
934
                let ident = &self.src()[2..2 + len];
934
                self.advance_bytes(2 + len);
934
                return Some(ident);
8
            }
8
            return None;
10215403
        }
10215403
        if let Some(c) = self.peek_char() {
            // maybe a normal identifier
10213853
            if is_ident_first_char(c) {
224885
                let len =
224885
                    c.len_utf8() + self.next_chars_while_from_len(c.len_utf8(), is_xid_continue);
224885
                let ident = &self.src()[..len];
224885
                self.advance_bytes(len);
224885
                return Some(ident);
9988968
            }
1550
        }
9990518
        None
10469313
    }
386486
    pub fn identifier(&mut self) -> Result<&'a str> {
386486
        let first = self.peek_char_or_eof()?;
386486
        if !is_ident_first_char(first) {
2492
            if is_ident_raw_char(first) {
1240
                let ident_bytes = self.next_chars_while_len(is_ident_raw_char);
1240
                return Err(Error::SuggestRawIdentifier(
1240
                    self.src()[..ident_bytes].into(),
1240
                ));
1252
            }
1252
            return Err(Error::ExpectedIdentifier);
383994
        }
        // If the next 2-3 bytes signify the start of a (raw) (byte) string
        //  literal, return an error.
        #[allow(clippy::nonminimal_bool)]
383994
        if self.check_str("b\"") // byte string
383684
            || self.check_str("b'") // byte literal
383374
            || self.check_str("br#") // raw byte string
383064
            || self.check_str("br\"") // raw byte string
382754
            || self.check_str("r\"") // raw string
382444
            || self.check_str("r#\"") // raw string
382134
            || self.check_str("r##") // raw string
381824
            || false
        {
2170
            return Err(Error::ExpectedIdentifier);
381824
        }
381824
        let length = if self.check_str("r#") {
8088
            let cursor_backup = self.cursor;
8088
            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.
8088
            if !matches!(self.peek_char(), Some(c) if is_ident_raw_char(c)) {
620
                self.set_cursor(cursor_backup);
620
                return Err(Error::ExpectedIdentifier);
7468
            }
7468
            self.next_chars_while_len(is_ident_raw_char)
373736
        } else if first == 'r' {
620
            let std_ident_length = self.next_chars_while_len(is_xid_continue);
620
            let raw_ident_length = self.next_chars_while_len(is_ident_raw_char);
620
            if raw_ident_length > std_ident_length {
310
                return Err(Error::SuggestRawIdentifier(
310
                    self.src()[..raw_ident_length].into(),
310
                ));
310
            }
310
            std_ident_length
        } else {
373116
            let std_ident_length = first.len_utf8()
373116
                + self.next_chars_while_from_len(first.len_utf8(), is_xid_continue);
373116
            let raw_ident_length = self.next_chars_while_len(is_ident_raw_char);
373116
            if raw_ident_length > std_ident_length {
930
                return Err(Error::SuggestRawIdentifier(
930
                    self.src()[..raw_ident_length].into(),
930
                ));
372186
            }
372186
            std_ident_length
        };
379964
        let ident = &self.src()[..length];
379964
        self.advance_bytes(length);
379964
        Ok(ident)
386486
    }
9985399
    pub fn next_bytes_is_float(&mut self) -> bool {
9985399
        if let Some(c) = self.peek_char() {
9985395
            let skip = match c {
7522
                '+' | '-' => 1,
9977873
                _ => 0,
            };
9985395
            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.
9985395
            let valid_float_len = self.src()[skip..][..raw_float_len]
9985395
                .find("..")
9985395
                .map_or(raw_float_len, |i| i.min(raw_float_len));
9985395
            let valid_int_len = self.next_chars_while_from_len(skip, is_int_char);
9985395
            valid_float_len > valid_int_len
        } else {
4
            false
        }
9985399
    }
150097708
    pub fn skip_ws(&mut self) -> Result<()> {
150097708
        if (self.cursor.last_ws_len != WS_CURSOR_UNCLOSED_LINE)
150097084
            && ((self.cursor.pre_ws_cursor + self.cursor.last_ws_len) < self.cursor.cursor)
80595212
        {
80595212
            // the last whitespace is disjoint from this one, we need to track a new one
80595212
            self.cursor.pre_ws_cursor = self.cursor.cursor;
80595212
        }
150097708
        if self.src().is_empty() {
576767
            return Ok(());
149520941
        }
        loop {
149571481
            self.advance_bytes(self.next_chars_while_len(is_whitespace_char));
149571481
            match self.skip_comment()? {
149515973
                None => break,
                Some(Comment::UnclosedLine) => {
3724
                    self.cursor.last_ws_len = WS_CURSOR_UNCLOSED_LINE;
3724
                    return Ok(());
                }
50540
                Some(Comment::ClosedLine | Comment::Block) => continue,
            }
        }
149515973
        self.cursor.last_ws_len = self.cursor.cursor - self.cursor.pre_ws_cursor;
149515973
        Ok(())
150097708
    }
49910
    pub fn has_unclosed_line_comment(&self) -> bool {
49910
        self.src().is_empty() && self.cursor.last_ws_len == WS_CURSOR_UNCLOSED_LINE
49910
    }
12758
    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
12758
        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),
            }
12750
        } 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 {
12738
            self.byte_string_no_base64()
        }
12758
    }
58151113
    pub fn byte_string_no_base64(&mut self) -> Result<ParsedByteStr<'a>> {
58151113
        if self.consume_str("b\"") {
12428
            self.escaped_byte_string()
58138685
        } else if self.consume_str("br") {
4340
            self.raw_byte_string()
        } else {
58134345
            Err(Error::ExpectedByteString)
        }
58151113
    }
12428
    fn escaped_byte_string(&mut self) -> Result<ParsedByteStr<'a>> {
12428
        match self.escaped_byte_buf(EscapeEncoding::Binary) {
10568
            Ok((bytes, advance)) => {
10568
                self.advance_bytes(advance);
10568
                Ok(bytes)
            }
1860
            Err(err) => Err(err),
        }
12428
    }
4340
    fn raw_byte_string(&mut self) -> Result<ParsedByteStr<'a>> {
4340
        match self.raw_byte_buf() {
3720
            Ok((bytes, advance)) => {
3720
                self.advance_bytes(advance);
3720
                Ok(bytes)
            }
310
            Err(Error::ExpectedString) => Err(Error::ExpectedByteString),
310
            Err(err) => Err(err),
        }
4340
    }
58255267
    pub fn string(&mut self) -> Result<ParsedStr<'a>> {
58255267
        if self.consume_char('"') {
113418
            self.escaped_string()
58141849
        } else if self.consume_char('r') {
5012
            self.raw_string()
        } else {
58136837
            Err(Error::ExpectedString)
        }
58255267
    }
113426
    fn escaped_string(&mut self) -> Result<ParsedStr<'a>> {
113426
        match self.escaped_byte_buf(EscapeEncoding::Utf8) {
109381
            Ok((bytes, advance)) => {
109381
                let string = ParsedStr::try_from_bytes(bytes).map_err(Error::from)?;
109381
                self.advance_bytes(advance);
109381
                Ok(string)
            }
4045
            Err(err) => Err(err),
        }
113426
    }
5024
    fn raw_string(&mut self) -> Result<ParsedStr<'a>> {
5024
        match self.raw_byte_buf() {
4400
            Ok((bytes, advance)) => {
4400
                let string = ParsedStr::try_from_bytes(bytes).map_err(Error::from)?;
4400
                self.advance_bytes(advance);
4400
                Ok(string)
            }
624
            Err(err) => Err(err),
        }
5024
    }
125854
    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
125854
        let str_end = self.src().find('"').ok_or(Error::ExpectedStringEnd)?;
124909
        let escape = self.src()[..str_end].find('\\');
124909
        if let Some(escape) = escape {
            // Now check if escaping is used inside the string
22360
            let mut i = escape;
22360
            let mut s = self.src().as_bytes()[..i].to_vec();
            loop {
55782760
                self.advance_bytes(i + 1);
55782760
                if !self.consume_string_continuation() {
55780280
                    match self.parse_escape(encoding, false)? {
55757022
                        EscapeCharacter::Ascii(c) => s.push(c),
18298
                        EscapeCharacter::Utf8(c) => match c.len_utf8() {
13330
                            1 => s.push(c as u8),
4968
                            len => {
4968
                                let start = s.len();
4968
                                s.extend(core::iter::repeat(0).take(len));
4968
                                c.encode_utf8(&mut s[start..]);
4968
                            }
                        },
                    }
2480
                }
                // 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.
55777800
                let next = self
55777800
                    .src()
55777800
                    .find(['"', '\\'])
55777800
                    .ok_or(Error::ExpectedStringEnd)?;
55777800
                s.extend_from_slice(&self.src().as_bytes()[..next]);
                // `next` indexes an ASCII byte, so byte indexing is valid here.
55777800
                if self.src().as_bytes()[next] == b'\\' {
55760400
                    i = next;
55760400
                } else {
                    // Advance to the end of the string + 1 for the `"`.
17400
                    break Ok((ParsedByteStr::Allocated(s), next + 1));
                }
            }
        } else {
102549
            let s = &self.src().as_bytes()[..str_end];
            // Advance by the number of bytes of the string + 1 for the `"`.
102549
            Ok((ParsedByteStr::Slice(s), str_end + 1))
        }
125854
    }
    /// 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.
55782760
    fn consume_string_continuation(&mut self) -> bool {
55782760
        let line_ending_len = if self.check_str("\r\n") {
620
            2
55782140
        } else if self.check_char('\n') {
1860
            1
        } else {
55780280
            return false;
        };
2480
        self.advance_bytes(line_ending_len);
2480
        let whitespace = self.next_chars_while_len(is_string_continuation_whitespace);
2480
        self.advance_bytes(whitespace);
2480
        true
55782760
    }
9364
    fn raw_byte_buf(&mut self) -> Result<(ParsedByteStr<'a>, usize)> {
18096
        let num_hashes = self.next_chars_while_len(|c| c == '#');
9364
        let hashes = &self.src()[..num_hashes];
9364
        self.advance_bytes(num_hashes);
9364
        self.expect_char('"', Error::ExpectedString)?;
8740
        let ending = ["\"", hashes].concat();
8740
        let i = self.src().find(&ending).ok_or(Error::ExpectedStringEnd)?;
8120
        let s = &self.src().as_bytes()[..i];
        // Advance by the number of bytes of the byte string
        // + `num_hashes` + 1 for the `"`.
8120
        Ok((ParsedByteStr::Slice(s), i + num_hashes + 1))
9364
    }
219294
    fn decode_ascii_escape(&mut self) -> Result<u8> {
219294
        let mut n = 0;
219294
        for _ in 0..2 {
438588
            n <<= 4;
438588
            let byte = self.next_char()?;
438588
            let decoded = Self::decode_hex(byte)?;
437968
            n |= decoded;
        }
218674
        Ok(n)
219294
    }
    #[inline]
1110734
    fn decode_hex(c: char) -> Result<u8> {
1110734
        if !c.is_ascii() {
310
            return Err(Error::InvalidEscape("Non-hex digit found"));
1110424
        }
        // c is an ASCII character that can be losslessly cast to u8
1110424
        match c as u8 {
1110114
            c @ b'0'..=b'9' => Ok(c - b'0'),
128714
            c @ b'a'..=b'f' => Ok(10 + c - b'a'),
63240
            c @ b'A'..=b'F' => Ok(10 + c - b'A'),
310
            _ => Err(Error::InvalidEscape("Non-hex digit found")),
        }
1110734
    }
55997292
    fn parse_escape(&mut self, encoding: EscapeEncoding, is_char: bool) -> Result<EscapeCharacter> {
55997292
        let c = match self.next_char()? {
2802
            '\'' => EscapeCharacter::Ascii(b'\''),
7694534
            '"' => EscapeCharacter::Ascii(b'"'),
3720
            '\\' => EscapeCharacter::Ascii(b'\\'),
48053410
            'n' => EscapeCharacter::Ascii(b'\n'),
620
            'r' => EscapeCharacter::Ascii(b'\r'),
1240
            't' => EscapeCharacter::Ascii(b'\t'),
2480
            '0' => EscapeCharacter::Ascii(b'\0'),
            'x' => {
                // Fast exit for ascii escape in byte string
215856
                let b: u8 = self.decode_ascii_escape()?;
215236
                if let EscapeEncoding::Binary = encoding {
212128
                    return Ok(EscapeCharacter::Ascii(b));
3108
                }
                // Fast exit for ascii character in UTF-8 string
3108
                let mut bytes = [b, 0, 0, 0];
3108
                if let Ok(Some(c)) = from_utf8(&bytes[..=0]).map(|s| s.chars().next()) {
930
                    return Ok(EscapeCharacter::Utf8(c));
2178
                }
2178
                if is_char {
                    // Character literals are not allowed to use multiple byte
                    //  escapes to build a unicode character
310
                    return Err(Error::InvalidEscape(
310
                        "Not a valid byte-escaped Unicode character",
310
                    ));
1868
                }
                // UTF-8 character needs up to four bytes and we have already
                //  consumed one, so at most three to go
4674
                for i in 1..4 {
4674
                    if !self.consume_str(r"\x") {
1240
                        return Err(Error::InvalidEscape(
1240
                            "Not a valid byte-escaped Unicode character",
1240
                        ));
3434
                    }
3434
                    bytes[i] = self.decode_ascii_escape()?;
                    // Check if we now have a valid UTF-8 character
3434
                    if let Ok(Some(c)) = from_utf8(&bytes[..=i]).map(|s| s.chars().next()) {
318
                        return Ok(EscapeCharacter::Utf8(c));
3116
                    }
                }
310
                return Err(Error::InvalidEscape(
310
                    "Not a valid byte-escaped Unicode character",
310
                ));
            }
            'u' => {
18910
                self.expect_char('{', Error::InvalidEscape("Missing { in Unicode escape"))?;
18910
                let mut bytes: u32 = 0;
18910
                let mut num_digits = 0;
57350
                while num_digits < 6 {
57350
                    let byte = self.peek_char_or_eof()?;
57350
                    if byte == '}' {
18910
                        break;
38440
                    }
38440
                    self.skip_next_char();
38440
                    num_digits += 1;
38440
                    let byte = Self::decode_hex(byte)?;
38440
                    bytes <<= 4;
38440
                    bytes |= u32::from(byte);
                }
18910
                if num_digits == 0 {
310
                    return Err(Error::InvalidEscape(
310
                        "Expected 1-6 digits, got 0 digits in Unicode escape",
310
                    ));
18600
                }
18600
                self.expect_char(
                    '}',
18600
                    Error::InvalidEscape("No } at the end of Unicode escape"),
                )?;
18600
                let c = char_from_u32(bytes).ok_or(Error::InvalidEscape(
18600
                    "Not a valid Unicode-escaped character",
18600
                ))?;
18600
                EscapeCharacter::Utf8(c)
            }
3720
            _ => return Err(Error::InvalidEscape("Unknown escape character")),
        };
55777406
        Ok(c)
55997292
    }
149571481
    fn skip_comment(&mut self) -> Result<Option<Comment>> {
149571481
        if self.consume_char('/') {
55508
            match self.next_char()? {
                '/' => {
231776
                    let bytes = self.next_chars_while_len(|c| c != '\n');
22636
                    self.advance_bytes(bytes);
22636
                    if self.src().is_empty() {
3724
                        Ok(Some(Comment::UnclosedLine))
                    } else {
18912
                        Ok(Some(Comment::ClosedLine))
                    }
                }
                '*' => {
32562
                    let mut level = 1;
72250
                    while level > 0 {
257642
                        let bytes = self.next_chars_while_len(|c| !matches!(c, '/' | '*'));
40622
                        if self.src().is_empty() {
314
                            return Err(Error::UnclosedBlockComment);
40308
                        }
40308
                        self.advance_bytes(bytes);
                        // check whether / or * and take action
40308
                        if self.consume_str("/*") {
2170
                            level += 1;
38138
                        } else if self.consume_str("*/") {
33798
                            level -= 1;
33798
                        } else {
4340
                            self.next_char().map_err(|_| Error::UnclosedBlockComment)?;
                        }
                    }
31628
                    Ok(Some(Comment::Block))
                }
310
                c => Err(Error::UnexpectedChar(c)),
            }
        } else {
149515973
            Ok(None)
        }
149571481
    }
}
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 {
1541513
            fn from_u8(x: u8) -> Self {
82156
                x as $ty
1541513
            }
634644
            fn checked_mul_ext(&mut self, x: u8) -> bool {
634644
                match self.checked_mul(Self::from_u8(x)) {
633706
                    Some(n) => {
633706
                        *self = n;
633706
                        false
                    }
938
                    None => true,
                }
634644
            }
525212
            fn checked_add_ext(&mut self, x: u8) -> bool {
525212
                match self.checked_add(Self::from_u8(x)) {
524747
                    Some(n) => {
524747
                        *self = n;
524747
                        false
                    }
465
                    None => true,
                }
525212
            }
105394
            fn checked_sub_ext(&mut self, x: u8) -> bool {
105394
                match self.checked_sub(Self::from_u8(x)) {
102294
                    Some(n) => {
102294
                        *self = n;
102294
                        false
                    }
3100
                    None => true,
                }
105394
            }
        }
    };
    ($($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 {
128353
            fn parse(parser: &mut Parser, sign: i8, base: u8) -> Result<Self> {
128353
                parser.parse_integer(sign, base)
128353
            }
37820
            fn try_from_parsed_integer(parsed: ParsedInteger, ron: &str) -> Result<Self> {
37820
                match parsed {
13950
                    ParsedInteger::$wrap(v) => Ok(v),
                    _ => Err(Error::InvalidValueForType {
23870
                        expected: format!(
                            "a{} {}-bit {}signed integer",
23870
                            if <$ty>::BITS == 8 { "n" } else { "" },
                            <$ty>::BITS,
23870
                            if <$ty>::MIN == 0 { "un" } else { "" },
                        ),
23870
                        found: String::from(ron),
                    }),
                }
37820
            }
        }
    };
    ($($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 {
110118
    fn parse(parser: &mut Parser, sign: i8, base: u8) -> Result<Self> {
110118
        if sign < 0 {
3770
            let signed = parser.parse_integer::<LargeSInt>(-1, base)?;
1266
            return if let Ok(x) = i8::try_from(signed) {
942
                Ok(ParsedInteger::I8(x))
324
            } else if let Ok(x) = i16::try_from(signed) {
4
                Ok(ParsedInteger::I16(x))
320
            } 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")]
314
                if let Ok(x) = i64::try_from(signed) {
2
                    Ok(ParsedInteger::I64(x))
                } else {
312
                    Ok(ParsedInteger::I128(signed))
                }
            };
106348
        }
106348
        let unsigned = parser.parse_integer::<LargeUInt>(1, base)?;
104631
        if let Ok(x) = u8::try_from(unsigned) {
103683
            Ok(ParsedInteger::U8(x))
948
        } else if let Ok(x) = u16::try_from(unsigned) {
318
            Ok(ParsedInteger::U16(x))
630
        } 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")]
624
            if let Ok(x) = u64::try_from(unsigned) {
2
                Ok(ParsedInteger::U64(x))
            } else {
622
                Ok(ParsedInteger::U128(unsigned))
            }
        }
110118
    }
246760
    fn try_from_parsed_integer(parsed: ParsedInteger, _ron: &str) -> Result<Self> {
246760
        Ok(parsed)
246760
    }
}
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 {
44633
            fn parse(float: &str) -> Result<Self> {
44633
                <$ty>::from_str(float).map_err(|_| Error::ExpectedFloat)
44633
            }
6200
            fn try_from_parsed_float(parsed: ParsedFloat, ron: &str) -> Result<Self> {
6200
                match parsed {
5580
                    ParsedFloat::$wrap(v) => Ok(v),
620
                    _ => Err(Error::InvalidValueForType {
620
                        expected: format!(
620
                            "a {}-bit floating point number", $bits,
620
                        ),
620
                        found: String::from(ron),
620
                    }),
                }
6200
            }
        }
    };
    ($($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 {
9628708
    fn parse(float: &str) -> Result<Self> {
9628708
        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.
9628708
        if value.is_nan() {
322
            let nan = if value.is_sign_negative() {
318
                -f32::NAN
            } else {
4
                f32::NAN
            };
322
            return Ok(ParsedFloat::F32(nan));
9628386
        }
        #[allow(clippy::cast_possible_truncation)]
9628386
        if value.total_cmp(&f64::from(value as f32)).is_eq() {
9984
            Ok(ParsedFloat::F32(value as f32))
        } else {
9618402
            Ok(ParsedFloat::F64(value))
        }
9628708
    }
3100
    fn try_from_parsed_float(parsed: ParsedFloat, _ron: &str) -> Result<Self> {
3100
        Ok(parsed)
3100
    }
}
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> {
113781
    pub fn try_from_bytes(bytes: ParsedByteStr<'a>) -> Result<Self, Utf8Error> {
113781
        match bytes {
13660
            ParsedByteStr::Allocated(byte_buf) => Ok(ParsedStr::Allocated(
13660
                String::from_utf8(byte_buf).map_err(|e| e.utf8_error())?,
            )),
100121
            ParsedByteStr::Slice(bytes) => Ok(ParsedStr::Slice(from_utf8(bytes)?)),
        }
113781
    }
}
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
    }
}