Skip to main content

core/num/imp/dec2flt/
parse.rs

1//! Functions to parse floating-point numbers.
2
3use dec2flt::common::{ByteSlice, is_8digits};
4use dec2flt::decimal::Decimal;
5
6use crate::num::imp::{Float, dec2flt};
7
8const MIN_19DIGIT_INT: u64 = 100_0000_0000_0000_0000;
9
10/// Parse 8 digits, loaded as bytes in little-endian order.
11///
12/// This uses the trick where every digit is in [0x030, 0x39],
13/// and therefore can be parsed in 3 multiplications, much
14/// faster than the normal 8.
15///
16/// This is based off the algorithm described in "Fast numeric string to
17/// int", available here: <https://johnnylee-sde.github.io/Fast-numeric-string-to-int/>.
18fn parse_8digits(mut v: u64) -> u64 {
19    const MASK: u64 = 0x0000_00FF_0000_00FF;
20    const MUL1: u64 = 0x000F_4240_0000_0064;
21    const MUL2: u64 = 0x0000_2710_0000_0001;
22    v -= 0x3030_3030_3030_3030;
23    v = (v * 10) + (v >> 8); // will not overflow, fits in 63 bits
24    let v1 = (v & MASK).wrapping_mul(MUL1);
25    let v2 = ((v >> 16) & MASK).wrapping_mul(MUL2);
26    ((v1.wrapping_add(v2) >> 32) as u32) as u64
27}
28
29/// Parse digits until a non-digit character is found.
30fn try_parse_digits(mut s: &[u8], mut x: u64) -> (&[u8], u64) {
31    // may cause overflows, to be handled later
32
33    while s.len() >= 8 {
34        let num = s.read_u64();
35        if is_8digits(num) {
36            x = x.wrapping_mul(1_0000_0000).wrapping_add(parse_8digits(num));
37            s = &s[8..];
38        } else {
39            break;
40        }
41    }
42
43    s = s.parse_digits(|digit| {
44        x = x.wrapping_mul(10).wrapping_add(digit as _);
45    });
46
47    (s, x)
48}
49
50/// Parse up to 19 digits (the max that can be stored in a 64-bit integer).
51fn try_parse_19digits(s_ref: &mut &[u8], x: &mut u64) {
52    let mut s = *s_ref;
53
54    while *x < MIN_19DIGIT_INT {
55        if let Some((c, s_next)) = s.split_first() {
56            let digit = c.wrapping_sub(b'0');
57
58            if digit < 10 {
59                *x = (*x * 10) + digit as u64; // no overflows here
60                s = s_next;
61            } else {
62                break;
63            }
64        }