lexical_parse_integer/
algorithm.rs

1//! Radix-generic, optimized, string-to-integer conversion routines.
2//!
3//! These routines are highly optimized: they use various optimizations
4//! to read multiple digits at-a-time with less multiplication instructions,
5//! as well as other optimizations to avoid unnecessary compile-time branching.
6//!
7//! See [Algorithm.md](/docs/Algorithm.md) for a more detailed description of
8//! the algorithm choice here. See [Benchmarks.md](/docs/Benchmarks.md) for
9//! recent benchmark data.
10//!
11//! These allow implementations of partial and complete parsers
12//! using a single code-path via macros.
13//!
14//! This looks relatively, complex, but it's quite simple. Almost all
15//! of these branches are resolved at compile-time, so the resulting
16//! code is quite small while handling all of the internal complexity.
17//!
18//! 1. Helpers to process ok and error results for both complete and partial
19//!    parsers. They have different APIs, and mixing the APIs leads to
20//!    substantial performance hits.
21//! 2. Overflow checking on invalid digits for partial parsers, while just
22//!    returning invalid digits for complete parsers.
23//! 3. A format-aware sign parser.
24//! 4. Digit parsing algorithms which explicitly wrap on overflow, for no
25//!    additional overhead. This has major performance wins for **most**
26//!    real-world integers, so most valid input will be substantially faster.
27//! 5. An algorithm to detect if overflow occurred. This is comprehensive, and
28//!    short-circuits for common cases.
29//! 6. A parsing algorithm for unsigned integers, always producing positive
30//!    values. This avoids any unnecessary branching.
31//! 7. Multi-digit optimizations for larger sizes.
32
33#![doc(hidden)]
34
35use lexical_util::digit::char_to_digit_const;
36use lexical_util::error::Error;
37use lexical_util::format::NumberFormat;
38use lexical_util::iterator::{AsBytes, Bytes, DigitsIter, Iter};
39use lexical_util::num::{as_cast, Integer};
40use lexical_util::result::Result;
41
42use crate::Options;
43
44// HELPERS
45
46/// Check if we should do multi-digit optimizations
47const fn can_try_parse_multidigits<'a, Iter: DigitsIter<'a>, const FORMAT: u128>(_: &Iter) -> bool {
48    let format = NumberFormat::<FORMAT> {};
49    Iter::IS_CONTIGUOUS && (cfg!(not(feature = "power-of-two")) || format.mantissa_radix() <= 10)
50}
51
52// Get if digits are required for the format.
53#[cfg_attr(not(feature = "format"), allow(unused_macros))]
54macro_rules! required_digits {
55    () => {
56        NumberFormat::<FORMAT>::REQUIRED_INTEGER_DIGITS
57            || NumberFormat::<FORMAT>::REQUIRED_MANTISSA_DIGITS
58    };
59}
60
61/// Return an value for a complete parser.
62macro_rules! into_ok_complete {
63    ($value:expr, $index:expr, $count:expr) => {{
64        #[cfg(not(feature = "format"))]
65        return Ok(as_cast($value));
66
67        #[cfg(feature = "format")]
68        if required_digits!() && $count == 0 {
69            into_error!(Empty, $index);
70        } else {
71            return Ok(as_cast($value));
72        }
73    }};
74}
75
76/// Return an value and index for a partial parser.
77macro_rules! into_ok_partial {
78    ($value:expr, $index:expr, $count:expr) => {{
79        #[cfg(not(feature = "format"))]
80        return Ok((as_cast($value), $index));
81
82        #[cfg(feature = "format")]
83        if required_digits!() && $count == 0 {
84            into_error!(Empty, $index);
85        } else {
86            return Ok((as_cast($value), $index));
87        }
88    }};
89}
90
91/// Return an error for a complete parser upon an invalid digit.
92macro_rules! invalid_digit_complete {
93    ($value:expr, $index:expr, $count:expr) => {
94        // Don't do any overflow checking here: we don't need it.
95        into_error!(InvalidDigit, $index - 1)
96    };
97}
98
99/// Return a value for a partial parser upon an invalid digit.
100/// This checks for numeric overflow, and returns the appropriate error.
101macro_rules! invalid_digit_partial {
102    ($value:expr, $index:expr, $count:expr) => {
103        // NOTE: The value is already positive/negative
104        into_ok_partial!($value, $index - 1, $count)
105    };
106}
107
108/// Return an error, returning the index and the error.
109macro_rules! into_error {
110    ($code:ident, $index:expr) => {{
111        return Err(Error::$code($index));
112    }};
113}
114
115/// Handle an invalid digit if the format feature is enabled.
116///
117/// This is because we can have special, non-digit characters near
118/// the start or internally. If `$is_end` is set to false, there **MUST**
119/// be elements in the underlying slice after the current iterator.
120#[cfg(feature = "format")]
121macro_rules! fmt_invalid_digit {
122    (
123        $value:ident, $iter:ident, $c:expr, $start_index:ident, $invalid_digit:ident, $is_end:expr
124    ) => {{
125        // NOTE: If we have non-contiguous iterators, we could have a skip character
126        // here at the boundary. This does not affect safety but it does affect
127        // correctness.
128        debug_assert!($iter.is_contiguous() || $is_end);
129
130        let base_suffix = NumberFormat::<FORMAT>::BASE_SUFFIX;
131        let uncased_base_suffix = NumberFormat::<FORMAT>::CASE_SENSITIVE_BASE_SUFFIX;
132        // Need to check for a base suffix, if so, return a valid value.
133        // We can't have a base suffix at the first value (need at least
134        // 1 digit).
135        if base_suffix != 0 && $iter.cursor() - $start_index > 1 {
136            let is_suffix = if uncased_base_suffix {
137                $c == base_suffix
138            } else {
139                $c.eq_ignore_ascii_case(&base_suffix)
140            };
141            // NOTE: If we're using the `take_n` optimization where it can't
142            // be the end, then the iterator cannot be done. So, in that case,
143            // we need to end. `take_n` also can never be used for non-
144            // contiguous iterators.
145            if is_suffix && $is_end && $iter.is_buffer_empty() {
146                // Break out of the loop, we've finished parsing.
147                break;
148            } else if !$iter.is_buffer_empty() {
149                // Haven't finished parsing, so we're going to call
150                // `invalid_digit!`. Need to ensure we include the
151                // base suffix in that.
152
153                // SAFETY: safe since the iterator is not empty, as checked
154                // in `$iter.is_buffer_empty()`. Adding in the check hopefully
155                // will be elided since it's a known constant.
156                unsafe { $iter.step_unchecked() };
157            }
158        }
159        // Might have handled our base-prefix here.
160        $invalid_digit!($value, $iter.cursor(), $iter.current_count())
161    }};
162}
163
164/// Just return an invalid digit
165#[cfg(not(feature = "format"))]
166macro_rules! fmt_invalid_digit {
167    (
168        $value:ident, $iter:ident, $c:expr, $start_index:ident, $invalid_digit:ident, $is_end:expr
169    ) => {{
170        $invalid_digit!($value, $iter.cursor(), $iter.current_count());
171    }};
172}
173
174/// Parse the sign from the leading digits.
175///
176/// This routine does the following:
177///
178/// 1. Parses the sign digit.
179/// 2. Handles if positive signs before integers are not allowed.
180/// 3. Handles negative signs if the type is unsigned.
181/// 4. Handles if the sign is required, but missing.
182/// 5. Handles if the iterator is empty, before or after parsing the sign.
183/// 6. Handles if the iterator has invalid, leading zeros.
184///
185/// Returns if the value is negative, or any values detected when
186/// validating the input.
187#[macro_export]
188macro_rules! parse_sign {
189    (
190        $byte:ident,
191        $is_signed:expr,
192        $no_positive:expr,
193        $required:expr,
194        $invalid_positive:ident,
195        $missing:ident
196    ) => {
197        // NOTE: `read_if` optimizes poorly since we then match after
198        match $byte.integer_iter().first() {
199            Some(&b'+') if !$no_positive => {
200                // SAFETY: We have at least 1 item left since we peaked a value
201                unsafe { $byte.step_unchecked() };
202                Ok(false)
203            },
204            Some(&b'+') if $no_positive => Err(Error::$invalid_positive($byte.cursor())),
205            Some(&b'-') if $is_signed => {
206                // SAFETY: We have at least 1 item left since we peaked a value
207                unsafe { $byte.step_unchecked() };
208                Ok(true)
209            },
210            Some(_) if $required => Err(Error::$missing($byte.cursor())),
211            _ if $required => Err(Error::$missing($byte.cursor())),
212            _ => Ok(false),
213        }
214    };
215}
216
217/// Parse the sign from the leading digits.
218#[cfg_attr(not(feature = "compact"), inline(always))]
219pub fn parse_sign<T: Integer, const FORMAT: u128>(byte: &mut Bytes<'_, FORMAT>) -> Result<bool> {
220    let format = NumberFormat::<FORMAT> {};
221    parse_sign!(
222        byte,
223        T::IS_SIGNED,
224        format.no_positive_mantissa_sign(),
225        format.required_mantissa_sign(),
226        InvalidPositiveSign,
227        MissingSign
228    )
229}
230
231// FOUR DIGITS
232
233/// Determine if 4 bytes, read raw from bytes, are 4 digits for the radix.
234#[cfg_attr(not(feature = "compact"), inline(always))]
235pub fn is_4digits<const FORMAT: u128>(v: u32) -> bool {
236    let radix = NumberFormat::<{ FORMAT }>::MANTISSA_RADIX;
237    debug_assert!(radix <= 10);
238
239    // We want to have a wrapping add and sub such that only values from the
240    // range `[0x30, 0x39]` (or narrower for custom radixes) will not
241    // overflow into the high bit. This means that the value needs to overflow
242    // into into `0x80` if the digit is 1 above, or `0x46` for the value `0x39`.
243    // Likewise, we only valid for `[0x30, 0x38]` for radix 8, so we need
244    // `0x47`.
245    let add = 0x46 + 10 - radix;
246    let add = add + (add << 8) + (add << 16) + (add << 24);
247    // This aims to underflow if anything is below the min digit: if we have any
248    // values under `0x30`, then this underflows and wraps into the high bit.
249    let sub = 0x3030_3030;
250    let a = v.wrapping_add(add);
251    let b = v.wrapping_sub(sub);
252
253    (a | b) & 0x8080_8080 == 0
254}
255
256/// Parse 4 bytes read from bytes into 4 digits.
257#[cfg_attr(not(feature = "compact"), inline(always))]
258pub fn parse_4digits<const FORMAT: u128>(mut v: u32) -> u32 {
259    let radix = NumberFormat::<{ FORMAT }>::MANTISSA_RADIX;
260    debug_assert!(radix <= 10);
261
262    // Normalize our digits to the range `[0, 9]`.
263    v -= 0x3030_3030;
264    // Scale digits in `0 <= Nn <= 99`.
265    v = (v * radix) + (v >> 8);
266    // Scale digits in `0 <= Nnnn <= 9999`.
267    v = ((v & 0x0000007f) * radix * radix) + ((v >> 16) & 0x0000007f);
268
269    v
270}
271
272/// Use a fast-path optimization, where we attempt to parse 4 digits at a time.
273/// This reduces the number of multiplications necessary to 2, instead of 4.
274///
275/// This approach is described in full here:
276/// <https://johnnylee-sde.github.io/Fast-numeric-string-to-int/>
277#[cfg_attr(not(feature = "compact"), inline(always))]
278pub fn try_parse_4digits<'a, T, Iter, const FORMAT: u128>(iter: &mut Iter) -> Option<T>
279where
280    T: Integer,
281    Iter: DigitsIter<'a>,
282{
283    // Can't do fast optimizations with radixes larger than 10, since
284    // we no longer have a contiguous ASCII block. Likewise, cannot
285    // use non-contiguous iterators.
286    debug_assert!(NumberFormat::<{ FORMAT }>::MANTISSA_RADIX <= 10);
287    debug_assert!(Iter::IS_CONTIGUOUS);
288
289    // Read our digits, validate the input, and check from there.
290    let bytes = u32::from_le(iter.peek_u32()?);
291    if is_4digits::<FORMAT>(bytes) {
292        // SAFETY: safe since we have at least 4 bytes in the buffer.
293        unsafe { iter.step_by_unchecked(4) };
294        Some(T::as_cast(parse_4digits::<FORMAT>(bytes)))
295    } else {
296        None
297    }
298}
299
300// EIGHT DIGITS
301
302/// Determine if 8 bytes, read raw from bytes, are 8 digits for the radix.
303/// See `is_4digits` for the algorithm description.
304#[cfg_attr(not(feature = "compact"), inline(always))]
305pub fn is_8digits<const FORMAT: u128>(v: u64) -> bool {
306    let radix = NumberFormat::<{ FORMAT }>::MANTISSA_RADIX;
307    debug_assert!(radix <= 10);
308
309    let add = 0x46 + 10 - radix;
310    let add = add + (add << 8) + (add << 16) + (add << 24);
311    let add = (add as u64) | ((add as u64) << 32);
312    // This aims to underflow if anything is below the min digit: if we have any
313    // values under `0x30`, then this underflows and wraps into the high bit.
314    let sub = 0x3030_3030_3030_3030;
315    let a = v.wrapping_add(add);
316    let b = v.wrapping_sub(sub);
317
318    (a | b) & 0x8080_8080_8080_8080 == 0
319}
320
321/// Parse 8 bytes read from bytes into 8 digits.
322/// Credit for this goes to @aqrit, which further optimizes the
323/// optimization described by Johnny Lee above.
324#[cfg_attr(not(feature = "compact"), inline(always))]
325pub fn parse_8digits<const FORMAT: u128>(mut v: u64) -> u64 {
326    let radix = NumberFormat::<{ FORMAT }>::MANTISSA_RADIX as u64;
327    debug_assert!(radix <= 10);
328
329    // Create our masks. Assume the optimizer will do this at compile time.
330    // It seems like an optimizing compiler **will** do this, so we
331    // should be safe.
332    let radix2 = radix * radix;
333    let radix4 = radix2 * radix2;
334    let radix6 = radix2 * radix4;
335    let mask = 0x0000_00FF_0000_00FFu64;
336    let mul1 = radix2 + (radix6 << 32);
337    let mul2 = 1 + (radix4 << 32);
338
339    // Normalize our digits to the base.
340    v -= 0x3030_3030_3030_3030;
341    // Scale digits in `0 <= Nn <= 99`.
342    v = (v * radix) + (v >> 8);
343    let v1 = (v & mask).wrapping_mul(mul1);
344    let v2 = ((v >> 16) & mask).wrapping_mul(mul2);
345
346    ((v1.wrapping_add(v2) >> 32) as u32) as u64
347}
348
349/// Use a fast-path optimization, where we attempt to parse 8 digits at a time.
350/// This reduces the number of multiplications necessary to 3, instead of 8.
351#[cfg_attr(not(feature = "compact"), inline(always))]
352pub fn try_parse_8digits<'a, T, Iter, const FORMAT: u128>(iter: &mut Iter) -> Option<T>
353where
354    T: Integer,
355    Iter: DigitsIter<'a>,
356{
357    // Can't do fast optimizations with radixes larger than 10, since
358    // we no longer have a contiguous ASCII block. Likewise, cannot
359    // use non-contiguous iterators.
360    debug_assert!(NumberFormat::<{ FORMAT }>::MANTISSA_RADIX <= 10);
361    debug_assert!(Iter::IS_CONTIGUOUS);
362
363    // Read our digits, validate the input, and check from there.
364    let bytes = u64::from_le(iter.peek_u64()?);
365    if is_8digits::<FORMAT>(bytes) {
366        // SAFETY: safe since we have at least 8 bytes in the buffer.
367        unsafe { iter.step_by_unchecked(8) };
368        Some(T::as_cast(parse_8digits::<FORMAT>(bytes)))
369    } else {
370        None
371    }
372}
373
374// ONE DIGIT
375
376/// Run a loop where the integer cannot possibly overflow.
377///
378/// If the length of the str is short compared to the range of the type
379/// we are parsing into, then we can be certain that an overflow will not occur.
380/// This bound is when `radix.pow(digits.len()) - 1 <= T::MAX` but the condition
381/// above is a faster (conservative) approximation of this.
382///
383/// Consider radix 16 as it has the highest information density per digit and
384/// will thus overflow the earliest: `u8::MAX` is `ff` - any str of length 2 is
385/// guaranteed to not overflow. `i8::MAX` is `7f` - only a str of length 1 is
386/// guaranteed to not overflow.
387///
388/// This is based off of [core/num](core).
389///
390/// * `value` - The current parsed value.
391/// * `iter` - An iterator over all bytes in the input.
392/// * `add_op` - The unchecked add/sub op.
393/// * `start_index` - The offset where parsing started.
394/// * `invalid_digit` - Behavior when an invalid digit is found.
395/// * `is_end` - If iter corresponds to the full input.
396///
397/// core: <https://doc.rust-lang.org/1.81.0/src/core/num/mod.rs.html#1480>
398macro_rules! parse_1digit_unchecked {
399    (
400        $value:ident,
401        $iter:ident,
402        $add_op:ident,
403        $start_index:ident,
404        $invalid_digit:ident,
405        $is_end:expr
406    ) => {{
407        // This is a slower parsing algorithm, going 1 digit at a time, but doing it in
408        // an unchecked loop.
409        let radix = NumberFormat::<FORMAT>::MANTISSA_RADIX;
410        while let Some(&c) = $iter.next() {
411            let digit = match char_to_digit_const(c, radix) {
412                Some(v) => v,
413                None => fmt_invalid_digit!($value, $iter, c, $start_index, $invalid_digit, $is_end),
414            };
415            // multiply first since compilers are good at optimizing things out and will do
416            // a fused mul/add We must do this after getting the digit for
417            // partial parsers
418            $value = $value.wrapping_mul(as_cast(radix)).$add_op(as_cast(digit));
419        }
420    }};
421}
422
423/// Run a loop where the integer could overflow.
424///
425/// This is a standard, unoptimized algorithm. This is based off of
426/// [core/num](core)
427///
428/// * `value` - The current parsed value.
429/// * `iter` - An iterator over all bytes in the input.
430/// * `add_op` - The checked add/sub op.
431/// * `start_index` - The offset where parsing started.
432/// * `invalid_digit` - Behavior when an invalid digit is found.
433/// * `overflow` - If the error is overflow or underflow.
434///
435/// core: <https://doc.rust-lang.org/1.81.0/src/core/num/mod.rs.html#1505>
436macro_rules! parse_1digit_checked {
437    (
438        $value:ident,
439        $iter:ident,
440        $add_op:ident,
441        $start_index:ident,
442        $invalid_digit:ident,
443        $overflow:ident
444    ) => {{
445        // This is a slower parsing algorithm, going 1 digit at a time, but doing it in
446        // an unchecked loop.
447        let radix = NumberFormat::<FORMAT>::MANTISSA_RADIX;
448        while let Some(&c) = $iter.next() {
449            let digit = match char_to_digit_const(c, radix) {
450                Some(v) => v,
451                None => fmt_invalid_digit!($value, $iter, c, $start_index, $invalid_digit, true),
452            };
453            // multiply first since compilers are good at optimizing things out and will do
454            // a fused mul/add
455            $value =
456                match $value.checked_mul(as_cast(radix)).and_then(|x| x.$add_op(as_cast(digit))) {
457                    Some(value) => value,
458                    None => into_error!($overflow, $iter.cursor() - 1),
459                }
460        }
461    }};
462}
463
464// OVERALL DIGITS
465// --------------
466
467/// Run an unchecked loop where digits are processed incrementally.
468///
469/// If the type size is small or there's not many digits, skip multi-digit
470/// optimizations. Otherwise, if the type size is large and we're not manually
471/// skipping manual optimizations, then we do this here.
472///
473/// * `value` - The current parsed value.
474/// * `iter` - An iterator over all bytes in the input.
475/// * `add_op` - The unchecked add/sub op.
476/// * `start_index` - The offset where parsing started.
477/// * `invalid_digit` - Behavior when an invalid digit is found.
478/// * `no_multi_digit` - If to disable multi-digit optimizations.
479/// * `is_end` - If iter corresponds to the full input.
480macro_rules! parse_digits_unchecked {
481    (
482        $value:ident,
483        $iter:ident,
484        $add_op:ident,
485        $start_index:ident,
486        $invalid_digit:ident,
487        $no_multi_digit:expr,
488        $is_end:expr
489    ) => {{
490        let can_multi = can_try_parse_multidigits::<_, FORMAT>(&$iter);
491        let use_multi = can_multi && !$no_multi_digit;
492
493        // these cannot overflow. also, we use at most 3 for a 128-bit float and 1 for a
494        // 64-bit float NOTE: Miri will complain about this if we use radices >=
495        // 16 but since they won't go into `try_parse_8digits!` or
496        // `try_parse_4digits` it will be optimized out and the overflow won't
497        // matter.
498        let format = NumberFormat::<FORMAT> {};
499        if use_multi && T::BITS >= 64 && $iter.buffer_length() >= 8 {
500            // Try our fast, 8-digit at a time optimizations.
501            let radix8 = T::from_u32(format.radix8());
502            while let Some(value) = try_parse_8digits::<T, _, FORMAT>(&mut $iter) {
503                $value = $value.wrapping_mul(radix8).$add_op(value);
504            }
505        } else if use_multi && T::BITS == 32 && $iter.buffer_length() >= 4 {
506            // Try our fast, 8-digit at a time optimizations.
507            let radix4 = T::from_u32(format.radix4());
508            while let Some(value) = try_parse_4digits::<T, _, FORMAT>(&mut $iter) {
509                $value = $value.wrapping_mul(radix4).$add_op(value);
510            }
511        }
512        parse_1digit_unchecked!($value, $iter, $add_op, $start_index, $invalid_digit, $is_end)
513    }};
514}
515
516/// Run  checked loop where digits are processed with overflow checking.
517///
518/// If the type size is small or there's not many digits, skip multi-digit
519/// optimizations. Otherwise, if the type size is large and we're not manually
520/// skipping manual optimizations, then we do this here.
521///
522/// * `value` - The current parsed value.
523/// * `iter` - An iterator over all bytes in the input.
524/// * `add_op` - The checked add/sub op.
525/// * `add_op_uc` - The unchecked add/sub op for small digit optimizations.
526/// * `start_index` - The offset where parsing started.
527/// * `invalid_digit` - Behavior when an invalid digit is found.
528/// * `overflow` - If the error is overflow or underflow.
529/// * `no_multi_digit` - If to disable multi-digit optimizations.
530/// * `overflow_digits` - The number of digits before we need to consider
531///   checked ops.
532macro_rules! parse_digits_checked {
533    (
534        $value:ident,
535        $iter:ident,
536        $add_op:ident,
537        $add_op_uc:ident,
538        $start_index:ident,
539        $invalid_digit:ident,
540        $overflow:ident,
541        $no_multi_digit:expr,
542        $overflow_digits:expr
543    ) => {{
544        // Can use the unchecked for the `max_digits` here. If we
545        // have a non-contiguous iterator, we could have a case like
546        // 123__456, with no consecutive digit separators allowed. If
547        // it's broken between the `_` characters, the integer will be
548        // seen as valid when it isn't.
549        if cfg!(not(feature = "format")) || $iter.is_contiguous() {
550            if let Some(mut small) = $iter.take_n($overflow_digits) {
551                let mut small_iter = small.integer_iter();
552                parse_digits_unchecked!(
553                    $value,
554                    small_iter,
555                    $add_op_uc,
556                    $start_index,
557                    $invalid_digit,
558                    $no_multi_digit,
559                    false
560                );
561            }
562        }
563
564        // NOTE: all our multi-digit optimizations have been done here: skip this
565        parse_1digit_checked!($value, $iter, $add_op, $start_index, $invalid_digit, $overflow)
566    }};
567}
568
569// ALGORITHM
570
571/// Generic algorithm for both partial and complete parsers.
572///
573/// * `invalid_digit` - Behavior on finding an invalid digit.
574/// * `into_ok` - Behavior when returning a valid value.
575/// * `invalid_digit` - Behavior when an invalid digit is found.
576/// * `no_multi_digit` - If to disable multi-digit optimizations.
577/// * `is_partial` - If the parser is a partial parser.
578#[rustfmt::skip]
579macro_rules! algorithm {
580($bytes:ident, $into_ok:ident, $invalid_digit:ident, $no_multi_digit:expr) => {{
581    // WARNING:
582    // --------
583    // None of this code can be changed for optimization reasons.
584    // Do not change it without benchmarking every change.
585    //  1. You cannot use the `NoSkipIterator` in the loop,
586    //      you must either return a subslice (indexing)
587    //      or increment outside of the loop.
588    //      Failing to do so leads to numerous more, unnecessary
589    //      conditional move instructions, killing performance.
590    //  2. Return a 0 or 1 shift, and indexing unchecked outside
591    //      of the loop is slightly faster.
592    //  3. Partial and complete parsers cannot be efficiently done
593    //      together.
594    //
595    // If you try to refactor without carefully monitoring benchmarks or
596    // assembly generation, please log the number of wasted hours: so
597    //  16 hours so far.
598
599    // With `step_by_unchecked`, this is sufficiently optimized.
600    // Removes conditional paths, to, which simplifies maintenance.
601    // The skip version of the iterator automatically coalesces to
602    // the no-skip iterator.
603    let mut byte = $bytes.bytes::<FORMAT>();
604    let radix = NumberFormat::<FORMAT>::MANTISSA_RADIX;
605
606    let is_negative = parse_sign::<T, FORMAT>(&mut byte)?;
607    let mut iter = byte.integer_iter();
608    if iter.is_buffer_empty() {
609        // Our default format **ALWAYS** requires significant digits, however,
610        // we can have cases where we don
611        #[cfg(not(feature = "format"))]
612        into_error!(Empty, iter.cursor());
613
614        #[cfg(feature = "format")]
615        if required_digits!() {
616            into_error!(Empty, iter.cursor());
617        } else {
618            $into_ok!(T::ZERO, iter.cursor(), 0)
619        }
620    }
621
622    // Feature-gate a lot of format-only code here to simplify analysis with our branching
623    // We only want to skip the zeros if have either require a base prefix or we don't
624    // allow integer leading zeros, since the skip is expensive
625    #[allow(unused_variables, unused_mut)]
626    let mut start_index = iter.cursor();
627    #[cfg_attr(not(feature = "format"), allow(unused_variables))]
628    let format = NumberFormat::<FORMAT> {};
629    #[cfg(feature = "format")]
630    if format.has_base_prefix() || format.no_integer_leading_zeros() {
631        // Skip any leading zeros. We want to do our check if it can't possibly overflow after.
632        // For skipping digit-based formats, this approximation is a way over estimate.
633        // NOTE: Skipping zeros is **EXPENSIVE* so we skip that without our format feature
634        let zeros = iter.skip_zeros();
635        start_index += zeros;
636
637        // Now, check to see if we have a valid base prefix.
638        let mut is_prefix = false;
639        let base_prefix = format.base_prefix();
640        if base_prefix != 0 && zeros == 1 {
641            // Check to see if the next character is the base prefix.
642            // We must have a format like `0x`, `0d`, `0o`. Note:
643            if iter.read_if_value(base_prefix, format.case_sensitive_base_prefix()).is_some() {
644                is_prefix = true;
645                if iter.is_buffer_empty() {
646                    into_error!(Empty, iter.cursor());
647                } else {
648                    start_index += 1;
649                }
650            }
651        }
652
653        // If we have a format that doesn't accept leading zeros,
654        // check if the next value is invalid. It's invalid if the
655        // first is 0, and the next is not a valid digit.
656        if !is_prefix && format.no_integer_leading_zeros() && zeros != 0 {
657            // Cannot have a base prefix and no leading zeros.
658            let index = iter.cursor() - zeros;
659            if zeros > 1 {
660                into_error!(InvalidLeadingZeros, index);
661            }
662            // NOTE: Zeros has to be 0 here, so our index == 1 or 2 (depending on sign)
663            match iter.peek().map(|&c| char_to_digit_const(c, format.radix())) {
664                // Valid digit, we have an invalid value.
665                Some(Some(_)) => into_error!(InvalidLeadingZeros, index),
666                // Have a non-digit character that follows.
667                Some(None) => $invalid_digit!(<T>::ZERO, iter.cursor() + 1, iter.current_count()),
668                // No digits following, has to be ok
669                None => $into_ok!(<T>::ZERO, index, iter.current_count()),
670            };
671        }
672    }
673
674    // shorter strings cannot possibly overflow so a great optimization
675    let overflow_digits = T::overflow_digits(radix);
676    let cannot_overflow = iter.as_slice().len() <= overflow_digits;
677
678    //  NOTE:
679    //      Don't add optimizations for 128-bit integers.
680    //      128-bit multiplication is rather efficient, it's only division
681    //      that's very slow. Any shortcut optimizations increasing branching,
682    //      and even if parsing a 64-bit integer is marginally faster, it
683    //      culminates in **way** slower performance overall for simple
684    //      integers, and no improvement for large integers.
685    let mut value = T::ZERO;
686    if cannot_overflow && is_negative {
687        parse_digits_unchecked!(value, iter, wrapping_sub, start_index, $invalid_digit, $no_multi_digit, true);
688    } if cannot_overflow {
689        parse_digits_unchecked!(value, iter, wrapping_add, start_index, $invalid_digit, $no_multi_digit, true);
690    } else if is_negative {
691        parse_digits_checked!(value, iter, checked_sub, wrapping_sub, start_index, $invalid_digit, Underflow, $no_multi_digit, overflow_digits);
692    } else {
693        parse_digits_checked!(value, iter, checked_add, wrapping_add, start_index, $invalid_digit, Overflow, $no_multi_digit, overflow_digits);
694    }
695
696    $into_ok!(value, iter.buffer_length(), iter.current_count())
697}};
698}
699
700/// Algorithm for the complete parser.
701#[cfg_attr(not(feature = "compact"), inline(always))]
702pub fn algorithm_complete<T, const FORMAT: u128>(bytes: &[u8], options: &Options) -> Result<T>
703where
704    T: Integer,
705{
706    algorithm!(bytes, into_ok_complete, invalid_digit_complete, options.get_no_multi_digit())
707}
708
709/// Algorithm for the partial parser.
710#[cfg_attr(not(feature = "compact"), inline(always))]
711pub fn algorithm_partial<T, const FORMAT: u128>(
712    bytes: &[u8],
713    options: &Options,
714) -> Result<(T, usize)>
715where
716    T: Integer,
717{
718    algorithm!(bytes, into_ok_partial, invalid_digit_partial, options.get_no_multi_digit())
719}