| 1 | use crate::common::AdjustedMantissa; |
| 2 | use crate::decimal::{parse_decimal, Decimal}; |
| 3 | use crate::float::Float; |
| 4 | |
| 5 | #[inline] |
| 6 | pub fn parse_long_mantissa<F: Float>(s: &[u8]) -> AdjustedMantissa { |
| 7 | const MAX_SHIFT: usize = 60; |
| 8 | const NUM_POWERS: usize = 19; |
| 9 | const POWERS: [u8; 19] = |
| 10 | [0, 3, 6, 9, 13, 16, 19, 23, 26, 29, 33, 36, 39, 43, 46, 49, 53, 56, 59]; |
| 11 | |
| 12 | let get_shift = |n| { |
| 13 | if n < NUM_POWERS { |
| 14 | POWERS[n] as usize |
| 15 | } else { |
| 16 | MAX_SHIFT |
| 17 | } |
| 18 | }; |
| 19 | |
| 20 | let am_zero = AdjustedMantissa::zero_pow2(0); |
| 21 | let am_inf = AdjustedMantissa::zero_pow2(F::INFINITE_POWER); |
| 22 | |
| 23 | let mut d = parse_decimal(s); |
| 24 | |
| 25 | if d.num_digits == 0 || d.decimal_point < -324 { |
| 26 | return am_zero; |
| 27 | } else if d.decimal_point >= 310 { |
| 28 | return am_inf; |
| 29 | } |
| 30 | let mut exp2 = 0_i32; |
| 31 | while d.decimal_point > 0 { |
| 32 | let n = d.decimal_point as usize; |
| 33 | let shift = get_shift(n); |
| 34 | d.right_shift(shift); |
| 35 | if d.decimal_point < -Decimal::DECIMAL_POINT_RANGE { |
| 36 | return am_zero; |
| 37 | } |
| 38 | exp2 += shift as i32; |
| 39 | } |
| 40 | while d.decimal_point <= 0 { |
| 41 | let shift = if d.decimal_point == 0 { |
| 42 | match d.digits[0] { |
| 43 | digit if digit >= 5 => break, |
| 44 | 0 | 1 => 2, |
| 45 | _ => 1, |
| 46 | } |
| 47 | } else { |
| 48 | get_shift((-d.decimal_point) as usize) |
| 49 | }; |
| 50 | d.left_shift(shift); |
| 51 | if d.decimal_point > Decimal::DECIMAL_POINT_RANGE { |
| 52 | return am_inf; |
| 53 | } |
| 54 | exp2 -= shift as i32; |
| 55 | } |
| 56 | exp2 -= 1; |
| 57 | while (F::MINIMUM_EXPONENT + 1) > exp2 { |
| 58 | let mut n = ((F::MINIMUM_EXPONENT + 1) - exp2) as usize; |
| 59 | if n > MAX_SHIFT { |
| 60 | n = MAX_SHIFT; |
| 61 | } |
| 62 | d.right_shift(n); |
| 63 | exp2 += n as i32; |
| 64 | } |
| 65 | if (exp2 - F::MINIMUM_EXPONENT) >= F::INFINITE_POWER { |
| 66 | return am_inf; |
| 67 | } |
| 68 | d.left_shift(F::MANTISSA_EXPLICIT_BITS + 1); |
| 69 | let mut mantissa = d.round(); |
| 70 | if mantissa >= (1_u64 << (F::MANTISSA_EXPLICIT_BITS + 1)) { |
| 71 | d.right_shift(1); |
| 72 | exp2 += 1; |
| 73 | mantissa = d.round(); |
| 74 | if (exp2 - F::MINIMUM_EXPONENT) >= F::INFINITE_POWER { |
| 75 | return am_inf; |
| 76 | } |
| 77 | } |
| 78 | let mut power2 = exp2 - F::MINIMUM_EXPONENT; |
| 79 | if mantissa < (1_u64 << F::MANTISSA_EXPLICIT_BITS) { |
| 80 | power2 -= 1; |
| 81 | } |
| 82 | mantissa &= (1_u64 << F::MANTISSA_EXPLICIT_BITS) - 1; |
| 83 | AdjustedMantissa { |
| 84 | mantissa, |
| 85 | power2, |
| 86 | } |
| 87 | } |