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