trivet 3.1.0

The trivet Parser Library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
// Trivet
// Copyright (c) 2025 by Stacy Prowell.  All rights reserved.
// https://gitlab.com/binary-tools/trivet

//! Faster parsing of numbers with fewer options.  If you want more configurability,
//! see [`crate::numbers::NumberParser`].
//!
//! Specific functions are provided that parse the next `u128`, `i128`, `u64`, `i64`,
//! or `f64` value given an instance of [`crate::ParserCore`].  You would use these instead
//! of invoking the method of the same name in [`crate::Parser`].

use crate::errors::{syntax_error, ParseResult};
use crate::ParserCore;

/// Read a possibly-signed integer from the stream at the current location and compute
/// and return an `i128` value.  Every alphanumeric character is treated as if it is part
/// of the number.  Underscores may be permitted in the number; that can be specified by
/// the `allow_underscores` flag.
///
/// Number radices are read and processed here.  The arguments allow excluding any radices
/// you do not want to permit.  Note that we don't generate an error saying that, say,
/// "octal is not permitted," we just treat the 'o' as an illegal digit.
///
/// **This method does not allow you to change the radix specifiers!**  The default radix
/// specifiers are always used, if enabled, with the default radix being decimal.  This is
/// *subject to change* so do not rely on this!
///
/// |Prefix  |Radix       |
/// |--------|------------|
/// |`0b`    |Binary      |
/// |`0o`    |Octal       |
/// |`0x`    |Hexadecimal |
///
/// If an optional radix is provided, it must be 2, 8, 10, or 16 (it isn't checked here).
/// In that case no radix indicator is checked or permitted.
///
/// Errors are generated if an unexpected alphanumeric character is encountered during
/// parsing.  The first non-alphanumeric stops the parse.
pub fn parse_i128(parser: &mut ParserCore) -> ParseResult<i128> {
    // Deal with any leading minus sign.
    let negative = parser.peek_and_consume('-');
    let mut base = 10u32;
    let mut digits = false;
    let mut nonzero_pending = true;
    let mut value = 0i128;
    let mut fail_mul;
    let mut fail_add;
    let mut fail = false;

    let accumulate = if negative {
        i128::overflowing_sub
    } else {
        i128::overflowing_add
    };

    // Look for a radix indicator.
    if parser.peek_and_consume('0') {
        // This could be a radix indicator, or it could be a zero.  Check for the radix
        // indicator and if not found, assume it is just a leading zero.
        match parser.peek() {
            'x' => {
                // Hexadecimal radix.
                parser.consume();
                base = 16;
            }
            'o' => {
                // Octal radix.
                parser.consume();
                base = 8;
            }
            'b' => {
                // Binary radix.
                parser.consume();
                base = 2;
            }
            _ => {
                // The leading zero counts as a digit.
                digits = true;
            }
        }
    }

    // Now we have the radix and we might have also processed a digit.  Process all
    // alphanumerics until we encounter a non-alphanumeric character or we encounter
    // an error.
    while !parser.is_at_eof() {
        // Get next potential digit and convert it to the numeric value.  Note that
        // underscores do not count as digits.
        let ch = parser.peek();
        if ch == '_' {
            parser.consume();
            continue;
        }
        let mut dig = value as u32;
        if (0x30..=0x39).contains(&dig) {
            dig -= 0x30;
        } else if (0x41..0x5B).contains(&(dig & 0xdf)) {
            dig = (dig & 0xdf) - 0x37;
        } else {
            // Not alphanumeric.
            break;
        }
        digits = true;

        // If the digit is larger than the base, reject with an error.
        if dig >= base {
            return Err(syntax_error(
                parser.loc(),
                &format!("The digit '{}' is invalid for base {}.", ch, base),
            ));
        }

        // Consume the digit now.
        parser.consume();

        // Accumulate it.  The first non-zero digit is handled differently from
        // subsequent digits.  We discard leading zeros.
        if nonzero_pending {
            if dig > 0 {
                // This is the first non-zero digit.
                if negative {
                    value = -(dig as i128);
                } else {
                    value = dig as i128;
                }
                nonzero_pending = false;
            }
        } else {
            (value, fail_mul) = value.overflowing_mul(base as i128);
            (value, fail_add) = accumulate(value, dig as i128);
            fail = fail || fail_mul || fail_add;
        }
    }

    // If we overflowed (or underflowed) during accumulation, issue an error now.
    if fail {
        return Err(syntax_error(
            parser.loc(),
            "Integer value out of bounds for i64",
        ));
    }

    // If we didn't get any digits, then reject with an error.
    if digits == false {
        return Err(syntax_error(
            parser.loc(),
            "Expected a number but found no valid digits.",
        ));
    }
    Ok(value)
}

