CURRENT REQUEST-9 SOURCE AND EXTRACTION EVIDENCE
Date: 2026-10-09. This section supersedes predecessor identity records below.
No GOAL classification or source correctness is inferred from these excerpts.
Source/package configuration: modeling-input/SETUP.md and manifest.json.
Transparent extraction scope and all 24 external bindings were inspected with
python3 .trellis/scripts/pv_modeling.py inspect-native .
and checked with python3 .trellis/scripts/pv_modeling.py compose-native . --check.
Composition reports matches=true, changed=false, no mismatched files,
170 frozen extracted modules, 24 bindings, raw extraction SHA-256
438af8398703b81aa311d7885dfb34f1909125bee48b096dacc93baefcc4bcf9.
This is a composition identity result, not a Lean closure certificate.
COMMAND: sha256sum generated.lean GOAL.md modeling-input/manifest.json upstream/dec2flt/parse.rs crate/dec2flt/parse.rs upstream/dec2flt/decimal_seq.rs crate/dec2flt/decimal_seq.rs upstream/dec2flt/mod.rs crate/dec2flt/mod.rs
438af8398703b81aa311d7885dfb34f1909125bee48b096dacc93baefcc4bcf9 generated.lean
0f19c63a168623bd805c17b753dff6f74a695ff283680c22d356fb623fbb4771 GOAL.md
4b71c7166d09bafef194283156edd10e58f25ffd1a498d785e0af04a600c5b32 modeling-input/manifest.json
a9303bac61a5e8e7b610632925bb0d04483374a91f9ec38a7305fd4a1ca0b5f3 upstream/dec2flt/parse.rs
fb5f09bf0bc9742dae352ae0c3bf6706e8855ff22079765f6233fd16f975b669 crate/dec2flt/parse.rs
7b1b28b8c439afb4628411af12920b7c0ecd19036fa530dc74c6a356ec6e351d upstream/dec2flt/decimal_seq.rs
193ca485206899f913a3da75b6ac6484ee90b35c3a5d1c7059ae3d5c61110ad9 crate/dec2flt/decimal_seq.rs
7198e238c554b692405537a446b3526ad66805ec2900cd0e299f10c51402a44a upstream/dec2flt/mod.rs
6ce998fb79493021a6b7af183ba03934fa699ddb6f9c2bfafcea17d26e5c608a crate/dec2flt/mod.rs
COMMAND: nl -ba upstream/dec2flt/parse.rs
1 //! Functions to parse floating-point numbers.
2
3 use dec2flt::common::{ByteSlice, is_8digits};
4 use dec2flt::decimal::Decimal;
5
6 use crate::num::imp::{Float, dec2flt};
7
8 const 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: .
18 fn 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.
30 fn 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).
51 fn 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 } else {
65 break;
66 }
67 }
68
69 *s_ref = s;
70 }
71
72 /// Parse the scientific notation component of a float.
73 pub(super) fn parse_scientific(s_ref: &mut &[u8]) -> Option {
74 let mut exponent = 0i64;
75 let mut negative = false;
76
77 let mut s = *s_ref;
78
79 if let Some((&c, s_next)) = s.split_first() {
80 negative = c == b'-';
81 if c == b'-' || c == b'+' {
82 s = s_next;
83 }
84 }
85
86 if matches!(s.first(), Some(&x) if x.is_ascii_digit()) {
87 *s_ref = s.parse_digits(|digit| {
88 // The exponent is at most 10 * 2^59 - 1, which fits in i64.
89 if exponent < (1_i64 << 59) {
90 exponent = 10 * exponent + digit as i64;
91 }
92 });
93 if negative { Some(-exponent) } else { Some(exponent) }
94 } else {
95 *s_ref = s;
96 None
97 }
98 }
99
100 /// Parse a partial, non-special floating point number.
101 ///
102 /// This creates a representation of the float as the
103 /// significant digits and the decimal exponent.
104 fn parse_partial_number(mut s: &[u8]) -> Option<(Decimal, usize)> {
105 debug_assert!(!s.is_empty());
106
107 // parse initial digits before dot
108 let mut mantissa = 0_u64;
109 let start = s;
110 let tmp = try_parse_digits(s, mantissa);
111 s = tmp.0;
112 mantissa = tmp.1;
113 let mut n_digits = s.offset_from(start);
114
115 // handle dot with the following digits
116 let mut n_after_dot = 0;
117 let mut exponent = 0_i64;
118 let int_end = s;
119
120 if let Some((&b'.', s_next)) = s.split_first() {
121 s = s_next;
122 let before = s;
123 let tmp = try_parse_digits(s, mantissa);
124 s = tmp.0;
125 mantissa = tmp.1;
126 n_after_dot = s.offset_from(before);
127 exponent = -n_after_dot as i64;
128 }
129
130 n_digits += n_after_dot;
131 if n_digits == 0 {
132 return None;
133 }
134
135 // handle scientific format
136 let mut exp_number = 0_i64;
137 if let Some((&c, s_next)) = s.split_first() {
138 if c == b'e' || c == b'E' {
139 s = s_next;
140 // If None, we have no trailing digits after exponent, or an invalid float.
141 exp_number = parse_scientific(&mut s)?;
142 exponent += exp_number;
143 }
144 }
145
146 let len = s.offset_from(start) as _;
147
148 // handle uncommon case with many digits
149 if n_digits <= 19 {
150 return Some((Decimal { exponent, mantissa, negative: false, many_digits: false }, len));
151 }
152
153 n_digits -= 19;
154 let mut many_digits = false;
155 let mut p = start;
156 while let Some((&c, p_next)) = p.split_first() {
157 if c == b'.' || c == b'0' {
158 n_digits -= c.saturating_sub(b'0' - 1) as isize;
159 p = p_next;
160 } else {
161 break;
162 }
163 }
164 if n_digits > 0 {
165 // at this point we have more than 19 significant digits, let's try again
166 many_digits = true;
167 mantissa = 0;
168 let mut s = start;
169 try_parse_19digits(&mut s, &mut mantissa);
170 exponent = if mantissa >= MIN_19DIGIT_INT {
171 // big int
172 int_end.offset_from(s)
173 } else {
174 s = &s[1..];
175 let before = s;
176 try_parse_19digits(&mut s, &mut mantissa);
177 -s.offset_from(before)
178 } as i64;
179 // add back the explicit part
180 exponent += exp_number;
181 }
182
183 Some((Decimal { exponent, mantissa, negative: false, many_digits }, len))
184 }
185
186 /// Try to parse a non-special floating point number,
187 /// as well as two slices with integer and fractional parts
188 /// and the parsed exponent.
189 pub fn parse_number(s: &[u8]) -> Option {
190 if let Some((float, rest)) = parse_partial_number(s) {
191 if rest == s.len() {
192 return Some(float);
193 }
194 }
195 None
196 }
197
198 /// Try to parse a special, non-finite float.
199 pub(crate) fn parse_inf_nan(s: &[u8], negative: bool) -> Option {
200 // Since a valid string has at most the length 8, we can load
201 // all relevant characters into a u64 and work from there.
202 // This also generates much better code.
203
204 let mut register;
205 let len: usize;
206
207 // All valid strings are either of length 8 or 3.
208 if s.len() == 8 {
209 register = s.read_u64();
210 len = 8;
211 } else if s.len() == 3 {
212 let a = s[0] as u64;
213 let b = s[1] as u64;
214 let c = s[2] as u64;
215 register = (c << 16) | (b << 8) | a;
216 len = 3;
217 } else {
218 return None;
219 }
220
221 // Clear out the bits which turn ASCII uppercase characters into
222 // lowercase characters. The resulting string is all uppercase.
223 // What happens to other characters is irrelevant.
224 register &= 0xDFDFDFDFDFDFDFDF;
225
226 // u64 values corresponding to relevant cases
227 const INF_3: u64 = 0x464E49; // "INF"
228 const INF_8: u64 = 0x5954494E49464E49; // "INFINITY"
229 const NAN: u64 = 0x4E414E; // "NAN"
230
231 // Match register value to constant to parse string.
232 // Also match on the string length to catch edge cases
233 // like "inf\0\0\0\0\0".
234 let float = match (register, len) {
235 (INF_3, 3) => F::INFINITY,
236 (INF_8, 8) => F::INFINITY,
237 (NAN, 3) => F::NAN,
238 _ => return None,
239 };
240
241 if negative { Some(-float) } else { Some(float) }
242 }
COMMAND: nl -ba upstream/dec2flt/decimal_seq.rs
1 //! Arbitrary-precision decimal type used by fallback algorithms.
2 //!
3 //! This is only used if the fast-path (native floats) and
4 //! the Eisel-Lemire algorithm are unable to unambiguously
5 //! determine the float.
6 //!
7 //! The technique used is "Simple Decimal Conversion", developed
8 //! by Nigel Tao and Ken Thompson. A detailed description of the
9 //! algorithm can be found in "ParseNumberF64 by Simple Decimal Conversion",
10 //! available online: .
11
12 use dec2flt::common::{ByteSlice, is_8digits};
13 use dec2flt::parse::parse_scientific;
14
15 use crate::num::imp::dec2flt;
16
17 /// A decimal floating-point number, represented as a sequence of decimal digits.
18 #[derive(Clone, Debug, PartialEq)]
19 pub struct DecimalSeq {
20 /// The number of significant digits in the decimal.
21 pub num_digits: usize,
22 /// The offset of the decimal point in the significant digits.
23 pub decimal_point: i32,
24 /// If the number of significant digits stored in the decimal is truncated.
25 pub truncated: bool,
26 /// Buffer of the raw digits, in the range [0, 9].
27 pub digits: [u8; Self::MAX_DIGITS],
28 }
29
30 impl Default for DecimalSeq {
31 fn default() -> Self {
32 Self { num_digits: 0, decimal_point: 0, truncated: false, digits: [0; Self::MAX_DIGITS] }
33 }
34 }
35
36 impl DecimalSeq {
37 /// The maximum number of digits required to unambiguously round up to a 64-bit float.
38 ///
39 /// For an IEEE 754 binary64 float, this required 767 digits. So we store the max digits + 1.
40 ///
41 /// We can exactly represent a float in radix `b` from radix 2 if
42 /// `b` is divisible by 2. This function calculates the exact number of
43 /// digits required to exactly represent that float.
44 ///
45 /// According to the "Handbook of Floating Point Arithmetic",
46 /// for IEEE754, with `emin` being the min exponent, `p2` being the
47 /// precision, and `b` being the radix, the number of digits follows as:
48 ///
49 /// `−emin + p2 + ⌊(emin + 1) log(2, b) − log(1 − 2^(−p2), b)⌋`
50 ///
51 /// For f32, this follows as:
52 /// emin = -126
53 /// p2 = 24
54 ///
55 /// For f64, this follows as:
56 /// emin = -1022
57 /// p2 = 53
58 ///
59 /// In Python:
60 /// `-emin + p2 + math.floor((emin+ 1)*math.log(2, b)-math.log(1-2**(-p2), b))`
61 pub const MAX_DIGITS: usize = 768;
62
63 /// The max decimal digits that can be exactly represented in a 64-bit integer.
64 pub(super) const MAX_DIGITS_WITHOUT_OVERFLOW: usize = 19;
65 pub(super) const DECIMAL_POINT_RANGE: i32 = 2047;
66
67 /// Append a digit to the buffer if it fits.
68 // FIXME(tgross35): it may be better for this to return an option
69 // FIXME(tgross35): incrementing the digit counter even if we don't push anything
70 // seems incorrect.
71 pub(super) fn try_add_digit(&mut self, digit: u8) {
72 if self.num_digits < Self::MAX_DIGITS {
73 self.digits[self.num_digits] = digit;
74 }
75 self.num_digits += 1;
76 }
77
78 /// Trim trailing zeros from the buffer.
79 // FIXME(tgross35): this could be `.rev().position()` if perf is okay
80 pub fn trim(&mut self) {
81 // All of the following calls to `DecimalSeq::trim` can't panic because:
82 //
83 // 1. `parse_decimal` sets `num_digits` to a max of `DecimalSeq::MAX_DIGITS`.
84 // 2. `right_shift` sets `num_digits` to `write_index`, which is bounded by `num_digits`.
85 // 3. `left_shift` `num_digits` to a max of `DecimalSeq::MAX_DIGITS`.
86 //
87 // Trim is only called in `right_shift` and `left_shift`.
88 debug_assert!(self.num_digits <= Self::MAX_DIGITS);
89 while self.num_digits != 0 && self.digits[self.num_digits - 1] == 0 {
90 self.num_digits -= 1;
91 }
92 }
93
94 pub(super) fn round(&self) -> u64 {
95 if self.num_digits == 0 || self.decimal_point < 0 {
96 return 0;
97 } else if self.decimal_point >= Self::MAX_DIGITS_WITHOUT_OVERFLOW as i32 {
98 return 0xFFFF_FFFF_FFFF_FFFF_u64;
99 }
100
101 let dp = self.decimal_point as usize;
102 let mut n = 0_u64;
103
104 for i in 0..dp {
105 n *= 10;
106 if i < self.num_digits {
107 n += self.digits[i] as u64;
108 }
109 }
110
111 let mut round_up = false;
112
113 if dp < self.num_digits {
114 round_up = self.digits[dp] >= 5;
115 if self.digits[dp] == 5 && dp + 1 == self.num_digits {
116 round_up = self.truncated || ((dp != 0) && (1 & self.digits[dp - 1] != 0))
117 }
118 }
119
120 if round_up {
121 n += 1;
122 }
123 n
124 }
125
126 /// Computes decimal * 2^shift.
127 pub(super) fn left_shift(&mut self, shift: usize) {
128 if self.num_digits == 0 {
129 return;
130 }
131 let num_new_digits = number_of_digits_decimal_left_shift(self, shift);
132 let mut read_index = self.num_digits;
133 let mut write_index = self.num_digits + num_new_digits;
134 let mut n = 0_u64;
135
136 while read_index != 0 {
137 read_index -= 1;
138 write_index -= 1;
139 n += (self.digits[read_index] as u64) << shift;
140 let quotient = n / 10;
141 let remainder = n - (10 * quotient);
142 if write_index < Self::MAX_DIGITS {
143 self.digits[write_index] = remainder as u8;
144 } else if remainder > 0 {
145 self.truncated = true;
146 }
147 n = quotient;
148 }
149
150 while n > 0 {
151 write_index -= 1;
152 let quotient = n / 10;
153 let remainder = n - (10 * quotient);
154 if write_index < Self::MAX_DIGITS {
155 self.digits[write_index] = remainder as u8;
156 } else if remainder > 0 {
157 self.truncated = true;
158 }
159 n = quotient;
160 }
161
162 self.num_digits += num_new_digits;
163
164 if self.num_digits > Self::MAX_DIGITS {
165 self.num_digits = Self::MAX_DIGITS;
166 }
167
168 self.decimal_point += num_new_digits as i32;
169 self.trim();
170 }
171
172 /// Computes decimal * 2^-shift.
173 pub(super) fn right_shift(&mut self, shift: usize) {
174 let mut read_index = 0;
175 let mut write_index = 0;
176 let mut n = 0_u64;
177 while (n >> shift) == 0 {
178 if read_index < self.num_digits {
179 n = (10 * n) + self.digits[read_index] as u64;
180 read_index += 1;
181 } else if n == 0 {
182 return;
183 } else {
184 while (n >> shift) == 0 {
185 n *= 10;
186 read_index += 1;
187 }
188 break;
189 }
190 }
191 self.decimal_point -= read_index as i32 - 1;
192 if self.decimal_point < -Self::DECIMAL_POINT_RANGE {
193 // `self = Self::Default()`, but without the overhead of clearing `digits`.
194 self.num_digits = 0;
195 self.decimal_point = 0;
196 self.truncated = false;
197 return;
198 }
199 let mask = (1_u64 << shift) - 1;
200 while read_index < self.num_digits {
201 let new_digit = (n >> shift) as u8;
202 n = (10 * (n & mask)) + self.digits[read_index] as u64;
203 read_index += 1;
204 self.digits[write_index] = new_digit;
205 write_index += 1;
206 }
207 while n > 0 {
208 let new_digit = (n >> shift) as u8;
209 n = 10 * (n & mask);
210 if write_index < Self::MAX_DIGITS {
211 self.digits[write_index] = new_digit;
212 write_index += 1;
213 } else if new_digit > 0 {
214 self.truncated = true;
215 }
216 }
217 self.num_digits = write_index;
218 self.trim();
219 }
220 }
221
222 /// Combine counts in i64 and clamp before casting to i32.
223 #[inline]
224 pub(super) fn final_decimal_point(
225 significant_count: usize,
226 fractional_count: usize,
227 explicit: i64,
228 ) -> i32 {
229 if significant_count == 0 {
230 return 0;
231 }
232 let base = significant_count as i64 - fractional_count as i64;
233 base.saturating_add(explicit)
234 .clamp(-(DecimalSeq::DECIMAL_POINT_RANGE as i64), DecimalSeq::DECIMAL_POINT_RANGE as i64)
235 as i32
236 }
237
238 /// Parse a big integer representation of the float as a decimal.
239 pub fn parse_decimal_seq(mut s: &[u8]) -> DecimalSeq {
240 let mut d = DecimalSeq::default();
241 let start = s;
242 let mut fractional_count = 0;
243
244 while let Some((&b'0', s_next)) = s.split_first() {
245 s = s_next;
246 }
247
248 s = s.parse_digits(|digit| d.try_add_digit(digit));
249
250 if let Some((b'.', s_next)) = s.split_first() {
251 s = s_next;
252 let first = s;
253 // Skip leading zeros.
254 if d.num_digits == 0 {
255 while let Some((&b'0', s_next)) = s.split_first() {
256 s = s_next;
257 }
258 }
259 while s.len() >= 8 && d.num_digits + 8 < DecimalSeq::MAX_DIGITS {
260 let v = s.read_u64();
261 if !is_8digits(v) {
262 break;
263 }
264 d.digits[d.num_digits..].write_u64(v - 0x3030_3030_3030_3030);
265 d.num_digits += 8;
266 s = &s[8..];
267 }
268 s = s.parse_digits(|digit| d.try_add_digit(digit));
269 fractional_count = first.len() - s.len();
270 }
271
272 let significant_count = d.num_digits;
273 if d.num_digits != 0 {
274 // Ignore the trailing zeros if there are any
275 let mut n_trailing_zeros = 0;
276 for &c in start[..(start.len() - s.len())].iter().rev() {
277 if c == b'0' {
278 n_trailing_zeros += 1;
279 } else if c != b'.' {
280 break;
281 }
282 }
283 d.num_digits -= n_trailing_zeros;
284 if d.num_digits > DecimalSeq::MAX_DIGITS {
285 d.truncated = true;
286 d.num_digits = DecimalSeq::MAX_DIGITS;
287 }
288 }
289
290 let mut explicit = 0;
291 if let Some((&ch, s_next)) = s.split_first() {
292 if ch == b'e' || ch == b'E' {
293 s = s_next;
294 explicit = parse_scientific(&mut s).unwrap_or(0);
295 }
296 }
297 d.decimal_point = final_decimal_point(significant_count, fractional_count, explicit);
298
299 for i in d.num_digits..DecimalSeq::MAX_DIGITS_WITHOUT_OVERFLOW {
300 d.digits[i] = 0;
301 }
302
303 d
304 }
305
306 fn number_of_digits_decimal_left_shift(d: &DecimalSeq, mut shift: usize) -> usize {
307 #[rustfmt::skip]
308 const TABLE: [u16; 65] = [
309 0x0000, 0x0800, 0x0801, 0x0803, 0x1006, 0x1009, 0x100D, 0x1812, 0x1817, 0x181D, 0x2024,
310 0x202B, 0x2033, 0x203C, 0x2846, 0x2850, 0x285B, 0x3067, 0x3073, 0x3080, 0x388E, 0x389C,
311 0x38AB, 0x38BB, 0x40CC, 0x40DD, 0x40EF, 0x4902, 0x4915, 0x4929, 0x513E, 0x5153, 0x5169,
312 0x5180, 0x5998, 0x59B0, 0x59C9, 0x61E3, 0x61FD, 0x6218, 0x6A34, 0x6A50, 0x6A6D, 0x6A8B,
313 0x72AA, 0x72C9, 0x72E9, 0x7B0A, 0x7B2B, 0x7B4D, 0x8370, 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 2, 4, 0, 6, 9, 5, 9, 5, 3, 3, 6, 9, 1, 4, 0, 6, 2, 5,
362 ];
363
364 shift &= 63;
365 let x_a = TABLE[shift];
366 let x_b = TABLE[shift + 1];
367 let num_new_digits = (x_a >> 11) as _;
368 let pow5_a = (0x7FF & x_a) as usize;
369 let pow5_b = (0x7FF & x_b) as usize;
370 let pow5 = &TABLE_POW5[pow5_a..];
371
372 for (i, &p5) in pow5.iter().enumerate().take(pow5_b - pow5_a) {
373 if i >= d.num_digits {
374 return num_new_digits - 1;
375 } else if d.digits[i] == p5 {
376 continue;
377 } else if d.digits[i] < p5 {
378 return num_new_digits - 1;
379 } else {
380 return num_new_digits;
381 }
382 }
383
384 num_new_digits
385 }
COMMAND: nl -ba crate/dec2flt/parse.rs
1 //! Functions to parse floating-point numbers.
2
3 use dec2flt::common::{ByteSlice, is_8digits};
4 use dec2flt::decimal::Decimal;
5
6 use crate::num::imp::{Float, dec2flt};
7
8 const 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: .
18 fn 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.
30 fn 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 // `chunk` is the source's local `num` under a nonconflicting name.
35 // The rename has no Rust effect and prevents the Lean backend from
36 // resolving `num.imp...` as a field projection on this local value.
37 let chunk = s.read_u64();
38 if is_8digits(chunk) {
39 x = x.wrapping_mul(1_0000_0000).wrapping_add(parse_8digits(chunk));
40 s = &s[8..];
41 } else {
42 break;
43 }
44 }
45
46 // This is the removed `ByteSlice::parse_digits` call specialized to this
47 // accumulator: identical wrapping digit classification, accumulator
48 // update, and first-nondigit stop, without an unsupported closure state.
49 let mut count = 0;
50 while count < s.len() && s[count].wrapping_sub(b'0') < 10 {
51 let digit = s[count].wrapping_sub(b'0');
52 x = x.wrapping_mul(10).wrapping_add(digit as _);
53 count += 1;
54 }
55 s = &s[count..];
56
57 (s, x)
58 }
59
60 /// Parse up to 19 digits (the max that can be stored in a 64-bit integer).
61 fn try_parse_19digits(s_ref: &mut &[u8], x: &mut u64) {
62 let mut s = *s_ref;
63
64 while *x < MIN_19DIGIT_INT {
65 if let Some((c, s_next)) = s.split_first() {
66 let digit = c.wrapping_sub(b'0');
67
68 if digit < 10 {
69 *x = (*x * 10) + digit as u64; // no overflows here
70 s = s_next;
71 } else {
72 break;
73 }
74 } else {
75 break;
76 }
77 }
78
79 *s_ref = s;
80 }
81
82 // This is the source prefix scan isolated from `parse_partial_number` because
83 // Aeneas cannot join its loop context while the enclosing function's other
84 // slice borrows are live. It visits the same bytes, in order, and performs
85 // the identical checked `isize` subtraction for every leading dot or zero.
86 fn adjust_many_digit_count(start: &[u8], mut n_digits: isize) -> isize {
87 let mut scan_index = 0;
88 let mut scanning = true;
89 while scan_index < start.len() && scanning {
90 let c = start[scan_index];
91 if c == b'.' || c == b'0' {
92 n_digits -= c.saturating_sub(b'0' - 1) as isize;
93 scan_index += 1;
94 } else {
95 scanning = false;
96 }
97 }
98 n_digits
99 }
100
101 // This is the source many-digit retry as a transparent helper. Isolating its
102 // rebased slices avoids an Aeneas context-join failure; both calls, the branch,
103 // the offset arithmetic, and the explicit-exponent addition are unchanged.
104 fn parse_many_digits(start: &[u8], int_end: &[u8], exp_number: i64) -> (u64, i64) {
105 let mut mantissa = 0;
106 let mut s = start;
107 try_parse_19digits(&mut s, &mut mantissa);
108 let mut exponent = if mantissa >= MIN_19DIGIT_INT {
109 int_end.offset_from(s)
110 } else {
111 s = &s[1..];
112 let before = s;
113 try_parse_19digits(&mut s, &mut mantissa);
114 -s.offset_from(before)
115 } as i64;
116 exponent += exp_number;
117 (mantissa, exponent)
118 }
119
120 /// Parse the scientific notation component of a float.
121 pub(super) fn parse_scientific(s_ref: &mut &[u8]) -> Option {
122 let mut exponent = 0i64;
123 let mut negative = false;
124
125 let mut s = *s_ref;
126
127 if let Some((&c, s_next)) = s.split_first() {
128 negative = c == b'-';
129 if c == b'-' || c == b'+' {
130 s = s_next;
131 }
132 }
133
134 // `matches!` with a guarded slice pattern triggers an Aeneas internal
135 // error. This short-circuit test reads the same first byte exactly when
136 // it exists and therefore preserves both acceptance and evaluation order.
137 if !s.is_empty() && s[0].is_ascii_digit() {
138 // Specialized form of the revised source callback, shared with the
139 // sibling slow parser. The guard tests the pre-update accumulator:
140 // one digit can overshoot 2^59, up to 10 * 2^59 - 1, still below
141 // i64::MAX. This is not a clamp. Subsequent digits are still consumed
142 // and the first nondigit remains in the returned suffix, so the caller
143 // performs the same whole-input validation even after updates stop.
144 let mut count = 0;
145 while count < s.len() && s[count].wrapping_sub(b'0') < 10 {
146 let digit = s[count].wrapping_sub(b'0');
147 if exponent < (1_i64 << 59) {
148 exponent = 10 * exponent + digit as i64;
149 }
150 count += 1;
151 }
152 *s_ref = &s[count..];
153 if negative { Some(-exponent) } else { Some(exponent) }
154 } else {
155 *s_ref = s;
156 None
157 }
158 }
159
160 /// Parse a partial, non-special floating point number.
161 ///
162 /// This creates a representation of the float as the
163 /// significant digits and the decimal exponent.
164 fn parse_partial_number(mut s: &[u8]) -> Option<(Decimal, usize)> {
165 debug_assert!(!s.is_empty());
166
167 // parse initial digits before dot
168 let mut mantissa = 0_u64;
169 let start = s;
170 let tmp = try_parse_digits(s, mantissa);
171 s = tmp.0;
172 mantissa = tmp.1;
173 let mut n_digits = s.offset_from(start);
174
175 // handle dot with the following digits
176 let mut n_after_dot = 0;
177 let mut exponent = 0_i64;
178 let int_end = s;
179
180 if let Some((&b'.', s_next)) = s.split_first() {
181 s = s_next;
182 let before = s;
183 let tmp = try_parse_digits(s, mantissa);
184 s = tmp.0;
185 mantissa = tmp.1;
186 n_after_dot = s.offset_from(before);
187 exponent = -n_after_dot as i64;
188 }
189
190 n_digits += n_after_dot;
191 if n_digits == 0 {
192 return None;
193 }
194
195 // handle scientific format
196 let mut exp_number = 0_i64;
197 if let Some((&c, s_next)) = s.split_first() {
198 if c == b'e' || c == b'E' {
199 s = s_next;
200 // If None, we have no trailing digits after exponent, or an invalid float.
201 exp_number = parse_scientific(&mut s)?;
202 exponent += exp_number;
203 }
204 }
205
206 let len = s.offset_from(start) as _;
207
208 // handle uncommon case with many digits
209 if n_digits <= 19 {
210 return Some((Decimal { exponent, mantissa, negative: false, many_digits: false }, len));
211 }
212
213 n_digits -= 19;
214 let mut many_digits = false;
215 // The indexed loop is equivalent to the source `while let split_first`:
216 // it tests nonemptiness before the same byte read and consumes one byte
217 // only on the two source continuation cases. This avoids Aeneas's loop
218 // context mismatch without changing checked subtraction or slice bounds.
219 n_digits = adjust_many_digit_count(start, n_digits);
220 if n_digits > 0 {
221 // at this point we have more than 19 significant digits, let's try again
222 many_digits = true;
223 let retried = parse_many_digits(start, int_end, exp_number);
224 mantissa = retried.0;
225 exponent = retried.1;
226 }
227
228 Some((Decimal { exponent, mantissa, negative: false, many_digits }, len))
229 }
230
231 /// Try to parse a non-special floating point number,
232 /// as well as two slices with integer and fractional parts
233 /// and the parsed exponent.
234 pub fn parse_number(s: &[u8]) -> Option {
235 if let Some((float, rest)) = parse_partial_number(s) {
236 if rest == s.len() {
237 return Some(float);
238 }
239 }
240 None
241 }
242
243 /// Try to parse a special, non-finite float.
244 pub(crate) fn parse_inf_nan(s: &[u8], negative: bool) -> Option {
245 // Since a valid string has at most the length 8, we can load
246 // all relevant characters into a u64 and work from there.
247 // This also generates much better code.
248
249 let mut register;
250 let len: usize;
251
252 // All valid strings are either of length 8 or 3.
253 if s.len() == 8 {
254 register = s.read_u64();
255 len = 8;
256 } else if s.len() == 3 {
257 let a = s[0] as u64;
258 let b = s[1] as u64;
259 let c = s[2] as u64;
260 register = (c << 16) | (b << 8) | a;
261 len = 3;
262 } else {
263 return None;
264 }
265
266 // Clear out the bits which turn ASCII uppercase characters into
267 // lowercase characters. The resulting string is all uppercase.
268 // What happens to other characters is irrelevant.
269 register &= 0xDFDFDFDFDFDFDFDF;
270
271 // u64 values corresponding to relevant cases
272 const INF_3: u64 = 0x464E49; // "INF"
273 const INF_8: u64 = 0x5954494E49464E49; // "INFINITY"
274 const NAN: u64 = 0x4E414E; // "NAN"
275
276 // Match register value to constant to parse string.
277 // Also match on the string length to catch edge cases
278 // like "inf\0\0\0\0\0".
279 let float = match (register, len) {
280 (INF_3, 3) => F::INFINITY,
281 (INF_8, 8) => F::INFINITY,
282 (NAN, 3) => F::NAN,
283 _ => return None,
284 };
285
286 if negative { Some(-float) } else { Some(float) }
287 }
COMMAND: nl -ba crate/dec2flt/decimal_seq.rs
1 //! Arbitrary-precision decimal type used by fallback algorithms.
2 //!
3 //! This is only used if the fast-path (native floats) and
4 //! the Eisel-Lemire algorithm are unable to unambiguously
5 //! determine the float.
6 //!
7 //! The technique used is "Simple Decimal Conversion", developed
8 //! by Nigel Tao and Ken Thompson. A detailed description of the
9 //! algorithm can be found in "ParseNumberF64 by Simple Decimal Conversion",
10 //! available online: .
11
12 use dec2flt::common::{ByteSlice, is_8digits};
13 use dec2flt::parse::parse_scientific;
14
15 use crate::num::imp::dec2flt;
16
17 /// A decimal floating-point number, represented as a sequence of decimal digits.
18 // Debug output is absent from the scoped observations. Removing only that
19 // implementation preserves the representation, Clone/PartialEq behavior, and
20 // every fallback operation independently of GOAL truth.
21 #[derive(Clone, PartialEq)]
22 pub struct DecimalSeq {
23 /// The number of significant digits in the decimal.
24 pub num_digits: usize,
25 /// The offset of the decimal point in the significant digits.
26 pub decimal_point: i32,
27 /// If the number of significant digits stored in the decimal is truncated.
28 pub truncated: bool,
29 /// Buffer of the raw digits, in the range [0, 9].
30 pub digits: [u8; Self::MAX_DIGITS],
31 }
32
33 impl Default for DecimalSeq {
34 fn default() -> Self {
35 Self { num_digits: 0, decimal_point: 0, truncated: false, digits: [0; Self::MAX_DIGITS] }
36 }
37 }
38
39 impl DecimalSeq {
40 /// The maximum number of digits required to unambiguously round up to a 64-bit float.
41 ///
42 /// For an IEEE 754 binary64 float, this required 767 digits. So we store the max digits + 1.
43 ///
44 /// We can exactly represent a float in radix `b` from radix 2 if
45 /// `b` is divisible by 2. This function calculates the exact number of
46 /// digits required to exactly represent that float.
47 ///
48 /// According to the "Handbook of Floating Point Arithmetic",
49 /// for IEEE754, with `emin` being the min exponent, `p2` being the
50 /// precision, and `b` being the radix, the number of digits follows as:
51 ///
52 /// `−emin + p2 + ⌊(emin + 1) log(2, b) − log(1 − 2^(−p2), b)⌋`
53 ///
54 /// For f32, this follows as:
55 /// emin = -126
56 /// p2 = 24
57 ///
58 /// For f64, this follows as:
59 /// emin = -1022
60 /// p2 = 53
61 ///
62 /// In Python:
63 /// `-emin + p2 + math.floor((emin+ 1)*math.log(2, b)-math.log(1-2**(-p2), b))`
64 pub const MAX_DIGITS: usize = 768;
65
66 /// The max decimal digits that can be exactly represented in a 64-bit integer.
67 pub(super) const MAX_DIGITS_WITHOUT_OVERFLOW: usize = 19;
68 pub(super) const DECIMAL_POINT_RANGE: i32 = 2047;
69
70 /// Append a digit to the buffer if it fits.
71 // FIXME(tgross35): it may be better for this to return an option
72 // FIXME(tgross35): incrementing the digit counter even if we don't push anything
73 // seems incorrect.
74 pub(super) fn try_add_digit(&mut self, digit: u8) {
75 if self.num_digits < Self::MAX_DIGITS {
76 self.digits[self.num_digits] = digit;
77 }
78 self.num_digits += 1;
79 }
80
81 /// Trim trailing zeros from the buffer.
82 // FIXME(tgross35): this could be `.rev().position()` if perf is okay
83 pub fn trim(&mut self) {
84 // All of the following calls to `DecimalSeq::trim` can't panic because:
85 //
86 // 1. `parse_decimal` sets `num_digits` to a max of `DecimalSeq::MAX_DIGITS`.
87 // 2. `right_shift` sets `num_digits` to `write_index`, which is bounded by `num_digits`.
88 // 3. `left_shift` `num_digits` to a max of `DecimalSeq::MAX_DIGITS`.
89 //
90 // Trim is only called in `right_shift` and `left_shift`.
91 debug_assert!(self.num_digits <= Self::MAX_DIGITS);
92 while self.num_digits != 0 && self.digits[self.num_digits - 1] == 0 {
93 self.num_digits -= 1;
94 }
95 }
96
97 pub(super) fn round(&self) -> u64 {
98 if self.num_digits == 0 || self.decimal_point < 0 {
99 return 0;
100 } else if self.decimal_point >= Self::MAX_DIGITS_WITHOUT_OVERFLOW as i32 {
101 return 0xFFFF_FFFF_FFFF_FFFF_u64;
102 }
103
104 let dp = self.decimal_point as usize;
105 let mut n = 0_u64;
106
107 for i in 0..dp {
108 n *= 10;
109 if i < self.num_digits {
110 n += self.digits[i] as u64;
111 }
112 }
113
114 let mut round_up = false;
115
116 if dp < self.num_digits {
117 round_up = self.digits[dp] >= 5;
118 if self.digits[dp] == 5 && dp + 1 == self.num_digits {
119 round_up = self.truncated || ((dp != 0) && (1 & self.digits[dp - 1] != 0))
120 }
121 }
122
123 if round_up {
124 n += 1;
125 }
126 n
127 }
128
129 /// Computes decimal * 2^shift.
130 pub(super) fn left_shift(&mut self, shift: usize) {
131 if self.num_digits == 0 {
132 return;
133 }
134 let num_new_digits = number_of_digits_decimal_left_shift(self, shift);
135 let mut read_index = self.num_digits;
136 let mut write_index = self.num_digits + num_new_digits;
137 let mut n = 0_u64;
138
139 while read_index != 0 {
140 read_index -= 1;
141 write_index -= 1;
142 n += (self.digits[read_index] as u64) << shift;
143 let quotient = n / 10;
144 let remainder = n - (10 * quotient);
145 if write_index < Self::MAX_DIGITS {
146 self.digits[write_index] = remainder as u8;
147 } else if remainder > 0 {
148 self.truncated = true;
149 }
150 n = quotient;
151 }
152
153 while n > 0 {
154 write_index -= 1;
155 let quotient = n / 10;
156 let remainder = n - (10 * quotient);
157 if write_index < Self::MAX_DIGITS {
158 self.digits[write_index] = remainder as u8;
159 } else if remainder > 0 {
160 self.truncated = true;
161 }
162 n = quotient;
163 }
164
165 self.num_digits += num_new_digits;
166
167 if self.num_digits > Self::MAX_DIGITS {
168 self.num_digits = Self::MAX_DIGITS;
169 }
170
171 self.decimal_point += num_new_digits as i32;
172 self.trim();
173 }
174
175 /// Computes decimal * 2^-shift.
176 pub(super) fn right_shift(&mut self, shift: usize) {
177 let mut read_index = 0;
178 let mut write_index = 0;
179 let mut n = 0_u64;
180 let mut all_zero = false;
181 while (n >> shift) == 0 && !all_zero {
182 if read_index < self.num_digits {
183 n = (10 * n) + self.digits[read_index] as u64;
184 read_index += 1;
185 } else if n == 0 {
186 // The source returns here from inside the loop. Recording the
187 // condition and returning immediately after the loop executes
188 // no intervening operation and preserves the unchanged value.
189 all_zero = true;
190 } else {
191 while (n >> shift) == 0 {
192 n *= 10;
193 read_index += 1;
194 }
195 break;
196 }
197 }
198 if all_zero {
199 return;
200 }
201 self.decimal_point -= read_index as i32 - 1;
202 if self.decimal_point < -Self::DECIMAL_POINT_RANGE {
203 // `self = Self::Default()`, but without the overhead of clearing `digits`.
204 self.num_digits = 0;
205 self.decimal_point = 0;
206 self.truncated = false;
207 return;
208 }
209 let mask = (1_u64 << shift) - 1;
210 while read_index < self.num_digits {
211 let new_digit = (n >> shift) as u8;
212 n = (10 * (n & mask)) + self.digits[read_index] as u64;
213 read_index += 1;
214 self.digits[write_index] = new_digit;
215 write_index += 1;
216 }
217 while n > 0 {
218 let new_digit = (n >> shift) as u8;
219 n = 10 * (n & mask);
220 if write_index < Self::MAX_DIGITS {
221 self.digits[write_index] = new_digit;
222 write_index += 1;
223 } else if new_digit > 0 {
224 self.truncated = true;
225 }
226 }
227 self.num_digits = write_index;
228 self.trim();
229 }
230 }
231
232 // This is exactly the source reverse scan over the already-consumed prefix.
233 // It is separate because Aeneas cannot join the loop while `parse_decimal_seq`
234 // retains its other slice borrows. The downward index has the same visitation
235 // order and counts precisely the same zero bytes while ignoring dots.
236 fn count_trailing_zeros(start: &[u8], consumed_len: usize) -> usize {
237 let mut n_trailing_zeros = 0;
238 let mut i = consumed_len;
239 let mut scanning = true;
240 while i != 0 && scanning {
241 let c = start[i - 1];
242 if c == b'0' || c == b'.' {
243 i -= 1;
244 if c == b'0' {
245 n_trailing_zeros += 1;
246 }
247 } else {
248 scanning = false;
249 }
250 }
251 n_trailing_zeros
252 }
253
254 // Equivalent to `ByteSlice::parse_digits(|digit| d.try_add_digit(digit))`.
255 // An explicit index keeps the closure's mutable borrow out of the enclosing
256 // parser context while retaining the same wrapping digit test and updates.
257 fn parse_digits_into_seq<'a>(s: &'a [u8], d: &mut DecimalSeq) -> &'a [u8] {
258 let mut count = 0;
259 while count < s.len() && s[count].wrapping_sub(b'0') < 10 {
260 let digit = s[count].wrapping_sub(b'0');
261 d.try_add_digit(digit);
262 count += 1;
263 }
264 &s[count..]
265 }
266
267 /// Combine counts in i64 and clamp before casting to i32.
268 #[inline]
269 pub(super) fn final_decimal_point(
270 significant_count: usize,
271 fractional_count: usize,
272 explicit: i64,
273 ) -> i32 {
274 // This is the repaired upstream body, not an extraction replacement.
275 // Source-valid byte slices bound both counts by isize::MAX on this target;
276 // their i64 difference is therefore in range. Retain saturating_add and
277 // clamp as source operations, including the zero-count early return.
278 if significant_count == 0 {
279 return 0;
280 }
281 let base = significant_count as i64 - fractional_count as i64;
282 base.saturating_add(explicit)
283 .clamp(-(DecimalSeq::DECIMAL_POINT_RANGE as i64), DecimalSeq::DECIMAL_POINT_RANGE as i64)
284 as i32
285 }
286
287 /// Parse a big integer representation of the float as a decimal.
288 pub fn parse_decimal_seq(mut s: &[u8]) -> DecimalSeq {
289 let mut d = DecimalSeq::default();
290 let start = s;
291 let mut fractional_count = 0;
292
293 // Aeneas rejects the literal-pattern `while let`; this loop performs the
294 // same nonempty check, byte comparison, and one-byte consumption in the
295 // same order, with identical slice bounds.
296 while !s.is_empty() && s[0] == b'0' {
297 s = &s[1..];
298 }
299
300 s = parse_digits_into_seq(s, &mut d);
301
302 if !s.is_empty() && s[0] == b'.' {
303 s = &s[1..];
304 let first = s;
305 // Skip leading zeros.
306 if d.num_digits == 0 {
307 // As above, this is the source leading-zero loop written in the
308 // indexed form accepted by Aeneas.
309 while !s.is_empty() && s[0] == b'0' {
310 s = &s[1..];
311 }
312 }
313 while s.len() >= 8 && d.num_digits + 8 < DecimalSeq::MAX_DIGITS {
314 let v = s.read_u64();
315 if !is_8digits(v) {
316 break;
317 }
318 d.digits[d.num_digits..].write_u64(v - 0x3030_3030_3030_3030);
319 d.num_digits += 8;
320 s = &s[8..];
321 }
322 s = parse_digits_into_seq(s, &mut d);
323 // `first` precedes zero skipping and both digit scans. This difference
324 // includes every fractional digit, just as in repaired upstream.
325 fractional_count = first.len() - s.len();
326 }
327
328 // Save the source's logical count before trimming and MAX_DIGITS capping;
329 // the stored digit prefix must not replace this count in point arithmetic.
330 let significant_count = d.num_digits;
331 if d.num_digits != 0 {
332 // Ignore the trailing zeros if there are any
333 let consumed_len = start.len() - s.len();
334 // Walking an index downward visits exactly the same bytes as
335 // `.iter().rev()` and stops on the same first nonzero nondot byte. It
336 // also avoids the missing extracted `Iterator::rev` library field.
337 let n_trailing_zeros = count_trailing_zeros(start, consumed_len);
338 d.num_digits -= n_trailing_zeros;
339 if d.num_digits > DecimalSeq::MAX_DIGITS {
340 d.truncated = true;
341 d.num_digits = DecimalSeq::MAX_DIGITS;
342 }
343 }
344
345 // Indexed tests preserve `split_first`'s nonempty guard and byte order but
346 // avoid the loop-context joins Aeneas creates for nested slice patterns.
347 let mut explicit = 0;
348 if !s.is_empty() {
349 let ch = s[0];
350 if ch == b'e' || ch == b'E' {
351 // Aeneas cannot join this branch when the enclosing `s` is
352 // rebased and mutably borrowed. A fresh slice local translates.
353 // The source never reads `s` after this call: all consumed-prefix,
354 // significant and fractional counts are already saved. Passing
355 // the identical suffix to the unchanged shared parser gives the
356 // same sign, digit consumption, bounded accumulation, checked
357 // operations and failures; only its unobserved suffix mutation
358 // targets a different local. Keep the call even for zero digits,
359 // and keep None-to-zero on missing/malformed exponent digits.
360 // This argument needs no numeric-validity or correctness premise;
361 // parse_number still observes the shared parser's returned suffix.
362 let mut exponent_suffix = &s[1..];
363 explicit = parse_scientific(&mut exponent_suffix).unwrap_or(0);
364 }
365 }
366 d.decimal_point = final_decimal_point(significant_count, fractional_count, explicit);
367
368 for i in d.num_digits..DecimalSeq::MAX_DIGITS_WITHOUT_OVERFLOW {
369 d.digits[i] = 0;
370 }
371
372 d
373 }
374
375 fn number_of_digits_decimal_left_shift(d: &DecimalSeq, mut shift: usize) -> usize {
376 #[rustfmt::skip]
377 const TABLE: [u16; 65] = [
378 0x0000, 0x0800, 0x0801, 0x0803, 0x1006, 0x1009, 0x100D, 0x1812, 0x1817, 0x181D, 0x2024,
379 0x202B, 0x2033, 0x203C, 0x2846, 0x2850, 0x285B, 0x3067, 0x3073, 0x3080, 0x388E, 0x389C,
380 0x38AB, 0x38BB, 0x40CC, 0x40DD, 0x40EF, 0x4902, 0x4915, 0x4929, 0x513E, 0x5153, 0x5169,
381 0x5180, 0x5998, 0x59B0, 0x59C9, 0x61E3, 0x61FD, 0x6218, 0x6A34, 0x6A50, 0x6A6D, 0x6A8B,
382 0x72AA, 0x72C9, 0x72E9, 0x7B0A, 0x7B2B, 0x7B4D, 0x8370, 0x8393, 0x83B7, 0x83DC, 0x8C02,
383 0x8C28, 0x8C4F, 0x9477, 0x949F, 0x94C8, 0x9CF2, 0x051C, 0x051C, 0x051C, 0x051C,
384 ];
385 #[rustfmt::skip]
386 const TABLE_POW5: [u8; 0x051C] = [
387 5, 2, 5, 1, 2, 5, 6, 2, 5, 3, 1, 2, 5, 1, 5, 6, 2, 5, 7, 8, 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, 3, 1, 2, 5, 5, 5, 5, 1, 1, 1, 5, 1, 2, 3, 1, 2, 5, 7, 8, 2, 7, 0, 2, 1, 1, 8, 1, 5,
422 8, 3, 4, 0, 4, 5, 4, 1, 0, 1, 5, 6, 2, 5, 2, 7, 7, 5, 5, 5, 7, 5, 6, 1, 5, 6, 2, 8, 9, 1,
423 3, 5, 1, 0, 5, 9, 0, 7, 9, 1, 7, 0, 2, 2, 7, 0, 5, 0, 7, 8, 1, 2, 5, 1, 3, 8, 7, 7, 7, 8,
424 7, 8, 0, 7, 8, 1, 4, 4, 5, 6, 7, 5, 5, 2, 9, 5, 3, 9, 5, 8, 5, 1, 1, 3, 5, 2, 5, 3, 9, 0,
425 6, 2, 5, 6, 9, 3, 8, 8, 9, 3, 9, 0, 3, 9, 0, 7, 2, 2, 8, 3, 7, 7, 6, 4, 7, 6, 9, 7, 9, 2,
426 5, 5, 6, 7, 6, 2, 6, 9, 5, 3, 1, 2, 5, 3, 4, 6, 9, 4, 4, 6, 9, 5, 1, 9, 5, 3, 6, 1, 4, 1,
427 8, 8, 8, 2, 3, 8, 4, 8, 9, 6, 2, 7, 8, 3, 8, 1, 3, 4, 7, 6, 5, 6, 2, 5, 1, 7, 3, 4, 7, 2,
428 3, 4, 7, 5, 9, 7, 6, 8, 0, 7, 0, 9, 4, 4, 1, 1, 9, 2, 4, 4, 8, 1, 3, 9, 1, 9, 0, 6, 7, 3,
429 8, 2, 8, 1, 2, 5, 8, 6, 7, 3, 6, 1, 7, 3, 7, 9, 8, 8, 4, 0, 3, 5, 4, 7, 2, 0, 5, 9, 6, 2,
430 2, 4, 0, 6, 9, 5, 9, 5, 3, 3, 6, 9, 1, 4, 0, 6, 2, 5,
431 ];
432
433 shift &= 63;
434 let x_a = TABLE[shift];
435 let x_b = TABLE[shift + 1];
436 let num_new_digits = (x_a >> 11) as _;
437 let pow5_a = (0x7FF & x_a) as usize;
438 let pow5_b = (0x7FF & x_b) as usize;
439 let pow5 = &TABLE_POW5[pow5_a..];
440
441 for (i, &p5) in pow5.iter().enumerate().take(pow5_b - pow5_a) {
442 if i >= d.num_digits {
443 return num_new_digits - 1;
444 } else if d.digits[i] == p5 {
445 continue;
446 } else if d.digits[i] < p5 {
447 return num_new_digits - 1;
448 } else {
449 return num_new_digits;
450 }
451 }
452
453 num_new_digits
454 }
COMMAND: nl -ba upstream/dec2flt/mod.rs
1 //! Converting decimal strings into IEEE 754 binary floating point numbers.
2 //!
3 //! # Problem statement
4 //!
5 //! We are given a decimal string such as `12.34e56`. This string consists of integral (`12`),
6 //! fractional (`34`), and exponent (`56`) parts. All parts are optional and interpreted as a
7 //! default value (1 or 0) when missing.
8 //!
9 //! We seek the IEEE 754 floating point number that is closest to the exact value of the decimal
10 //! string. It is well-known that many decimal strings do not have terminating representations in
11 //! base two, so we round to 0.5 units in the last place (in other words, as well as possible).
12 //! Ties, decimal values exactly half-way between two consecutive floats, are resolved with the
13 //! half-to-even strategy, also known as banker's rounding.
14 //!
15 //! Needless to say, this is quite hard, both in terms of implementation complexity and in terms
16 //! of CPU cycles taken.
17 //!
18 //! # Implementation
19 //!
20 //! First, we ignore signs. Or rather, we remove it at the very beginning of the conversion
21 //! process and re-apply it at the very end. This is correct in all edge cases since IEEE
22 //! floats are symmetric around zero, negating one simply flips the first bit.
23 //!
24 //! Then we remove the decimal point by adjusting the exponent: Conceptually, `12.34e56` turns
25 //! into `1234e54`, which we describe with a positive integer `f = 1234` and an integer `e = 54`.
26 //! The `(f, e)` representation is used by almost all code past the parsing stage.
27 //!
28 //! We then try a long chain of progressively more general and expensive special cases using
29 //! machine-sized integers and small, fixed-sized floating point numbers (first `f32`/`f64`, then
30 //! a type with 64 bit significand). The extended-precision algorithm
31 //! uses the Eisel-Lemire algorithm, which uses a 128-bit (or 192-bit)
32 //! representation that can accurately and quickly compute the vast majority
33 //! of floats. When all these fail, we bite the bullet and resort to using
34 //! a large-decimal representation, shifting the digits into range, calculating
35 //! the upper significant bits and exactly round to the nearest representation.
36 //!
37 //! Another aspect that needs attention is the ``RawFloat`` trait by which almost all functions
38 //! are parametrized. One might think that it's enough to parse to `f64` and cast the result to
39 //! `f32`. Unfortunately this is not the world we live in, and this has nothing to do with using
40 //! base two or half-to-even rounding.
41 //!
42 //! Consider for example two types `d2` and `d4` representing a decimal type with two decimal
43 //! digits and four decimal digits each and take "0.01499" as input. Let's use half-up rounding.
44 //! Going directly to two decimal digits gives `0.01`, but if we round to four digits first,
45 //! we get `0.0150`, which is then rounded up to `0.02`. The same principle applies to other
46 //! operations as well, if you want 0.5 ULP accuracy you need to do *everything* in full precision
47 //! and round *exactly once, at the end*, by considering all truncated bits at once.
48 //!
49 //! Primarily, this module and its children implement the algorithms described in:
50 //! "Number Parsing at a Gigabyte per Second", available online:
51 //! .
52 //!
53 //! # Other
54 //!
55 //! The conversion should *never* panic. There are assertions and explicit panics in the code,
56 //! but they should never be triggered and only serve as internal sanity checks. Any panics should
57 //! be considered a bug.
58 //!
59 //! There are unit tests but they are woefully inadequate at ensuring correctness, they only cover
60 //! a small percentage of possible errors. Far more extensive tests are located in the directory
61 //! `src/tools/test-float-parse` as a Rust program.
62 //!
63 //! A note on integer overflow: Many parts of this file perform arithmetic with the decimal
64 //! exponent `e`. Primarily, we shift the decimal point around: Before the first decimal digit,
65 //! after the last decimal digit, and so on. This could overflow if done carelessly. We rely on
66 //! the parsing submodule to only hand out sufficiently small exponents, where "sufficient" means
67 //! "such that the exponent +/- the number of decimal digits fits into a 64 bit integer".
68 //! Larger exponents are accepted, but we don't do arithmetic with them, they are immediately
69 //! turned into {positive,negative} {zero,infinity}.
70 //!
71 //! # Notation
72 //!
73 //! This module uses the same notation as the Lemire paper:
74 //!
75 //! - `m`: binary mantissa; always nonnegative
76 //! - `p`: binary exponent; a signed integer
77 //! - `w`: decimal significand; always nonnegative
78 //! - `q`: decimal exponent; a signed integer
79 //!
80 //! This gives `m * 2^p` for the binary floating-point number, with `w * 10^q` as the decimal
81 //! equivalent.
82
83 #![doc(hidden)]
84 #![unstable(
85 feature = "dec2flt",
86 reason = "internal routines only exposed for testing",
87 issue = "none"
88 )]
89
90 use common::BiasedFp;
91 use lemire::compute_float;
92 use parse::{parse_inf_nan, parse_number};
93 use slow::parse_long_mantissa;
94
95 use crate::f64;
96 use crate::num::ParseFloatError;
97 use crate::num::float_parse::FloatErrorKind;
98 use crate::num::imp::FloatExt;
99
100 mod common;
101 pub mod decimal;
102 pub mod decimal_seq;
103 mod fpu;
104 pub mod lemire;
105 pub mod parse;
106 mod slow;
107 mod table;
108
109 /// Extension to `Float` that are necessary for parsing using the Lemire method.
110 ///
111 /// See the parent module's doc comment for why this is necessary.
112 ///
113 /// Not intended for use outside of the `dec2flt` module.
114 #[doc(hidden)]
115 pub trait Lemire: FloatExt {
116 /// Maximum exponent for a fast path case, or `⌊(SIG_BITS+1)/log2(5)⌋`
117 // assuming FLT_EVAL_METHOD = 0
118 const MAX_EXPONENT_FAST_PATH: i64 = {
119 let log2_5 = f64::consts::LOG2_10 - 1.0;
120 (Self::SIG_TOTAL_BITS as f64 / log2_5) as i64
121 };
122
123 /// Minimum exponent for a fast path case, or `-⌊(SIG_BITS+1)/log2(5)⌋`
124 const MIN_EXPONENT_FAST_PATH: i64 = -Self::MAX_EXPONENT_FAST_PATH;
125
126 /// Maximum exponent that can be represented for a disguised-fast path case.
127 /// This is `MAX_EXPONENT_FAST_PATH + ⌊(SIG_BITS+1)/log2(10)⌋`
128 const MAX_EXPONENT_DISGUISED_FAST_PATH: i64 =
129 Self::MAX_EXPONENT_FAST_PATH + (Self::SIG_TOTAL_BITS as f64 / f64::consts::LOG2_10) as i64;
130
131 /// Maximum mantissa for the fast-path (`1 << 53` for f64).
132 const MAX_MANTISSA_FAST_PATH: u64 = 1 << Self::SIG_TOTAL_BITS;
133
134 /// Gets a small power-of-ten for fast-path multiplication.
135 fn pow10_fast_path(exponent: usize) -> Self;
136
137 /// Converts integer into float through an as cast.
138 /// This is only called in the fast-path algorithm, and therefore
139 /// will not lose precision, since the value will always have
140 /// only if the value is <= Self::MAX_MANTISSA_FAST_PATH.
141 fn from_u64(v: u64) -> Self;
142 }
143
144 #[cfg(target_has_reliable_f16)]
145 impl Lemire for f16 {
146 fn pow10_fast_path(exponent: usize) -> Self {
147 #[allow(clippy::use_self)]
148 const TABLE: [f16; 8] = [1e0, 1e1, 1e2, 1e3, 1e4, 0.0, 0.0, 0.];
149 TABLE[exponent & 7]
150 }
151
152 #[inline]
153 fn from_u64(v: u64) -> Self {
154 debug_assert!(v <= Self::MAX_MANTISSA_FAST_PATH);
155 v as _
156 }
157 }
158
159 impl Lemire for f32 {
160 fn pow10_fast_path(exponent: usize) -> Self {
161 #[allow(clippy::use_self)]
162 const TABLE: [f32; 16] =
163 [1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 0., 0., 0., 0., 0.];
164 TABLE[exponent & 15]
165 }
166
167 #[inline]
168 fn from_u64(v: u64) -> Self {
169 debug_assert!(v <= Self::MAX_MANTISSA_FAST_PATH);
170 v as _
171 }
172 }
173
174 impl Lemire for f64 {
175 fn pow10_fast_path(exponent: usize) -> Self {
176 const TABLE: [f64; 32] = [
177 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15,
178 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22, 0., 0., 0., 0., 0., 0., 0., 0., 0.,
179 ];
180 TABLE[exponent & 31]
181 }
182
183 #[inline]
184 fn from_u64(v: u64) -> Self {
185 debug_assert!(v <= Self::MAX_MANTISSA_FAST_PATH);
186 v as _
187 }
188 }
189
190 #[inline]
191 pub(super) fn pfe_empty() -> ParseFloatError {
192 ParseFloatError { kind: FloatErrorKind::Empty }
193 }
194
195 // Used in unit tests, keep public.
196 // This is much better than making FloatErrorKind and ParseFloatError::kind public.
197 #[inline]
198 pub fn pfe_invalid() -> ParseFloatError {
199 ParseFloatError { kind: FloatErrorKind::Invalid }
200 }
201
202 /// Converts a `BiasedFp` to the closest machine float type.
203 fn biased_fp_to_float(x: BiasedFp) -> F {
204 let mut word = x.m;
205 word |= (x.p_biased as u64) << F::SIG_BITS;
206 F::from_u64_bits(word)
207 }
208
209 /// Converts a decimal string into a floating point number.
210 #[inline(always)] // Will be inlined into a function with `#[inline(never)]`, see above
211 pub fn dec2flt(s: &str) -> Result {
212 let mut s = s.as_bytes();
213 let Some(&c) = s.first() else { return Err(pfe_empty()) };
214 let negative = c == b'-';
215 if c == b'-' || c == b'+' {
216 s = &s[1..];
217 }
218 if s.is_empty() {
219 return Err(pfe_invalid());
220 }
221
222 let mut num = match parse_number(s) {
223 Some(r) => r,
224 None if let Some(value) = parse_inf_nan(s, negative) => return Ok(value),
225 None => return Err(pfe_invalid()),
226 };
227 num.negative = negative;
228 if !cfg!(feature = "optimize_for_size") {
229 if let Some(value) = num.try_fast_path::() {
230 return Ok(value);
231 }
232 }
233
234 // If significant digits were truncated, then we can have rounding error
235 // only if `mantissa + 1` produces a different result. We also avoid
236 // redundantly using the Eisel-Lemire algorithm if it was unable to
237 // correctly round on the first pass.
238 let mut fp = compute_float::(num.exponent, num.mantissa);
239 if num.many_digits
240 && fp.p_biased >= 0
241 && fp != compute_float::(num.exponent, num.mantissa + 1)
242 {
243 fp.p_biased = -1;
244 }
245 // Unable to correctly round the float using the Eisel-Lemire algorithm.
246 // Fallback to a slower, but always correct algorithm.
247 if fp.p_biased < 0 {
248 fp = parse_long_mantissa::(s);
249 }
250
251 let mut float = biased_fp_to_float::(fp);
252 if num.negative {
253 float = -float;
254 }
255 Ok(float)
256 }
COMMAND: nl -ba crate/dec2flt/mod.rs
1 //! Converting decimal strings into IEEE 754 binary floating point numbers.
2 //!
3 //! # Problem statement
4 //!
5 //! We are given a decimal string such as `12.34e56`. This string consists of integral (`12`),
6 //! fractional (`34`), and exponent (`56`) parts. All parts are optional and interpreted as a
7 //! default value (1 or 0) when missing.
8 //!
9 //! We seek the IEEE 754 floating point number that is closest to the exact value of the decimal
10 //! string. It is well-known that many decimal strings do not have terminating representations in
11 //! base two, so we round to 0.5 units in the last place (in other words, as well as possible).
12 //! Ties, decimal values exactly half-way between two consecutive floats, are resolved with the
13 //! half-to-even strategy, also known as banker's rounding.
14 //!
15 //! Needless to say, this is quite hard, both in terms of implementation complexity and in terms
16 //! of CPU cycles taken.
17 //!
18 //! # Implementation
19 //!
20 //! First, we ignore signs. Or rather, we remove it at the very beginning of the conversion
21 //! process and re-apply it at the very end. This is correct in all edge cases since IEEE
22 //! floats are symmetric around zero, negating one simply flips the first bit.
23 //!
24 //! Then we remove the decimal point by adjusting the exponent: Conceptually, `12.34e56` turns
25 //! into `1234e54`, which we describe with a positive integer `f = 1234` and an integer `e = 54`.
26 //! The `(f, e)` representation is used by almost all code past the parsing stage.
27 //!
28 //! We then try a long chain of progressively more general and expensive special cases using
29 //! machine-sized integers and small, fixed-sized floating point numbers (first `f32`/`f64`, then
30 //! a type with 64 bit significand). The extended-precision algorithm
31 //! uses the Eisel-Lemire algorithm, which uses a 128-bit (or 192-bit)
32 //! representation that can accurately and quickly compute the vast majority
33 //! of floats. When all these fail, we bite the bullet and resort to using
34 //! a large-decimal representation, shifting the digits into range, calculating
35 //! the upper significant bits and exactly round to the nearest representation.
36 //!
37 //! Another aspect that needs attention is the ``RawFloat`` trait by which almost all functions
38 //! are parametrized. One might think that it's enough to parse to `f64` and cast the result to
39 //! `f32`. Unfortunately this is not the world we live in, and this has nothing to do with using
40 //! base two or half-to-even rounding.
41 //!
42 //! Consider for example two types `d2` and `d4` representing a decimal type with two decimal
43 //! digits and four decimal digits each and take "0.01499" as input. Let's use half-up rounding.
44 //! Going directly to two decimal digits gives `0.01`, but if we round to four digits first,
45 //! we get `0.0150`, which is then rounded up to `0.02`. The same principle applies to other
46 //! operations as well, if you want 0.5 ULP accuracy you need to do *everything* in full precision
47 //! and round *exactly once, at the end*, by considering all truncated bits at once.
48 //!
49 //! Primarily, this module and its children implement the algorithms described in:
50 //! "Number Parsing at a Gigabyte per Second", available online:
51 //! .
52 //!
53 //! # Other
54 //!
55 //! The conversion should *never* panic. There are assertions and explicit panics in the code,
56 //! but they should never be triggered and only serve as internal sanity checks. Any panics should
57 //! be considered a bug.
58 //!
59 //! There are unit tests but they are woefully inadequate at ensuring correctness, they only cover
60 //! a small percentage of possible errors. Far more extensive tests are located in the directory
61 //! `src/tools/test-float-parse` as a Rust program.
62 //!
63 //! A note on integer overflow: Many parts of this file perform arithmetic with the decimal
64 //! exponent `e`. Primarily, we shift the decimal point around: Before the first decimal digit,
65 //! after the last decimal digit, and so on. This could overflow if done carelessly. We rely on
66 //! the parsing submodule to only hand out sufficiently small exponents, where "sufficient" means
67 //! "such that the exponent +/- the number of decimal digits fits into a 64 bit integer".
68 //! Larger exponents are accepted, but we don't do arithmetic with them, they are immediately
69 //! turned into {positive,negative} {zero,infinity}.
70 //!
71 //! # Notation
72 //!
73 //! This module uses the same notation as the Lemire paper:
74 //!
75 //! - `m`: binary mantissa; always nonnegative
76 //! - `p`: binary exponent; a signed integer
77 //! - `w`: decimal significand; always nonnegative
78 //! - `q`: decimal exponent; a signed integer
79 //!
80 //! This gives `m * 2^p` for the binary floating-point number, with `w * 10^q` as the decimal
81 //! equivalent.
82
83 #![doc(hidden)]
84 #![unstable(
85 feature = "dec2flt",
86 reason = "internal routines only exposed for testing",
87 issue = "none"
88 )]
89
90 pub use common::BiasedFp;
91 use lemire::compute_float;
92 use parse::{parse_inf_nan, parse_number};
93 use slow::parse_long_mantissa;
94
95 use crate::f64;
96 use crate::num::ParseFloatError;
97 use crate::num::float_parse::FloatErrorKind;
98 use crate::num::imp::FloatExt;
99
100 mod common;
101 pub mod decimal;
102 pub mod decimal_seq;
103 mod fpu;
104 pub mod lemire;
105 pub mod parse;
106 mod slow;
107 mod table;
108
109 /// Extension to `Float` that are necessary for parsing using the Lemire method.
110 ///
111 /// See the parent module's doc comment for why this is necessary.
112 ///
113 /// Not intended for use outside of the `dec2flt` module.
114 #[doc(hidden)]
115 pub trait Lemire: FloatExt {
116 /// Maximum exponent for a fast path case, or `⌊(SIG_BITS+1)/log2(5)⌋`
117 // assuming FLT_EVAL_METHOD = 0
118 const MAX_EXPONENT_FAST_PATH: i64;
119
120 /// Minimum exponent for a fast path case, or `-⌊(SIG_BITS+1)/log2(5)⌋`
121 const MIN_EXPONENT_FAST_PATH: i64 = -Self::MAX_EXPONENT_FAST_PATH;
122
123 /// Maximum exponent that can be represented for a disguised-fast path case.
124 /// This is `MAX_EXPONENT_FAST_PATH + ⌊(SIG_BITS+1)/log2(10)⌋`
125 const MAX_EXPONENT_DISGUISED_FAST_PATH: i64;
126
127 /// Maximum mantissa for the fast-path (`1 << 53` for f64).
128 const MAX_MANTISSA_FAST_PATH: u64 = 1 << Self::SIG_TOTAL_BITS;
129
130 /// Gets a small power-of-ten for fast-path multiplication.
131 fn pow10_fast_path(exponent: usize) -> Self;
132
133 /// Converts integer into float through an as cast.
134 /// This is only called in the fast-path algorithm, and therefore
135 /// will not lose precision, since the value will always have
136 /// only if the value is <= Self::MAX_MANTISSA_FAST_PATH.
137 fn from_u64(v: u64) -> Self;
138 }
139
140 #[cfg(target_has_reliable_f16)]
141 // The f16 Lemire instance is outside the exclusively f64 scope. Disabling it
142 // leaves every retained f64 parser/helper/trace body, native decision, checked
143 // operation, debug assertion, return value, and scoped observation unchanged.
144 #[cfg(any())]
145 impl Lemire for f16 {
146 // These are the exact integer results of the upstream compile-time float
147 // formulae for `SIG_TOTAL_BITS = 11`: floor(11/log2(5)) = 4 and
148 // 4 + floor(11/log2(10)) = 7. Concrete integers avoid unsupported const
149 // float arithmetic without changing either fast-path guard.
150 const MAX_EXPONENT_FAST_PATH: i64 = 4;
151 const MAX_EXPONENT_DISGUISED_FAST_PATH: i64 = 7;
152
153 fn pow10_fast_path(exponent: usize) -> Self {
154 // Each integer is the exact IEEE encoding of the corresponding
155 // upstream table literal; the masked lookup and fallback zeros are
156 // unchanged. Aeneas cannot translate arrays containing float values.
157 match exponent & 7 {
158 0 => f16::from_bits(0x3C00),
159 1 => f16::from_bits(0x4900),
160 2 => f16::from_bits(0x5640),
161 3 => f16::from_bits(0x63D0),
162 4 => f16::from_bits(0x70E2),
163 _ => f16::from_bits(0),
164 }
165 }
166
167 #[inline]
168 // This method is exactly the upstream primitive `u64 as f16` conversion.
169 // Charon extracts the cast, but Aeneas reports it unreachable; making only
170 // this primitive boundary opaque preserves all guards and dispatcher logic.
171 #[charon::opaque]
172 fn from_u64(v: u64) -> Self {
173 debug_assert!(v <= Self::MAX_MANTISSA_FAST_PATH);
174 v as _
175 }
176 }
177
178 // The f32 Lemire instance is likewise unused by the retained f64
179 // specialization, so disabling it cannot affect any retained body or observed
180 // f64 execution independently of the correctness GOALs.
181 #[cfg(any())]
182 impl Lemire for f32 {
183 // Exact upstream formula results for `SIG_TOTAL_BITS = 24`.
184 const MAX_EXPONENT_FAST_PATH: i64 = 10;
185 const MAX_EXPONENT_DISGUISED_FAST_PATH: i64 = 17;
186
187 fn pow10_fast_path(exponent: usize) -> Self {
188 // Bit constructors preserve the exact table values and masked lookup,
189 // while avoiding Aeneas's unsupported float-valued array constants.
190 match exponent & 15 {
191 0 => f32::from_bits(0x3F80_0000),
192 1 => f32::from_bits(0x4120_0000),
193 2 => f32::from_bits(0x42C8_0000),
194 3 => f32::from_bits(0x447A_0000),
195 4 => f32::from_bits(0x461C_4000),
196 5 => f32::from_bits(0x47C3_5000),
197 6 => f32::from_bits(0x4974_2400),
198 7 => f32::from_bits(0x4B18_9680),
199 8 => f32::from_bits(0x4CBE_BC20),
200 9 => f32::from_bits(0x4E6E_6B28),
201 10 => f32::from_bits(0x5015_02F9),
202 _ => f32::from_bits(0),
203 }
204 }
205
206 #[inline]
207 // This is exactly the source `u64 as f32` conversion. The narrow opaque
208 // boundary is required because Aeneas rejects the primitive cast itself;
209 // its input guard and every caller remain transparent.
210 #[charon::opaque]
211 fn from_u64(v: u64) -> Self {
212 debug_assert!(v <= Self::MAX_MANTISSA_FAST_PATH);
213 v as _
214 }
215 }
216
217 impl Lemire for f64 {
218 // Exact upstream formula results for `SIG_TOTAL_BITS = 53`.
219 const MAX_EXPONENT_FAST_PATH: i64 = 22;
220 const MAX_EXPONENT_DISGUISED_FAST_PATH: i64 = 37;
221
222 fn pow10_fast_path(exponent: usize) -> Self {
223 // These bit patterns are exactly the source table's rounded binary64
224 // literals. The match is the same masked lookup; it merely keeps float
225 // constants out of Aeneas's unsupported constant interpreter.
226 match exponent & 31 {
227 0 => f64::from_bits(0x3FF0_0000_0000_0000),
228 1 => f64::from_bits(0x4024_0000_0000_0000),
229 2 => f64::from_bits(0x4059_0000_0000_0000),
230 3 => f64::from_bits(0x408F_4000_0000_0000),
231 4 => f64::from_bits(0x40C3_8800_0000_0000),
232 5 => f64::from_bits(0x40F8_6A00_0000_0000),
233 6 => f64::from_bits(0x412E_8480_0000_0000),
234 7 => f64::from_bits(0x4163_12D0_0000_0000),
235 8 => f64::from_bits(0x4197_D784_0000_0000),
236 9 => f64::from_bits(0x41CD_CD65_0000_0000),
237 10 => f64::from_bits(0x4202_A05F_2000_0000),
238 11 => f64::from_bits(0x4237_4876_E800_0000),
239 12 => f64::from_bits(0x426D_1A94_A200_0000),
240 13 => f64::from_bits(0x42A2_309C_E540_0000),
241 14 => f64::from_bits(0x42D6_BCC4_1E90_0000),
242 15 => f64::from_bits(0x430C_6BF5_2634_0000),
243 16 => f64::from_bits(0x4341_C379_37E0_8000),
244 17 => f64::from_bits(0x4376_3457_85D8_A000),
245 18 => f64::from_bits(0x43AB_C16D_674E_C800),
246 19 => f64::from_bits(0x43E1_58E4_6091_3D00),
247 20 => f64::from_bits(0x4415_AF1D_78B5_8C40),
248 21 => f64::from_bits(0x444B_1AE4_D6E2_EF50),
249 22 => f64::from_bits(0x4480_F0CF_064D_D592),
250 _ => f64::from_bits(0),
251 }
252 }
253
254 #[inline]
255 // Aeneas cannot translate the source `u64 as f64` primitive conversion, so
256 // `charon::opaque` makes this entire asserted conversion external: both the
257 // unchanged `debug_assert!` and the unchanged cast below are in the opaque
258 // body. The callers, their fast-path guards, and their surrounding
259 // computation remain mechanically visible. A corresponding model binding
260 // must fail the assertion above `MAX_MANTISSA_FAST_PATH` and return the
261 // exact binary64 conversion at or below that bound.
262 #[charon::opaque]
263 fn from_u64(v: u64) -> Self {
264 debug_assert!(v <= Self::MAX_MANTISSA_FAST_PATH);
265 v as _
266 }
267 }
268
269 #[inline]
270 pub(super) fn pfe_empty() -> ParseFloatError {
271 ParseFloatError { kind: FloatErrorKind::Empty }
272 }
273
274 // Used in unit tests, keep public.
275 // This is much better than making FloatErrorKind and ParseFloatError::kind public.
276 #[inline]
277 pub fn pfe_invalid() -> ParseFloatError {
278 ParseFloatError { kind: FloatErrorKind::Invalid }
279 }
280
281 /// Converts a `BiasedFp` to the closest machine float type.
282 fn biased_fp_to_float(x: BiasedFp) -> F {
283 let mut word = x.m;
284 word |= (x.p_biased as u64) << F::SIG_BITS;
285 F::from_u64_bits(word)
286 }
287
288 /// Observable control-flow record for a dispatcher execution.
289 ///
290 /// These variants add no decisions to the conversion: each stores values
291 /// already computed at the corresponding source branch. In particular, the
292 /// first component returned by `dec2flt_with_trace` is the ordinary parser
293 /// result, so projecting it preserves every public source observation without
294 /// assuming any correctness goal.
295 pub enum Dec2FltTrace<'a, F> {
296 /// The original string was empty; no helper was called.
297 EmptyInput,
298 /// Removing one lexical sign left an empty body; no helper was called.
299 SignOnly { body: &'a [u8], negative: bool },
300 /// Both lexical helpers returned `None`; no raw pair was selected.
301 Invalid {
302 body: &'a [u8],
303 negative: bool,
304 parse_number_result: Option,
305 parse_inf_nan_result: Option,
306 },
307 /// The special helper supplied the directly returned value; no pair was selected.
308 Special {
309 body: &'a [u8],
310 negative: bool,
311 parse_number_result: Option,
312 parse_inf_nan_result: Option,
313 result: F,
314 },
315 /// The ordinary native shortcut supplied the directly returned value.
316 FastPath {
317 body: &'a [u8],
318 negative: bool,
319 parse_number_result: Option,
320 fast_path_input: decimal::Decimal,
321 fast_path_result: Option,
322 result: F,
323 },
324 /// The integer/slow path selected and assembled one raw pair.
325 Assembled(Dec2FltAssemblyTrace<'a, F>),
326 }
327
328 /// Full observation record for the dispatcher path that performs final assembly.
329 pub struct Dec2FltAssemblyTrace<'a, F> {
330 pub body: &'a [u8],
331 pub negative: bool,
332 pub parse_number_result: Option,
333 pub fast_path_input: decimal::Decimal,
334 pub fast_path_result: Option,
335 pub first_compute_exponent: i64,
336 pub first_compute_mantissa: u64,
337 pub first_compute_result: BiasedFp,
338 pub second_compute_guard: bool,
339 pub second_compute_exponent: Option,
340 pub second_compute_mantissa: Option,
341 pub second_compute_result: Option,
342 pub second_equals_first: Option,
343 pub forced_deferral: bool,
344 pub post_comparison_pair: BiasedFp,
345 pub slow_path_guard: bool,
346 pub slow_path_result: Option,
347 pub selected_pair: BiasedFp,
348 pub assembled_word: u64,
349 pub assembly_result: F,
350 pub lexical_sign_applied: bool,
351 pub result: F,
352 }
353
354 /// Run the actual dispatcher while retaining its goal-relevant internal observations.
355 pub fn dec2flt_with_trace<
356 'a,
357 F: Lemire
358 + core::ops::Div