1 | // Copyright 2010 the V8 project authors. All rights reserved. |
2 | // Redistribution and use in source and binary forms, with or without |
3 | // modification, are permitted provided that the following conditions are |
4 | // met: |
5 | // |
6 | // * Redistributions of source code must retain the above copyright |
7 | // notice, this list of conditions and the following disclaimer. |
8 | // * Redistributions in binary form must reproduce the above |
9 | // copyright notice, this list of conditions and the following |
10 | // disclaimer in the documentation and/or other materials provided |
11 | // with the distribution. |
12 | // * Neither the name of Google Inc. nor the names of its |
13 | // contributors may be used to endorse or promote products derived |
14 | // from this software without specific prior written permission. |
15 | // |
16 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
17 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
18 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
19 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
20 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
21 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
22 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
23 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
24 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
25 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
26 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
27 | |
28 | #include <climits> |
29 | #include <cstdarg> |
30 | |
31 | #include <double-conversion/bignum.h> |
32 | #include <double-conversion/cached-powers.h> |
33 | #include <double-conversion/ieee.h> |
34 | #include <double-conversion/strtod.h> |
35 | |
36 | namespace double_conversion { |
37 | |
38 | // 2^53 = 9007199254740992. |
39 | // Any integer with at most 15 decimal digits will hence fit into a double |
40 | // (which has a 53bit significand) without loss of precision. |
41 | static const int kMaxExactDoubleIntegerDecimalDigits = 15; |
42 | // 2^64 = 18446744073709551616 > 10^19 |
43 | static const int kMaxUint64DecimalDigits = 19; |
44 | |
45 | // Max double: 1.7976931348623157 x 10^308 |
46 | // Min non-zero double: 4.9406564584124654 x 10^-324 |
47 | // Any x >= 10^309 is interpreted as +infinity. |
48 | // Any x <= 10^-324 is interpreted as 0. |
49 | // Note that 2.5e-324 (despite being smaller than the min double) will be read |
50 | // as non-zero (equal to the min non-zero double). |
51 | static const int kMaxDecimalPower = 309; |
52 | static const int kMinDecimalPower = -324; |
53 | |
54 | // 2^64 = 18446744073709551616 |
55 | static const uint64_t kMaxUint64 = UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF); |
56 | |
57 | |
58 | static const double exact_powers_of_ten[] = { |
59 | 1.0, // 10^0 |
60 | 10.0, |
61 | 100.0, |
62 | 1000.0, |
63 | 10000.0, |
64 | 100000.0, |
65 | 1000000.0, |
66 | 10000000.0, |
67 | 100000000.0, |
68 | 1000000000.0, |
69 | 10000000000.0, // 10^10 |
70 | 100000000000.0, |
71 | 1000000000000.0, |
72 | 10000000000000.0, |
73 | 100000000000000.0, |
74 | 1000000000000000.0, |
75 | 10000000000000000.0, |
76 | 100000000000000000.0, |
77 | 1000000000000000000.0, |
78 | 10000000000000000000.0, |
79 | 100000000000000000000.0, // 10^20 |
80 | 1000000000000000000000.0, |
81 | // 10^22 = 0x21e19e0c9bab2400000 = 0x878678326eac9 * 2^22 |
82 | 10000000000000000000000.0 |
83 | }; |
84 | static const int kExactPowersOfTenSize = ARRAY_SIZE(exact_powers_of_ten); |
85 | |
86 | // Maximum number of significant digits in the decimal representation. |
87 | // In fact the value is 772 (see conversions.cc), but to give us some margin |
88 | // we round up to 780. |
89 | static const int kMaxSignificantDecimalDigits = 780; |
90 | |
91 | static Vector<const char> TrimLeadingZeros(Vector<const char> buffer) { |
92 | for (int i = 0; i < buffer.length(); i++) { |
93 | if (buffer[i] != '0') { |
94 | return buffer.SubVector(from: i, to: buffer.length()); |
95 | } |
96 | } |
97 | return Vector<const char>(buffer.start(), 0); |
98 | } |
99 | |
100 | |
101 | static Vector<const char> TrimTrailingZeros(Vector<const char> buffer) { |
102 | for (int i = buffer.length() - 1; i >= 0; --i) { |
103 | if (buffer[i] != '0') { |
104 | return buffer.SubVector(from: 0, to: i + 1); |
105 | } |
106 | } |
107 | return Vector<const char>(buffer.start(), 0); |
108 | } |
109 | |
110 | |
111 | static void CutToMaxSignificantDigits(Vector<const char> buffer, |
112 | int exponent, |
113 | char* significant_buffer, |
114 | int* significant_exponent) { |
115 | for (int i = 0; i < kMaxSignificantDecimalDigits - 1; ++i) { |
116 | significant_buffer[i] = buffer[i]; |
117 | } |
118 | // The input buffer has been trimmed. Therefore the last digit must be |
119 | // different from '0'. |
120 | ASSERT(buffer[buffer.length() - 1] != '0'); |
121 | // Set the last digit to be non-zero. This is sufficient to guarantee |
122 | // correct rounding. |
123 | significant_buffer[kMaxSignificantDecimalDigits - 1] = '1'; |
124 | *significant_exponent = |
125 | exponent + (buffer.length() - kMaxSignificantDecimalDigits); |
126 | } |
127 | |
128 | |
129 | // Trims the buffer and cuts it to at most kMaxSignificantDecimalDigits. |
130 | // If possible the input-buffer is reused, but if the buffer needs to be |
131 | // modified (due to cutting), then the input needs to be copied into the |
132 | // buffer_copy_space. |
133 | static void TrimAndCut(Vector<const char> buffer, int exponent, |
134 | char* buffer_copy_space, int space_size, |
135 | Vector<const char>* trimmed, int* updated_exponent) { |
136 | Vector<const char> left_trimmed = TrimLeadingZeros(buffer); |
137 | Vector<const char> right_trimmed = TrimTrailingZeros(buffer: left_trimmed); |
138 | exponent += left_trimmed.length() - right_trimmed.length(); |
139 | if (right_trimmed.length() > kMaxSignificantDecimalDigits) { |
140 | (void) space_size; // Mark variable as used. |
141 | ASSERT(space_size >= kMaxSignificantDecimalDigits); |
142 | CutToMaxSignificantDigits(buffer: right_trimmed, exponent, |
143 | significant_buffer: buffer_copy_space, significant_exponent: updated_exponent); |
144 | *trimmed = Vector<const char>(buffer_copy_space, |
145 | kMaxSignificantDecimalDigits); |
146 | } else { |
147 | *trimmed = right_trimmed; |
148 | *updated_exponent = exponent; |
149 | } |
150 | } |
151 | |
152 | |
153 | // Reads digits from the buffer and converts them to a uint64. |
154 | // Reads in as many digits as fit into a uint64. |
155 | // When the string starts with "1844674407370955161" no further digit is read. |
156 | // Since 2^64 = 18446744073709551616 it would still be possible read another |
157 | // digit if it was less or equal than 6, but this would complicate the code. |
158 | static uint64_t ReadUint64(Vector<const char> buffer, |
159 | int* number_of_read_digits) { |
160 | uint64_t result = 0; |
161 | int i = 0; |
162 | while (i < buffer.length() && result <= (kMaxUint64 / 10 - 1)) { |
163 | int digit = buffer[i++] - '0'; |
164 | ASSERT(0 <= digit && digit <= 9); |
165 | result = 10 * result + digit; |
166 | } |
167 | *number_of_read_digits = i; |
168 | return result; |
169 | } |
170 | |
171 | |
172 | // Reads a DiyFp from the buffer. |
173 | // The returned DiyFp is not necessarily normalized. |
174 | // If remaining_decimals is zero then the returned DiyFp is accurate. |
175 | // Otherwise it has been rounded and has error of at most 1/2 ulp. |
176 | static void ReadDiyFp(Vector<const char> buffer, |
177 | DiyFp* result, |
178 | int* remaining_decimals) { |
179 | int read_digits; |
180 | uint64_t significand = ReadUint64(buffer, number_of_read_digits: &read_digits); |
181 | if (buffer.length() == read_digits) { |
182 | *result = DiyFp(significand, 0); |
183 | *remaining_decimals = 0; |
184 | } else { |
185 | // Round the significand. |
186 | if (buffer[read_digits] >= '5') { |
187 | significand++; |
188 | } |
189 | // Compute the binary exponent. |
190 | int exponent = 0; |
191 | *result = DiyFp(significand, exponent); |
192 | *remaining_decimals = buffer.length() - read_digits; |
193 | } |
194 | } |
195 | |
196 | |
197 | static bool DoubleStrtod(Vector<const char> trimmed, |
198 | int exponent, |
199 | double* result) { |
200 | #if !defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS) |
201 | // NB: Qt uses -Werror=unused-parameter which results in compiler error here |
202 | // in this branch. Using "(void)x" idiom to prevent the error. |
203 | (void)trimmed; |
204 | (void)exponent; |
205 | (void)result; |
206 | |
207 | // On x86 the floating-point stack can be 64 or 80 bits wide. If it is |
208 | // 80 bits wide (as is the case on Linux) then double-rounding occurs and the |
209 | // result is not accurate. |
210 | // We know that Windows32 uses 64 bits and is therefore accurate. |
211 | // Note that the ARM simulator is compiled for 32bits. It therefore exhibits |
212 | // the same problem. |
213 | return false; |
214 | #else |
215 | if (trimmed.length() <= kMaxExactDoubleIntegerDecimalDigits) { |
216 | int read_digits; |
217 | // The trimmed input fits into a double. |
218 | // If the 10^exponent (resp. 10^-exponent) fits into a double too then we |
219 | // can compute the result-double simply by multiplying (resp. dividing) the |
220 | // two numbers. |
221 | // This is possible because IEEE guarantees that floating-point operations |
222 | // return the best possible approximation. |
223 | if (exponent < 0 && -exponent < kExactPowersOfTenSize) { |
224 | // 10^-exponent fits into a double. |
225 | *result = static_cast<double>(ReadUint64(buffer: trimmed, number_of_read_digits: &read_digits)); |
226 | ASSERT(read_digits == trimmed.length()); |
227 | *result /= exact_powers_of_ten[-exponent]; |
228 | return true; |
229 | } |
230 | if (0 <= exponent && exponent < kExactPowersOfTenSize) { |
231 | // 10^exponent fits into a double. |
232 | *result = static_cast<double>(ReadUint64(buffer: trimmed, number_of_read_digits: &read_digits)); |
233 | ASSERT(read_digits == trimmed.length()); |
234 | *result *= exact_powers_of_ten[exponent]; |
235 | return true; |
236 | } |
237 | int remaining_digits = |
238 | kMaxExactDoubleIntegerDecimalDigits - trimmed.length(); |
239 | if ((0 <= exponent) && |
240 | (exponent - remaining_digits < kExactPowersOfTenSize)) { |
241 | // The trimmed string was short and we can multiply it with |
242 | // 10^remaining_digits. As a result the remaining exponent now fits |
243 | // into a double too. |
244 | *result = static_cast<double>(ReadUint64(buffer: trimmed, number_of_read_digits: &read_digits)); |
245 | ASSERT(read_digits == trimmed.length()); |
246 | *result *= exact_powers_of_ten[remaining_digits]; |
247 | *result *= exact_powers_of_ten[exponent - remaining_digits]; |
248 | return true; |
249 | } |
250 | } |
251 | return false; |
252 | #endif |
253 | } |
254 | |
255 | |
256 | // Returns 10^exponent as an exact DiyFp. |
257 | // The given exponent must be in the range [1; kDecimalExponentDistance[. |
258 | static DiyFp AdjustmentPowerOfTen(int exponent) { |
259 | ASSERT(0 < exponent); |
260 | ASSERT(exponent < PowersOfTenCache::kDecimalExponentDistance); |
261 | // Simply hardcode the remaining powers for the given decimal exponent |
262 | // distance. |
263 | ASSERT(PowersOfTenCache::kDecimalExponentDistance == 8); |
264 | switch (exponent) { |
265 | case 1: return DiyFp(UINT64_2PART_C(0xa0000000, 00000000), -60); |
266 | case 2: return DiyFp(UINT64_2PART_C(0xc8000000, 00000000), -57); |
267 | case 3: return DiyFp(UINT64_2PART_C(0xfa000000, 00000000), -54); |
268 | case 4: return DiyFp(UINT64_2PART_C(0x9c400000, 00000000), -50); |
269 | case 5: return DiyFp(UINT64_2PART_C(0xc3500000, 00000000), -47); |
270 | case 6: return DiyFp(UINT64_2PART_C(0xf4240000, 00000000), -44); |
271 | case 7: return DiyFp(UINT64_2PART_C(0x98968000, 00000000), -40); |
272 | default: |
273 | UNREACHABLE(); |
274 | } |
275 | } |
276 | |
277 | |
278 | // If the function returns true then the result is the correct double. |
279 | // Otherwise it is either the correct double or the double that is just below |
280 | // the correct double. |
281 | static bool DiyFpStrtod(Vector<const char> buffer, |
282 | int exponent, |
283 | double* result) { |
284 | DiyFp input; |
285 | int remaining_decimals; |
286 | ReadDiyFp(buffer, result: &input, remaining_decimals: &remaining_decimals); |
287 | // Since we may have dropped some digits the input is not accurate. |
288 | // If remaining_decimals is different than 0 than the error is at most |
289 | // .5 ulp (unit in the last place). |
290 | // We don't want to deal with fractions and therefore keep a common |
291 | // denominator. |
292 | const int kDenominatorLog = 3; |
293 | const int kDenominator = 1 << kDenominatorLog; |
294 | // Move the remaining decimals into the exponent. |
295 | exponent += remaining_decimals; |
296 | uint64_t error = (remaining_decimals == 0 ? 0 : kDenominator / 2); |
297 | |
298 | int old_e = input.e(); |
299 | input.Normalize(); |
300 | error <<= old_e - input.e(); |
301 | |
302 | ASSERT(exponent <= PowersOfTenCache::kMaxDecimalExponent); |
303 | if (exponent < PowersOfTenCache::kMinDecimalExponent) { |
304 | *result = 0.0; |
305 | return true; |
306 | } |
307 | DiyFp cached_power; |
308 | int cached_decimal_exponent; |
309 | PowersOfTenCache::GetCachedPowerForDecimalExponent(requested_exponent: exponent, |
310 | power: &cached_power, |
311 | found_exponent: &cached_decimal_exponent); |
312 | |
313 | if (cached_decimal_exponent != exponent) { |
314 | int adjustment_exponent = exponent - cached_decimal_exponent; |
315 | DiyFp adjustment_power = AdjustmentPowerOfTen(exponent: adjustment_exponent); |
316 | input.Multiply(other: adjustment_power); |
317 | if (kMaxUint64DecimalDigits - buffer.length() >= adjustment_exponent) { |
318 | // The product of input with the adjustment power fits into a 64 bit |
319 | // integer. |
320 | ASSERT(DiyFp::kSignificandSize == 64); |
321 | } else { |
322 | // The adjustment power is exact. There is hence only an error of 0.5. |
323 | error += kDenominator / 2; |
324 | } |
325 | } |
326 | |
327 | input.Multiply(other: cached_power); |
328 | // The error introduced by a multiplication of a*b equals |
329 | // error_a + error_b + error_a*error_b/2^64 + 0.5 |
330 | // Substituting a with 'input' and b with 'cached_power' we have |
331 | // error_b = 0.5 (all cached powers have an error of less than 0.5 ulp), |
332 | // error_ab = 0 or 1 / kDenominator > error_a*error_b/ 2^64 |
333 | int error_b = kDenominator / 2; |
334 | int error_ab = (error == 0 ? 0 : 1); // We round up to 1. |
335 | int fixed_error = kDenominator / 2; |
336 | error += error_b + error_ab + fixed_error; |
337 | |
338 | old_e = input.e(); |
339 | input.Normalize(); |
340 | error <<= old_e - input.e(); |
341 | |
342 | // See if the double's significand changes if we add/subtract the error. |
343 | int order_of_magnitude = DiyFp::kSignificandSize + input.e(); |
344 | int effective_significand_size = |
345 | Double::SignificandSizeForOrderOfMagnitude(order: order_of_magnitude); |
346 | int precision_digits_count = |
347 | DiyFp::kSignificandSize - effective_significand_size; |
348 | if (precision_digits_count + kDenominatorLog >= DiyFp::kSignificandSize) { |
349 | // This can only happen for very small denormals. In this case the |
350 | // half-way multiplied by the denominator exceeds the range of an uint64. |
351 | // Simply shift everything to the right. |
352 | int shift_amount = (precision_digits_count + kDenominatorLog) - |
353 | DiyFp::kSignificandSize + 1; |
354 | input.set_f(input.f() >> shift_amount); |
355 | input.set_e(input.e() + shift_amount); |
356 | // We add 1 for the lost precision of error, and kDenominator for |
357 | // the lost precision of input.f(). |
358 | error = (error >> shift_amount) + 1 + kDenominator; |
359 | precision_digits_count -= shift_amount; |
360 | } |
361 | // We use uint64_ts now. This only works if the DiyFp uses uint64_ts too. |
362 | ASSERT(DiyFp::kSignificandSize == 64); |
363 | ASSERT(precision_digits_count < 64); |
364 | uint64_t one64 = 1; |
365 | uint64_t precision_bits_mask = (one64 << precision_digits_count) - 1; |
366 | uint64_t precision_bits = input.f() & precision_bits_mask; |
367 | uint64_t half_way = one64 << (precision_digits_count - 1); |
368 | precision_bits *= kDenominator; |
369 | half_way *= kDenominator; |
370 | DiyFp rounded_input(input.f() >> precision_digits_count, |
371 | input.e() + precision_digits_count); |
372 | if (precision_bits >= half_way + error) { |
373 | rounded_input.set_f(rounded_input.f() + 1); |
374 | } |
375 | // If the last_bits are too close to the half-way case than we are too |
376 | // inaccurate and round down. In this case we return false so that we can |
377 | // fall back to a more precise algorithm. |
378 | |
379 | *result = Double(rounded_input).value(); |
380 | if (half_way - error < precision_bits && precision_bits < half_way + error) { |
381 | // Too imprecise. The caller will have to fall back to a slower version. |
382 | // However the returned number is guaranteed to be either the correct |
383 | // double, or the next-lower double. |
384 | return false; |
385 | } else { |
386 | return true; |
387 | } |
388 | } |
389 | |
390 | |
391 | // Returns |
392 | // - -1 if buffer*10^exponent < diy_fp. |
393 | // - 0 if buffer*10^exponent == diy_fp. |
394 | // - +1 if buffer*10^exponent > diy_fp. |
395 | // Preconditions: |
396 | // buffer.length() + exponent <= kMaxDecimalPower + 1 |
397 | // buffer.length() + exponent > kMinDecimalPower |
398 | // buffer.length() <= kMaxDecimalSignificantDigits |
399 | static int CompareBufferWithDiyFp(Vector<const char> buffer, |
400 | int exponent, |
401 | DiyFp diy_fp) { |
402 | ASSERT(buffer.length() + exponent <= kMaxDecimalPower + 1); |
403 | ASSERT(buffer.length() + exponent > kMinDecimalPower); |
404 | ASSERT(buffer.length() <= kMaxSignificantDecimalDigits); |
405 | // Make sure that the Bignum will be able to hold all our numbers. |
406 | // Our Bignum implementation has a separate field for exponents. Shifts will |
407 | // consume at most one bigit (< 64 bits). |
408 | // ln(10) == 3.3219... |
409 | ASSERT(((kMaxDecimalPower + 1) * 333 / 100) < Bignum::kMaxSignificantBits); |
410 | Bignum buffer_bignum; |
411 | Bignum diy_fp_bignum; |
412 | buffer_bignum.AssignDecimalString(value: buffer); |
413 | diy_fp_bignum.AssignUInt64(value: diy_fp.f()); |
414 | if (exponent >= 0) { |
415 | buffer_bignum.MultiplyByPowerOfTen(exponent); |
416 | } else { |
417 | diy_fp_bignum.MultiplyByPowerOfTen(exponent: -exponent); |
418 | } |
419 | if (diy_fp.e() > 0) { |
420 | diy_fp_bignum.ShiftLeft(shift_amount: diy_fp.e()); |
421 | } else { |
422 | buffer_bignum.ShiftLeft(shift_amount: -diy_fp.e()); |
423 | } |
424 | return Bignum::Compare(a: buffer_bignum, b: diy_fp_bignum); |
425 | } |
426 | |
427 | |
428 | // Returns true if the guess is the correct double. |
429 | // Returns false, when guess is either correct or the next-lower double. |
430 | static bool ComputeGuess(Vector<const char> trimmed, int exponent, |
431 | double* guess) { |
432 | if (trimmed.length() == 0) { |
433 | *guess = 0.0; |
434 | return true; |
435 | } |
436 | if (exponent + trimmed.length() - 1 >= kMaxDecimalPower) { |
437 | *guess = Double::Infinity(); |
438 | return true; |
439 | } |
440 | if (exponent + trimmed.length() <= kMinDecimalPower) { |
441 | *guess = 0.0; |
442 | return true; |
443 | } |
444 | |
445 | if (DoubleStrtod(trimmed, exponent, result: guess) || |
446 | DiyFpStrtod(buffer: trimmed, exponent, result: guess)) { |
447 | return true; |
448 | } |
449 | if (*guess == Double::Infinity()) { |
450 | return true; |
451 | } |
452 | return false; |
453 | } |
454 | |
455 | double Strtod(Vector<const char> buffer, int exponent) { |
456 | char copy_buffer[kMaxSignificantDecimalDigits]; |
457 | Vector<const char> trimmed; |
458 | int updated_exponent; |
459 | TrimAndCut(buffer, exponent, buffer_copy_space: copy_buffer, space_size: kMaxSignificantDecimalDigits, |
460 | trimmed: &trimmed, updated_exponent: &updated_exponent); |
461 | exponent = updated_exponent; |
462 | |
463 | double guess; |
464 | bool is_correct = ComputeGuess(trimmed, exponent, guess: &guess); |
465 | if (is_correct) return guess; |
466 | |
467 | DiyFp upper_boundary = Double(guess).UpperBoundary(); |
468 | int comparison = CompareBufferWithDiyFp(buffer: trimmed, exponent, diy_fp: upper_boundary); |
469 | if (comparison < 0) { |
470 | return guess; |
471 | } else if (comparison > 0) { |
472 | return Double(guess).NextDouble(); |
473 | } else if ((Double(guess).Significand() & 1) == 0) { |
474 | // Round towards even. |
475 | return guess; |
476 | } else { |
477 | return Double(guess).NextDouble(); |
478 | } |
479 | } |
480 | |
481 | static float SanitizedDoubletof(double d) { |
482 | ASSERT(d >= 0.0); |
483 | // ASAN has a sanitize check that disallows casting doubles to floats if |
484 | // they are too big. |
485 | // https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#available-checks |
486 | // The behavior should be covered by IEEE 754, but some projects use this |
487 | // flag, so work around it. |
488 | float max_finite = 3.4028234663852885981170418348451692544e+38; |
489 | // The half-way point between the max-finite and infinity value. |
490 | // Since infinity has an even significand everything equal or greater than |
491 | // this value should become infinity. |
492 | double half_max_finite_infinity = |
493 | 3.40282356779733661637539395458142568448e+38; |
494 | if (d >= max_finite) { |
495 | if (d >= half_max_finite_infinity) { |
496 | return Single::Infinity(); |
497 | } else { |
498 | return max_finite; |
499 | } |
500 | } else { |
501 | return static_cast<float>(d); |
502 | } |
503 | } |
504 | |
505 | float Strtof(Vector<const char> buffer, int exponent) { |
506 | char copy_buffer[kMaxSignificantDecimalDigits]; |
507 | Vector<const char> trimmed; |
508 | int updated_exponent; |
509 | TrimAndCut(buffer, exponent, buffer_copy_space: copy_buffer, space_size: kMaxSignificantDecimalDigits, |
510 | trimmed: &trimmed, updated_exponent: &updated_exponent); |
511 | exponent = updated_exponent; |
512 | |
513 | double double_guess; |
514 | bool is_correct = ComputeGuess(trimmed, exponent, guess: &double_guess); |
515 | |
516 | float float_guess = SanitizedDoubletof(d: double_guess); |
517 | if (float_guess == double_guess) { |
518 | // This shortcut triggers for integer values. |
519 | return float_guess; |
520 | } |
521 | |
522 | // We must catch double-rounding. Say the double has been rounded up, and is |
523 | // now a boundary of a float, and rounds up again. This is why we have to |
524 | // look at previous too. |
525 | // Example (in decimal numbers): |
526 | // input: 12349 |
527 | // high-precision (4 digits): 1235 |
528 | // low-precision (3 digits): |
529 | // when read from input: 123 |
530 | // when rounded from high precision: 124. |
531 | // To do this we simply look at the neigbors of the correct result and see |
532 | // if they would round to the same float. If the guess is not correct we have |
533 | // to look at four values (since two different doubles could be the correct |
534 | // double). |
535 | |
536 | double double_next = Double(double_guess).NextDouble(); |
537 | double double_previous = Double(double_guess).PreviousDouble(); |
538 | |
539 | float f1 = SanitizedDoubletof(d: double_previous); |
540 | float f2 = float_guess; |
541 | float f3 = SanitizedDoubletof(d: double_next); |
542 | float f4; |
543 | if (is_correct) { |
544 | f4 = f3; |
545 | } else { |
546 | double double_next2 = Double(double_next).NextDouble(); |
547 | f4 = SanitizedDoubletof(d: double_next2); |
548 | } |
549 | (void) f2; // Mark variable as used. |
550 | ASSERT(f1 <= f2 && f2 <= f3 && f3 <= f4); |
551 | |
552 | // If the guess doesn't lie near a single-precision boundary we can simply |
553 | // return its float-value. |
554 | if (f1 == f4) { |
555 | return float_guess; |
556 | } |
557 | |
558 | ASSERT((f1 != f2 && f2 == f3 && f3 == f4) || |
559 | (f1 == f2 && f2 != f3 && f3 == f4) || |
560 | (f1 == f2 && f2 == f3 && f3 != f4)); |
561 | |
562 | // guess and next are the two possible candidates (in the same way that |
563 | // double_guess was the lower candidate for a double-precision guess). |
564 | float guess = f1; |
565 | float next = f4; |
566 | DiyFp upper_boundary; |
567 | if (guess == 0.0f) { |
568 | float min_float = 1e-45f; |
569 | upper_boundary = Double(static_cast<double>(min_float) / 2).AsDiyFp(); |
570 | } else { |
571 | upper_boundary = Single(guess).UpperBoundary(); |
572 | } |
573 | int comparison = CompareBufferWithDiyFp(buffer: trimmed, exponent, diy_fp: upper_boundary); |
574 | if (comparison < 0) { |
575 | return guess; |
576 | } else if (comparison > 0) { |
577 | return next; |
578 | } else if ((Single(guess).Significand() & 1) == 0) { |
579 | // Round towards even. |
580 | return guess; |
581 | } else { |
582 | return next; |
583 | } |
584 | } |
585 | |
586 | } // namespace double_conversion |
587 | |