/// Read an unsigned from the stream at the current location and compute
/// and return a `u128` value.  Every alphanumeric character is treated as if it is part
/// of the number.  Underscores may be permitted in the number; that can be specified by
/// the `allow_underscores` flag.
///
/// Number radices are read and processed here.  The arguments allow excluding any radices
/// you do not want to permit.  Note that we don't generate an error saying that, say,
/// "octal is not permitted," we just treat the 'o' as an illegal digit.
///
/// **This method does not allow you to change the radix specifiers!**  The default radix
/// specifiers are always used, if enabled, with the default radix being decimal.  This is
/// *subject to change* so do not rely on this!
///
/// |Prefix  |Radix       |
/// |--------|------------|
/// |`0b`    |Binary      |
/// |`0o`    |Octal       |
/// |`0x`    |Hexadecimal |
///
/// If an optional radix is provided, it must be 2, 8, 10, or 16 (it isn't checked here).
/// In that case no radix indicator is checked or permitted.
///
/// Errors are generated if an unexpected alphanumeric character is encountered during
/// parsing.  The first non-alphanumeric stops the parse.
pub fn parse_u128(parser: &mut ParserCore) -> ParseResult<u128> {
    let mut base = 10u32;
    let mut digits = false;
    let mut nonzero_pending = true;
    let mut value = 0u128;
    let mut fail_mul;
    let mut fail_add;
    let mut fail = false;

    // Look for a radix indicator.
    if parser.peek_and_consume('0') {
        // This could be a radix indicator, or it could be a zero.  Check for the radix
        // indicator and if not found, assume it is just a leading zero.
        match parser.peek() {
            'x' => {
                // Hexadecimal radix.
                parser.consume();
                base = 16;
            }
            'o' => {
                // Octal radix.
                parser.consume();
                base = 8;
            }
            'b' => {
                // Binary radix.
                parser.consume();
                base = 2;
            }
            _ => {
                // The leading zero counts as a digit.
                digits = true;
            }
        }
    }

    // Now we have the radix and we might have also processed a digit.  Process all
    // alphanumerics until we encounter a non-alphanumeric character or we encounter
    // an error.
    while !parser.is_at_eof() {
        // Get next potential digit and convert it to the numeric value.  Note that
        // underscores do not count as digits.
        let ch = parser.peek();
        let mut dig = value as u32;
        if (0x30..=0x39).contains(&dig) {
            dig -= 0x30;
        } else if (0x41..0x5B).contains(&(dig & 0xdf)) {
            dig = (dig & 0xdf) - 0x37;
        } else {
            // Not alphanumeric.
            break;
        }
        digits = true;

        // If the digit is larger than the base, reject with an error.
        if dig >= base {
            return Err(syntax_error(
                parser.loc(),
                &format!("The digit '{}' is invalid for base {}.", ch, base),
            ));
        }

        // Consume the digit now.
        parser.consume();

        // Accumulate it.  The first non-zero digit is handled differently from
        // subsequent digits.
        if nonzero_pending {
            if dig > 0 {
                // This is the first non-zero digit.
                value = dig as u128;
                nonzero_pending = false;
            }
        } else {
            // Accumulate the value and keep track of overflows.
            (value, fail_mul) = value.overflowing_mul(base as u128);
            (value, fail_add) = value.overflowing_add(dig as u128);
            fail = fail || fail_mul || fail_add;
        }
    }

    // Report any overflow.
    if fail {
        return Err(syntax_error(
            parser.loc(),
            "Integer value too large for u64",
        ));
    }

    // If we didn't get any digits, then reject with an error.
    if digits == false {
        return Err(syntax_error(
            parser.loc(),
            "Expected a number but found no valid digits",
        ));
    }
    Ok(value)
}

