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 <limits.h>
29#include <math.h>
30
31#include "double-conversion.h"
32
33#include "bignum-dtoa.h"
34#include "fast-dtoa.h"
35#include "fixed-dtoa.h"
36#include "ieee.h"
37#include "strtod.h"
38#include "utils.h"
39
40namespace double_conversion {
41
42const DoubleToStringConverter& DoubleToStringConverter::EcmaScriptConverter() {
43 int flags = UNIQUE_ZERO | EMIT_POSITIVE_EXPONENT_SIGN;
44 static DoubleToStringConverter converter(flags,
45 "Infinity",
46 "NaN",
47 'e',
48 -6, 21,
49 6, 0);
50 return converter;
51}
52
53
54bool DoubleToStringConverter::HandleSpecialValues(
55 double value,
56 StringBuilder* result_builder) const {
57 Double double_inspect(value);
58 if (double_inspect.IsInfinite()) {
59 if (infinity_symbol_ == NULL) return false;
60 if (value < 0) {
61 result_builder->AddCharacter('-');
62 }
63 result_builder->AddString(infinity_symbol_);
64 return true;
65 }
66 if (double_inspect.IsNan()) {
67 if (nan_symbol_ == NULL) return false;
68 result_builder->AddString(nan_symbol_);
69 return true;
70 }
71 return false;
72}
73
74
75void DoubleToStringConverter::CreateExponentialRepresentation(
76 const char* decimal_digits,
77 int length,
78 int exponent,
79 StringBuilder* result_builder) const {
80 ASSERT(length != 0);
81 result_builder->AddCharacter(decimal_digits[0]);
82 if (length != 1) {
83 result_builder->AddCharacter('.');
84 result_builder->AddSubstring(&decimal_digits[1], length-1);
85 }
86 result_builder->AddCharacter(exponent_character_);
87 if (exponent < 0) {
88 result_builder->AddCharacter('-');
89 exponent = -exponent;
90 } else {
91 if ((flags_ & EMIT_POSITIVE_EXPONENT_SIGN) != 0) {
92 result_builder->AddCharacter('+');
93 }
94 }
95 if (exponent == 0) {
96 result_builder->AddCharacter('0');
97 return;
98 }
99 ASSERT(exponent < 1e4);
100 const int kMaxExponentLength = 5;
101 char buffer[kMaxExponentLength + 1];
102 buffer[kMaxExponentLength] = '\0';
103 int first_char_pos = kMaxExponentLength;
104 while (exponent > 0) {
105 buffer[--first_char_pos] = '0' + (exponent % 10);
106 exponent /= 10;
107 }
108 result_builder->AddSubstring(&buffer[first_char_pos],
109 kMaxExponentLength - first_char_pos);
110}
111
112
113void DoubleToStringConverter::CreateDecimalRepresentation(
114 const char* decimal_digits,
115 int length,
116 int decimal_point,
117 int digits_after_point,
118 StringBuilder* result_builder) const {
119 // Create a representation that is padded with zeros if needed.
120 if (decimal_point <= 0) {
121 // "0.00000decimal_rep".
122 result_builder->AddCharacter('0');
123 if (digits_after_point > 0) {
124 result_builder->AddCharacter('.');
125 result_builder->AddPadding('0', -decimal_point);
126 ASSERT(length <= digits_after_point - (-decimal_point));
127 result_builder->AddSubstring(decimal_digits, length);
128 int remaining_digits = digits_after_point - (-decimal_point) - length;
129 result_builder->AddPadding('0', remaining_digits);
130 }
131 } else if (decimal_point >= length) {
132 // "decimal_rep0000.00000" or "decimal_rep.0000"
133 result_builder->AddSubstring(decimal_digits, length);
134 result_builder->AddPadding('0', decimal_point - length);
135 if (digits_after_point > 0) {
136 result_builder->AddCharacter('.');
137 result_builder->AddPadding('0', digits_after_point);
138 }
139 } else {
140 // "decima.l_rep000"
141 ASSERT(digits_after_point > 0);
142 result_builder->AddSubstring(decimal_digits, decimal_point);
143 result_builder->AddCharacter('.');
144 ASSERT(length - decimal_point <= digits_after_point);
145 result_builder->AddSubstring(&decimal_digits[decimal_point],
146 length - decimal_point);
147 int remaining_digits = digits_after_point - (length - decimal_point);
148 result_builder->AddPadding('0', remaining_digits);
149 }
150 if (digits_after_point == 0) {
151 if ((flags_ & EMIT_TRAILING_DECIMAL_POINT) != 0) {
152 result_builder->AddCharacter('.');
153 }
154 if ((flags_ & EMIT_TRAILING_ZERO_AFTER_POINT) != 0) {
155 result_builder->AddCharacter('0');
156 }
157 }
158}
159
160
161bool DoubleToStringConverter::ToShortestIeeeNumber(
162 double value,
163 StringBuilder* result_builder,
164 DoubleToStringConverter::DtoaMode mode) const {
165 ASSERT(mode == SHORTEST || mode == SHORTEST_SINGLE);
166 if (Double(value).IsSpecial()) {
167 return HandleSpecialValues(value, result_builder);
168 }
169
170 int decimal_point;
171 bool sign;
172 const int kDecimalRepCapacity = kBase10MaximalLength + 1;
173 char decimal_rep[kDecimalRepCapacity];
174 int decimal_rep_length;
175
176 DoubleToAscii(value, mode, 0, decimal_rep, kDecimalRepCapacity,
177 &sign, &decimal_rep_length, &decimal_point);
178
179 bool unique_zero = (flags_ & UNIQUE_ZERO) != 0;
180 if (sign && (value != 0.0 || !unique_zero)) {
181 result_builder->AddCharacter('-');
182 }
183
184 int exponent = decimal_point - 1;
185 if ((decimal_in_shortest_low_ <= exponent) &&
186 (exponent < decimal_in_shortest_high_)) {
187 CreateDecimalRepresentation(decimal_rep, decimal_rep_length,
188 decimal_point,
189 Max(0, decimal_rep_length - decimal_point),
190 result_builder);
191 } else {
192 CreateExponentialRepresentation(decimal_rep, decimal_rep_length, exponent,
193 result_builder);
194 }
195 return true;
196}
197
198
199bool DoubleToStringConverter::ToFixed(double value,
200 int requested_digits,
201 StringBuilder* result_builder) const {
202 ASSERT(kMaxFixedDigitsBeforePoint == 60);
203 const double kFirstNonFixed = 1e60;
204
205 if (Double(value).IsSpecial()) {
206 return HandleSpecialValues(value, result_builder);
207 }
208
209 if (requested_digits > kMaxFixedDigitsAfterPoint) return false;
210 if (value >= kFirstNonFixed || value <= -kFirstNonFixed) return false;
211
212 // Find a sufficiently precise decimal representation of n.
213 int decimal_point;
214 bool sign;
215 // Add space for the '\0' byte.
216 const int kDecimalRepCapacity =
217 kMaxFixedDigitsBeforePoint + kMaxFixedDigitsAfterPoint + 1;
218 char decimal_rep[kDecimalRepCapacity];
219 int decimal_rep_length;
220 DoubleToAscii(value, FIXED, requested_digits,
221 decimal_rep, kDecimalRepCapacity,
222 &sign, &decimal_rep_length, &decimal_point);
223
224 bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
225 if (sign && (value != 0.0 || !unique_zero)) {
226 result_builder->AddCharacter('-');
227 }
228
229 CreateDecimalRepresentation(decimal_rep, decimal_rep_length, decimal_point,
230 requested_digits, result_builder);
231 return true;
232}
233
234
235bool DoubleToStringConverter::ToExponential(
236 double value,
237 int requested_digits,
238 StringBuilder* result_builder) const {
239 if (Double(value).IsSpecial()) {
240 return HandleSpecialValues(value, result_builder);
241 }
242
243 if (requested_digits < -1) return false;
244 if (requested_digits > kMaxExponentialDigits) return false;
245
246 int decimal_point;
247 bool sign;
248 // Add space for digit before the decimal point and the '\0' character.
249 const int kDecimalRepCapacity = kMaxExponentialDigits + 2;
250 ASSERT(kDecimalRepCapacity > kBase10MaximalLength);
251 char decimal_rep[kDecimalRepCapacity];
252 int decimal_rep_length;
253
254 if (requested_digits == -1) {
255 DoubleToAscii(value, SHORTEST, 0,
256 decimal_rep, kDecimalRepCapacity,
257 &sign, &decimal_rep_length, &decimal_point);
258 } else {
259 DoubleToAscii(value, PRECISION, requested_digits + 1,
260 decimal_rep, kDecimalRepCapacity,
261 &sign, &decimal_rep_length, &decimal_point);
262 ASSERT(decimal_rep_length <= requested_digits + 1);
263
264 for (int i = decimal_rep_length; i < requested_digits + 1; ++i) {
265 decimal_rep[i] = '0';
266 }
267 decimal_rep_length = requested_digits + 1;
268 }
269
270 bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
271 if (sign && (value != 0.0 || !unique_zero)) {
272 result_builder->AddCharacter('-');
273 }
274
275 int exponent = decimal_point - 1;
276 CreateExponentialRepresentation(decimal_rep,
277 decimal_rep_length,
278 exponent,
279 result_builder);
280 return true;
281}
282
283
284bool DoubleToStringConverter::ToPrecision(double value,
285 int precision,
286 StringBuilder* result_builder) const {
287 if (Double(value).IsSpecial()) {
288 return HandleSpecialValues(value, result_builder);
289 }
290
291 if (precision < kMinPrecisionDigits || precision > kMaxPrecisionDigits) {
292 return false;
293 }
294
295 // Find a sufficiently precise decimal representation of n.
296 int decimal_point;
297 bool sign;
298 // Add one for the terminating null character.
299 const int kDecimalRepCapacity = kMaxPrecisionDigits + 1;
300 char decimal_rep[kDecimalRepCapacity];
301 int decimal_rep_length;
302
303 DoubleToAscii(value, PRECISION, precision,
304 decimal_rep, kDecimalRepCapacity,
305 &sign, &decimal_rep_length, &decimal_point);
306 ASSERT(decimal_rep_length <= precision);
307
308 bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
309 if (sign && (value != 0.0 || !unique_zero)) {
310 result_builder->AddCharacter('-');
311 }
312
313 // The exponent if we print the number as x.xxeyyy. That is with the
314 // decimal point after the first digit.
315 int exponent = decimal_point - 1;
316
317 int extra_zero = ((flags_ & EMIT_TRAILING_ZERO_AFTER_POINT) != 0) ? 1 : 0;
318 if ((-decimal_point + 1 > max_leading_padding_zeroes_in_precision_mode_) ||
319 (decimal_point - precision + extra_zero >
320 max_trailing_padding_zeroes_in_precision_mode_)) {
321 // Fill buffer to contain 'precision' digits.
322 // Usually the buffer is already at the correct length, but 'DoubleToAscii'
323 // is allowed to return less characters.
324 for (int i = decimal_rep_length; i < precision; ++i) {
325 decimal_rep[i] = '0';
326 }
327
328 CreateExponentialRepresentation(decimal_rep,
329 precision,
330 exponent,
331 result_builder);
332 } else {
333 CreateDecimalRepresentation(decimal_rep, decimal_rep_length, decimal_point,
334 Max(0, precision - decimal_point),
335 result_builder);
336 }
337 return true;
338}
339
340
341static BignumDtoaMode DtoaToBignumDtoaMode(
342 DoubleToStringConverter::DtoaMode dtoa_mode) {
343 switch (dtoa_mode) {
344 case DoubleToStringConverter::SHORTEST: return BIGNUM_DTOA_SHORTEST;
345 case DoubleToStringConverter::SHORTEST_SINGLE:
346 return BIGNUM_DTOA_SHORTEST_SINGLE;
347 case DoubleToStringConverter::FIXED: return BIGNUM_DTOA_FIXED;
348 case DoubleToStringConverter::PRECISION: return BIGNUM_DTOA_PRECISION;
349 default:
350 UNREACHABLE();
351 return BIGNUM_DTOA_SHORTEST;
352 }
353}
354
355
356void DoubleToStringConverter::DoubleToAscii(double v,
357 DtoaMode mode,
358 int requested_digits,
359 char* buffer,
360 int buffer_length,
361 bool* sign,
362 int* length,
363 int* point) {
364 Vector<char> vector(buffer, buffer_length);
365 ASSERT(!Double(v).IsSpecial());
366 ASSERT(mode == SHORTEST || mode == SHORTEST_SINGLE || requested_digits >= 0);
367
368 if (Double(v).Sign() < 0) {
369 *sign = true;
370 v = -v;
371 } else {
372 *sign = false;
373 }
374
375 if (mode == PRECISION && requested_digits == 0) {
376 vector[0] = '\0';
377 *length = 0;
378 return;
379 }
380
381 if (v == 0) {
382 vector[0] = '0';
383 vector[1] = '\0';
384 *length = 1;
385 *point = 1;
386 return;
387 }
388
389 bool fast_worked;
390 switch (mode) {
391 case SHORTEST:
392 fast_worked = FastDtoa(v, FAST_DTOA_SHORTEST, 0, vector, length, point);
393 break;
394 case SHORTEST_SINGLE:
395 fast_worked = FastDtoa(v, FAST_DTOA_SHORTEST_SINGLE, 0,
396 vector, length, point);
397 break;
398 case FIXED:
399 fast_worked = FastFixedDtoa(v, requested_digits, vector, length, point);
400 break;
401 case PRECISION:
402 fast_worked = FastDtoa(v, FAST_DTOA_PRECISION, requested_digits,
403 vector, length, point);
404 break;
405 default:
406 fast_worked = false;
407 UNREACHABLE();
408 }
409 if (fast_worked) return;
410
411 // If the fast dtoa didn't succeed use the slower bignum version.
412 BignumDtoaMode bignum_mode = DtoaToBignumDtoaMode(mode);
413 BignumDtoa(v, bignum_mode, requested_digits, vector, length, point);
414 vector[*length] = '\0';
415}
416
417
418// Consumes the given substring from the iterator.
419// Returns false, if the substring does not match.
420static bool ConsumeSubString(const char** current,
421 const char* end,
422 const char* substring) {
423 ASSERT(**current == *substring);
424 for (substring++; *substring != '\0'; substring++) {
425 ++*current;
426 if (*current == end || **current != *substring) return false;
427 }
428 ++*current;
429 return true;
430}
431
432
433// Maximum number of significant digits in decimal representation.
434// The longest possible double in decimal representation is
435// (2^53 - 1) * 2 ^ -1074 that is (2 ^ 53 - 1) * 5 ^ 1074 / 10 ^ 1074
436// (768 digits). If we parse a number whose first digits are equal to a
437// mean of 2 adjacent doubles (that could have up to 769 digits) the result
438// must be rounded to the bigger one unless the tail consists of zeros, so
439// we don't need to preserve all the digits.
440const int kMaxSignificantDigits = 772;
441
442
443// Returns true if a nonspace found and false if the end has reached.
444static inline bool AdvanceToNonspace(const char** current, const char* end) {
445 while (*current != end) {
446 if (**current != ' ') return true;
447 ++*current;
448 }
449 return false;
450}
451
452
453static bool isDigit(int x, int radix) {
454 return (x >= '0' && x <= '9' && x < '0' + radix)
455 || (radix > 10 && x >= 'a' && x < 'a' + radix - 10)
456 || (radix > 10 && x >= 'A' && x < 'A' + radix - 10);
457}
458
459
460static double SignedZero(bool sign) {
461 return sign ? -0.0 : 0.0;
462}
463
464
465// Returns true if 'c' is a decimal digit that is valid for the given radix.
466//
467// The function is small and could be inlined, but VS2012 emitted a warning
468// because it constant-propagated the radix and concluded that the last
469// condition was always true. By moving it into a separate function the
470// compiler wouldn't warn anymore.
471static bool IsDecimalDigitForRadix(int c, int radix) {
472 return '0' <= c && c <= '9' && (c - '0') < radix;
473}
474
475// Returns true if 'c' is a character digit that is valid for the given radix.
476// The 'a_character' should be 'a' or 'A'.
477//
478// The function is small and could be inlined, but VS2012 emitted a warning
479// because it constant-propagated the radix and concluded that the first
480// condition was always false. By moving it into a separate function the
481// compiler wouldn't warn anymore.
482static bool IsCharacterDigitForRadix(int c, int radix, char a_character) {
483 return radix > 10 && c >= a_character && c < a_character + radix - 10;
484}
485
486
487// Parsing integers with radix 2, 4, 8, 16, 32. Assumes current != end.
488template <int radix_log_2>
489static double RadixStringToIeee(const char* current,
490 const char* end,
491 bool sign,
492 bool allow_trailing_junk,
493 double junk_string_value,
494 bool read_as_double,
495 const char** trailing_pointer) {
496 ASSERT(current != end);
497
498 const int kDoubleSize = Double::kSignificandSize;
499 const int kSingleSize = Single::kSignificandSize;
500 const int kSignificandSize = read_as_double? kDoubleSize: kSingleSize;
501
502 // Skip leading 0s.
503 while (*current == '0') {
504 ++current;
505 if (current == end) {
506 *trailing_pointer = end;
507 return SignedZero(sign);
508 }
509 }
510
511 int64_t number = 0;
512 int exponent = 0;
513 const int radix = (1 << radix_log_2);
514
515 do {
516 int digit;
517 if (IsDecimalDigitForRadix(*current, radix)) {
518 digit = static_cast<char>(*current) - '0';
519 } else if (IsCharacterDigitForRadix(*current, radix, 'a')) {
520 digit = static_cast<char>(*current) - 'a' + 10;
521 } else if (IsCharacterDigitForRadix(*current, radix, 'A')) {
522 digit = static_cast<char>(*current) - 'A' + 10;
523 } else {
524 if (allow_trailing_junk || !AdvanceToNonspace(&current, end)) {
525 break;
526 } else {
527 return junk_string_value;
528 }
529 }
530
531 number = number * radix + digit;
532 int overflow = static_cast<int>(number >> kSignificandSize);
533 if (overflow != 0) {
534 // Overflow occurred. Need to determine which direction to round the
535 // result.
536 int overflow_bits_count = 1;
537 while (overflow > 1) {
538 overflow_bits_count++;
539 overflow >>= 1;
540 }
541
542 int dropped_bits_mask = ((1 << overflow_bits_count) - 1);
543 int dropped_bits = static_cast<int>(number) & dropped_bits_mask;
544 number >>= overflow_bits_count;
545 exponent = overflow_bits_count;
546
547 bool zero_tail = true;
548 for (;;) {
549 ++current;
550 if (current == end || !isDigit(*current, radix)) break;
551 zero_tail = zero_tail && *current == '0';
552 exponent += radix_log_2;
553 }
554
555 if (!allow_trailing_junk && AdvanceToNonspace(&current, end)) {
556 return junk_string_value;
557 }
558
559 int middle_value = (1 << (overflow_bits_count - 1));
560 if (dropped_bits > middle_value) {
561 number++; // Rounding up.
562 } else if (dropped_bits == middle_value) {
563 // Rounding to even to consistency with decimals: half-way case rounds
564 // up if significant part is odd and down otherwise.
565 if ((number & 1) != 0 || !zero_tail) {
566 number++; // Rounding up.
567 }
568 }
569
570 // Rounding up may cause overflow.
571 if ((number & ((int64_t)1 << kSignificandSize)) != 0) {
572 exponent++;
573 number >>= 1;
574 }
575 break;
576 }
577 ++current;
578 } while (current != end);
579
580 ASSERT(number < ((int64_t)1 << kSignificandSize));
581 ASSERT(static_cast<int64_t>(static_cast<double>(number)) == number);
582
583 *trailing_pointer = current;
584
585 if (exponent == 0) {
586 if (sign) {
587 if (number == 0) return -0.0;
588 number = -number;
589 }
590 return static_cast<double>(number);
591 }
592
593 ASSERT(number != 0);
594 return Double(DiyFp(number, exponent)).value();
595}
596
597
598double StringToDoubleConverter::StringToIeee(
599 const char* input,
600 int length,
601 int* processed_characters_count,
602 bool read_as_double) const {
603 const char* current = input;
604 const char* end = input + length;
605
606 *processed_characters_count = 0;
607
608 const bool allow_trailing_junk = (flags_ & ALLOW_TRAILING_JUNK) != 0;
609 const bool allow_leading_spaces = (flags_ & ALLOW_LEADING_SPACES) != 0;
610 const bool allow_trailing_spaces = (flags_ & ALLOW_TRAILING_SPACES) != 0;
611 const bool allow_spaces_after_sign = (flags_ & ALLOW_SPACES_AFTER_SIGN) != 0;
612
613 // To make sure that iterator dereferencing is valid the following
614 // convention is used:
615 // 1. Each '++current' statement is followed by check for equality to 'end'.
616 // 2. If AdvanceToNonspace returned false then current == end.
617 // 3. If 'current' becomes equal to 'end' the function returns or goes to
618 // 'parsing_done'.
619 // 4. 'current' is not dereferenced after the 'parsing_done' label.
620 // 5. Code before 'parsing_done' may rely on 'current != end'.
621 if (current == end) return empty_string_value_;
622
623 if (allow_leading_spaces || allow_trailing_spaces) {
624 if (!AdvanceToNonspace(&current, end)) {
625 *processed_characters_count = static_cast<int>(current - input);
626 return empty_string_value_;
627 }
628 if (!allow_leading_spaces && (input != current)) {
629 // No leading spaces allowed, but AdvanceToNonspace moved forward.
630 return junk_string_value_;
631 }
632 }
633
634 // The longest form of simplified number is: "-<significant digits>.1eXXX\0".
635 const int kBufferSize = kMaxSignificantDigits + 10;
636 char buffer[kBufferSize]; // NOLINT: size is known at compile time.
637 int buffer_pos = 0;
638
639 // Exponent will be adjusted if insignificant digits of the integer part
640 // or insignificant leading zeros of the fractional part are dropped.
641 int exponent = 0;
642 int significant_digits = 0;
643 int insignificant_digits = 0;
644 bool nonzero_digit_dropped = false;
645
646 bool sign = false;
647
648 if (*current == '+' || *current == '-') {
649 sign = (*current == '-');
650 ++current;
651 const char* next_non_space = current;
652 // Skip following spaces (if allowed).
653 if (!AdvanceToNonspace(&next_non_space, end)) return junk_string_value_;
654 if (!allow_spaces_after_sign && (current != next_non_space)) {
655 return junk_string_value_;
656 }
657 current = next_non_space;
658 }
659
660 if (infinity_symbol_ != NULL) {
661 if (*current == infinity_symbol_[0]) {
662 if (!ConsumeSubString(&current, end, infinity_symbol_)) {
663 return junk_string_value_;
664 }
665
666 if (!(allow_trailing_spaces || allow_trailing_junk) && (current != end)) {
667 return junk_string_value_;
668 }
669 if (!allow_trailing_junk && AdvanceToNonspace(&current, end)) {
670 return junk_string_value_;
671 }
672
673 ASSERT(buffer_pos == 0);
674 *processed_characters_count = static_cast<int>(current - input);
675 return sign ? -Double::Infinity() : Double::Infinity();
676 }
677 }
678
679 if (nan_symbol_ != NULL) {
680 if (*current == nan_symbol_[0]) {
681 if (!ConsumeSubString(&current, end, nan_symbol_)) {
682 return junk_string_value_;
683 }
684
685 if (!(allow_trailing_spaces || allow_trailing_junk) && (current != end)) {
686 return junk_string_value_;
687 }
688 if (!allow_trailing_junk && AdvanceToNonspace(&current, end)) {
689 return junk_string_value_;
690 }
691
692 ASSERT(buffer_pos == 0);
693 *processed_characters_count = static_cast<int>(current - input);
694 return sign ? -Double::NaN() : Double::NaN();
695 }
696 }
697
698 bool leading_zero = false;
699 if (*current == '0') {
700 ++current;
701 if (current == end) {
702 *processed_characters_count = static_cast<int>(current - input);
703 return SignedZero(sign);
704 }
705
706 leading_zero = true;
707
708 // It could be hexadecimal value.
709 if ((flags_ & ALLOW_HEX) && (*current == 'x' || *current == 'X')) {
710 ++current;
711 if (current == end || !isDigit(*current, 16)) {
712 return junk_string_value_; // "0x".
713 }
714
715 const char* tail_pointer = NULL;
716 double result = RadixStringToIeee<4>(current,
717 end,
718 sign,
719 allow_trailing_junk,
720 junk_string_value_,
721 read_as_double,
722 &tail_pointer);
723 if (tail_pointer != NULL) {
724 if (allow_trailing_spaces) AdvanceToNonspace(&tail_pointer, end);
725 *processed_characters_count = static_cast<int>(tail_pointer - input);
726 }
727 return result;
728 }
729
730 // Ignore leading zeros in the integer part.
731 while (*current == '0') {
732 ++current;
733 if (current == end) {
734 *processed_characters_count = static_cast<int>(current - input);
735 return SignedZero(sign);
736 }
737 }
738 }
739
740 bool octal = leading_zero && (flags_ & ALLOW_OCTALS) != 0;
741
742 // Copy significant digits of the integer part (if any) to the buffer.
743 while (*current >= '0' && *current <= '9') {
744 if (significant_digits < kMaxSignificantDigits) {
745 ASSERT(buffer_pos < kBufferSize);
746 buffer[buffer_pos++] = static_cast<char>(*current);
747 significant_digits++;
748 // Will later check if it's an octal in the buffer.
749 } else {
750 insignificant_digits++; // Move the digit into the exponential part.
751 nonzero_digit_dropped = nonzero_digit_dropped || *current != '0';
752 }
753 octal = octal && *current < '8';
754 ++current;
755 if (current == end) goto parsing_done;
756 }
757
758 if (significant_digits == 0) {
759 octal = false;
760 }
761
762 if (*current == '.') {
763 if (octal && !allow_trailing_junk) return junk_string_value_;
764 if (octal) goto parsing_done;
765
766 ++current;
767 if (current == end) {
768 if (significant_digits == 0 && !leading_zero) {
769 return junk_string_value_;
770 } else {
771 goto parsing_done;
772 }
773 }
774
775 if (significant_digits == 0) {
776 // octal = false;
777 // Integer part consists of 0 or is absent. Significant digits start after
778 // leading zeros (if any).
779 while (*current == '0') {
780 ++current;
781 if (current == end) {
782 *processed_characters_count = static_cast<int>(current - input);
783 return SignedZero(sign);
784 }
785 exponent--; // Move this 0 into the exponent.
786 }
787 }
788
789 // There is a fractional part.
790 // We don't emit a '.', but adjust the exponent instead.
791 while (*current >= '0' && *current <= '9') {
792 if (significant_digits < kMaxSignificantDigits) {
793 ASSERT(buffer_pos < kBufferSize);
794 buffer[buffer_pos++] = static_cast<char>(*current);
795 significant_digits++;
796 exponent--;
797 } else {
798 // Ignore insignificant digits in the fractional part.
799 nonzero_digit_dropped = nonzero_digit_dropped || *current != '0';
800 }
801 ++current;
802 if (current == end) goto parsing_done;
803 }
804 }
805
806 if (!leading_zero && exponent == 0 && significant_digits == 0) {
807 // If leading_zeros is true then the string contains zeros.
808 // If exponent < 0 then string was [+-]\.0*...
809 // If significant_digits != 0 the string is not equal to 0.
810 // Otherwise there are no digits in the string.
811 return junk_string_value_;
812 }
813
814 // Parse exponential part.
815 if (*current == 'e' || *current == 'E') {
816 if (octal && !allow_trailing_junk) return junk_string_value_;
817 if (octal) goto parsing_done;
818 ++current;
819 if (current == end) {
820 if (allow_trailing_junk) {
821 goto parsing_done;
822 } else {
823 return junk_string_value_;
824 }
825 }
826 char currentSign = '+';
827 if (*current == '+' || *current == '-') {
828 currentSign = static_cast<char>(*current);
829 ++current;
830 if (current == end) {
831 if (allow_trailing_junk) {
832 goto parsing_done;
833 } else {
834 return junk_string_value_;
835 }
836 }
837 }
838
839 if (current == end || *current < '0' || *current > '9') {
840 if (allow_trailing_junk) {
841 goto parsing_done;
842 } else {
843 return junk_string_value_;
844 }
845 }
846
847 const int max_exponent = INT_MAX / 2;
848 ASSERT(-max_exponent / 2 <= exponent && exponent <= max_exponent / 2);
849 int num = 0;
850 do {
851 // Check overflow.
852 int digit = *current - '0';
853 if (num >= max_exponent / 10
854 && !(num == max_exponent / 10 && digit <= max_exponent % 10)) {
855 num = max_exponent;
856 } else {
857 num = num * 10 + digit;
858 }
859 ++current;
860 } while (current != end && *current >= '0' && *current <= '9');
861
862 exponent += (currentSign == '-' ? -num : num);
863 }
864
865 if (!(allow_trailing_spaces || allow_trailing_junk) && (current != end)) {
866 return junk_string_value_;
867 }
868 if (!allow_trailing_junk && AdvanceToNonspace(&current, end)) {
869 return junk_string_value_;
870 }
871 if (allow_trailing_spaces) {
872 AdvanceToNonspace(&current, end);
873 }
874
875 parsing_done:
876 exponent += insignificant_digits;
877
878 if (octal) {
879 double result;
880 const char* tail_pointer = NULL;
881 result = RadixStringToIeee<3>(buffer,
882 buffer + buffer_pos,
883 sign,
884 allow_trailing_junk,
885 junk_string_value_,
886 read_as_double,
887 &tail_pointer);
888 ASSERT(tail_pointer != NULL);
889 *processed_characters_count = static_cast<int>(current - input);
890 return result;
891 }
892
893 if (nonzero_digit_dropped) {
894 buffer[buffer_pos++] = '1';
895 exponent--;
896 }
897
898 ASSERT(buffer_pos < kBufferSize);
899 buffer[buffer_pos] = '\0';
900
901 double converted;
902 if (read_as_double) {
903 converted = Strtod(Vector<const char>(buffer, buffer_pos), exponent);
904 } else {
905 converted = Strtof(Vector<const char>(buffer, buffer_pos), exponent);
906 }
907 *processed_characters_count = static_cast<int>(current - input);
908 return sign? -converted: converted;
909}
910
911} // namespace double_conversion
912