/// Read a possibly-signed integer from the stream at the current location and compute
/// and return an `i64` value.  Every alphanumeric character is treated as if it is part
/// of the number.  Underscores may be permitted in the number; that can be specified by
/// the `allow_underscores` flag.
///
/// Number radices are read and processed here.  The arguments allow excluding any radices
/// you do not want to permit.  Note that we don't generate an error saying that, say,
/// "octal is not permitted," we just treat the 'o' as an illegal digit.
///
/// **This method does not allow you to change the radix specifiers!**  The default radix
/// specifiers are always used, if enabled, with the default radix being decimal.  This is
/// *subject to change* so do not rely on this!
///
/// |Prefix  |Radix       |
/// |--------|------------|
/// |`0b`    |Binary      |
/// |`0o`    |Octal       |
/// |`0x`    |Hexadecimal |
///
/// If an optional radix is provided, it must be 2, 8, 10, or 16 (it isn't checked here).
/// In that case no radix indicator is checked or permitted.
///
/// Errors are generated if an unexpected alphanumeric character is encountered during
/// parsing.  The first non-alphanumeric stops the parse.
pub fn parse_i64(parser: &mut ParserCore) -> ParseResult<i64> {
    // Deal with any leading minus sign.
    let negative = parser.peek_and_consume('-');
    let mut base = 10u32;
    let mut digits = false;
    let mut nonzero_pending = true;
    let mut value = 0i64;
    let mut fail_mul;
    let mut fail_add;
    let mut fail = false;

    let accumulate = if negative {
        i64::overflowing_sub
    } else {
        i64::overflowing_add
    };

    // Look for a radix indicator.
    if parser.peek_and_consume('0') {
        // This could be a radix indicator, or it could be a zero.  Check for the radix
        // indicator and if not found, assume it is just a leading zero.
        match parser.peek() {
            'x' => {
                // Hexadecimal radix.
                parser.consume();
                base = 16;
            }
            'o' => {
                // Octal radix.
                parser.consume();
                base = 8;
            }
            'b' => {
                // Binary radix.
                parser.consume();
                base = 2;
            }
            _ => {
                // The leading zero counts as a digit.
                digits = true;
            }
        }
    }

    // Now we have the radix and we might have also processed a digit.  Process all
    // alphanumerics until we encounter a non-alphanumeric character or we encounter
    // an error.
    while !parser.is_at_eof() {
        // Get next potential digit and convert it to the numeric value.  Note that
        // underscores do not count as digits.
        let ch = parser.peek();
        if ch == '_' {
            parser.consume();
            continue;
        }
        let mut dig = value as u32;
        if (0x30..=0x39).contains(&dig) {
            dig -= 0x30;
        } else if (0x41..0x5B).contains(&(dig & 0xdf)) {
            dig = (dig & 0xdf) - 0x37;
        } else {
            // Not alphanumeric.
            break;
        }
        digits = true;

        // If the digit is larger than the base, reject with an error.
        if dig >= base {
            return Err(syntax_error(
                parser.loc(),
                &format!("The digit '{}' is invalid for base {}.", ch, base),
            ));
        }

        // Consume the digit now.
        parser.consume();

        // Accumulate it.  The first non-zero digit is handled differently from
        // subsequent digits.  We discard leading zeros.
        if nonzero_pending {
            if dig > 0 {
                // This is the first non-zero digit.
                if negative {
                    value = -(dig as i64);
                } else {
                    value = dig as i64;
                }
                nonzero_pending = false;
            }
        } else {
            (value, fail_mul) = value.overflowing_mul(base as i64);
            (value, fail_add) = accumulate(value, dig as i64);
            fail = fail || fail_mul || fail_add;
        }
    }

    // If we overflowed (or underflowed) during accumulation, issue an error now.
    if fail {
        return Err(syntax_error(
            parser.loc(),
            "Integer value out of bounds for i64",
        ));
    }

    // If we didn't get any digits, then reject with an error.
    if digits == false {
        return Err(syntax_error(
            parser.loc(),
            "Expected a number but found no valid digits.",
        ));
    }
    Ok(value)
}

/// Read an unsigned from the stream at the current location and compute
/// and return a `u64` value.  Every alphanumeric character is treated as if it is part
/// of the number.  Underscores may be permitted in the number; that can be specified by
/// the `allow_underscores` flag.
///
/// Number radices are read and processed here.  The arguments allow excluding any radices
/// you do not want to permit.  Note that we don't generate an error saying that, say,
/// "octal is not permitted," we just treat the 'o' as an illegal digit.
///
/// **This method does not allow you to change the radix specifiers!**  The default radix
/// specifiers are always used, if enabled, with the default radix being decimal.  This is
/// *subject to change* so do not rely on this!
///
/// |Prefix  |Radix       |
/// |--------|------------|
/// |`0b`    |Binary      |
/// |`0o`    |Octal       |
/// |`0x`    |Hexadecimal |
///
/// If an optional radix is provided, it must be 2, 8, 10, or 16 (it isn't checked here).
/// In that case no radix indicator is checked or permitted.
///
/// Errors are generated if an unexpected alphanumeric character is encountered during
/// parsing.  The first non-alphanumeric stops the parse.
pub fn parse_u64(parser: &mut ParserCore) -> ParseResult<u64> {
    let mut base = 10u32;
    let mut digits = false;
    let mut nonzero_pending = true;
    let mut value = 0u64;
    let mut fail_mul;
    let mut fail_add;
    let mut fail = false;

    // Look for a radix indicator.
    if parser.peek_and_consume('0') {
        // This could be a radix indicator, or it could be a zero.  Check for the radix
        // indicator and if not found, assume it is just a leading zero.
        match parser.peek() {
            'x' => {
                // Hexadecimal radix.
                parser.consume();
                base = 16;
            }
            'o' => {
                // Octal radix.
                parser.consume();
                base = 8;
            }
            'b' => {
                // Binary radix.
                parser.consume();
                base = 2;
            }
            _ => {
                // The leading zero counts as a digit.
                digits = true;
            }
        }
    }

    // Now we have the radix and we might have also processed a digit.  Process all
    // alphanumerics until we encounter a non-alphanumeric character or we encounter
    // an error.
    while !parser.is_at_eof() {
        // Get next potential digit and convert it to the numeric value.  Note that
        // underscores do not count as digits.
        let ch = parser.peek();
        let mut dig = value as u32;
        if (0x30..=0x39).contains(&dig) {
            dig -= 0x30;
        } else if (0x41..0x5B).contains(&(dig & 0xdf)) {
            dig = (dig & 0xdf) - 0x37;
        } else {
            // Not alphanumeric.
            break;
        }
        digits = true;

        // If the digit is larger than the base, reject with an error.
        if dig >= base {
            return Err(syntax_error(
                parser.loc(),
                &format!("The digit '{}' is invalid for base {}.", ch, base),
            ));
        }

        // Consume the digit now.
        parser.consume();

        // Accumulate it.  The first non-zero digit is handled differently from
        // subsequent digits.
        if nonzero_pending {
            if dig > 0 {
                // This is the first non-zero digit.
                value = dig as u64;
                nonzero_pending = false;
            }
        } else {
            // Accumulate the value and keep track of overflows.
            (value, fail_mul) = value.overflowing_mul(base as u64);
            (value, fail_add) = value.overflowing_add(dig as u64);
            fail = fail || fail_mul || fail_add;
        }
    }

    // Report any overflow.
    if fail {
        return Err(syntax_error(
            parser.loc(),
            "Integer value too large for u64",
        ));
    }

    // If we didn't get any digits, then reject with an error.
    if digits == false {
        return Err(syntax_error(
            parser.loc(),
            "Expected a number but found no valid digits",
        ));
    }
    Ok(value)
}

/// Parse a floating point number.  This only reads decimal numbers, and radix indicators are not
/// permitted.  Parsing stops at the first non-float character (so not in [0-9.eE]).  The Rust
/// parsing method is used to generate the f64 at the end of the parse, and an error will be
/// returned if this cannot be done.
pub fn parse_f64_decimal(parser: &mut ParserCore) -> ParseResult<f64> {
    let loc = parser.loc();
    let mut text = String::new();
    if parser.peek_and_consume('-') {
        text.push('-');
    }
    let digits = parser.take_while(|ch| ch.is_ascii_digit() || ch == '.' || ch == 'e' || ch == 'E');
    text.push_str(&digits);
    match text.parse::<f64>() {
        Err(err) => Err(syntax_error(loc, &err.to_string())),
        Ok(value) => Ok(value),
    }
}