blob: fd0f9ee4d81cce588c5f2625463205d0a117d206 [file] [log] [blame]
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001// Copyright 2011 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002// 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 <stdarg.h>
ager@chromium.orgb26c50a2010-03-26 09:27:16 +000029#include <limits.h>
ulan@chromium.org77ca49a2013-04-22 09:43:56 +000030#include <cmath>
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000031
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000032#include "conversions-inl.h"
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +000033#include "dtoa.h"
mvstanton@chromium.orgdd6d9ee2013-10-11 10:35:37 +000034#include "list-inl.h"
ager@chromium.orgb61a0d12010-10-13 08:35:23 +000035#include "strtod.h"
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +000036#include "utils.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000037
ulan@chromium.org77ca49a2013-04-22 09:43:56 +000038#ifndef _STLP_VENDOR_CSTD
39// STLPort doesn't import fpclassify into the std namespace.
40using std::fpclassify;
41#endif
42
kasperl@chromium.org71affb52009-05-26 05:44:31 +000043namespace v8 {
44namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000045
lrn@chromium.org25156de2010-04-06 13:10:27 +000046
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +000047double StringToDouble(UnicodeCache* unicode_cache,
48 const char* str, int flags, double empty_string_val) {
ager@chromium.orgb26c50a2010-03-26 09:27:16 +000049 const char* end = str + StrLength(str);
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +000050 return InternalStringToDouble(unicode_cache, str, end, flags,
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000051 empty_string_val);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000052}
53
54
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +000055double StringToDouble(UnicodeCache* unicode_cache,
56 Vector<const char> str,
ricow@chromium.org65fae842010-08-25 15:26:24 +000057 int flags,
58 double empty_string_val) {
59 const char* end = str.start() + str.length();
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +000060 return InternalStringToDouble(unicode_cache, str.start(), end, flags,
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000061 empty_string_val);
ricow@chromium.org65fae842010-08-25 15:26:24 +000062}
63
danno@chromium.org40cb8782011-05-25 07:58:50 +000064double StringToDouble(UnicodeCache* unicode_cache,
65 Vector<const uc16> str,
66 int flags,
67 double empty_string_val) {
68 const uc16* end = str.start() + str.length();
69 return InternalStringToDouble(unicode_cache, str.start(), end, flags,
70 empty_string_val);
71}
72
ricow@chromium.org65fae842010-08-25 15:26:24 +000073
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000074const char* DoubleToCString(double v, Vector<char> buffer) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000075 switch (fpclassify(v)) {
ricow@chromium.org83aa5492011-02-07 12:42:56 +000076 case FP_NAN: return "NaN";
77 case FP_INFINITE: return (v < 0.0 ? "-Infinity" : "Infinity");
78 case FP_ZERO: return "0";
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000079 default: {
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +000080 SimpleStringBuilder builder(buffer.start(), buffer.length());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000081 int decimal_point;
82 int sign;
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +000083 const int kV8DtoaBufferCapacity = kBase10MaximalLength + 1;
erik.corry@gmail.com4a6c3272010-11-18 12:04:40 +000084 char decimal_rep[kV8DtoaBufferCapacity];
whesse@chromium.orgcec079d2010-03-22 14:44:04 +000085 int length;
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +000086
erik.corry@gmail.com4a6c3272010-11-18 12:04:40 +000087 DoubleToAscii(v, DTOA_SHORTEST, 0,
88 Vector<char>(decimal_rep, kV8DtoaBufferCapacity),
89 &sign, &length, &decimal_point);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000090
91 if (sign) builder.AddCharacter('-');
92
93 if (length <= decimal_point && decimal_point <= 21) {
94 // ECMA-262 section 9.8.1 step 6.
95 builder.AddString(decimal_rep);
96 builder.AddPadding('0', decimal_point - length);
97
98 } else if (0 < decimal_point && decimal_point <= 21) {
99 // ECMA-262 section 9.8.1 step 7.
100 builder.AddSubstring(decimal_rep, decimal_point);
101 builder.AddCharacter('.');
102 builder.AddString(decimal_rep + decimal_point);
103
104 } else if (decimal_point <= 0 && decimal_point > -6) {
105 // ECMA-262 section 9.8.1 step 8.
106 builder.AddString("0.");
107 builder.AddPadding('0', -decimal_point);
108 builder.AddString(decimal_rep);
109
110 } else {
111 // ECMA-262 section 9.8.1 step 9 and 10 combined.
112 builder.AddCharacter(decimal_rep[0]);
113 if (length != 1) {
114 builder.AddCharacter('.');
115 builder.AddString(decimal_rep + 1);
116 }
117 builder.AddCharacter('e');
118 builder.AddCharacter((decimal_point >= 0) ? '+' : '-');
119 int exponent = decimal_point - 1;
120 if (exponent < 0) exponent = -exponent;
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +0000121 builder.AddDecimalInteger(exponent);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000122 }
ricow@chromium.org83aa5492011-02-07 12:42:56 +0000123 return builder.Finalize();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000124 }
125 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000126}
127
128
129const char* IntToCString(int n, Vector<char> buffer) {
130 bool negative = false;
131 if (n < 0) {
132 // We must not negate the most negative int.
133 if (n == kMinInt) return DoubleToCString(n, buffer);
134 negative = true;
135 n = -n;
136 }
137 // Build the string backwards from the least significant digit.
138 int i = buffer.length();
139 buffer[--i] = '\0';
140 do {
141 buffer[--i] = '0' + (n % 10);
142 n /= 10;
143 } while (n);
144 if (negative) buffer[--i] = '-';
145 return buffer.start() + i;
146}
147
148
149char* DoubleToFixedCString(double value, int f) {
whesse@chromium.orgf0ac72d2010-11-08 12:47:26 +0000150 const int kMaxDigitsBeforePoint = 21;
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000151 const double kFirstNonFixed = 1e21;
152 const int kMaxDigitsAfterPoint = 20;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000153 ASSERT(f >= 0);
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000154 ASSERT(f <= kMaxDigitsAfterPoint);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000155
156 bool negative = false;
157 double abs_value = value;
158 if (value < 0) {
159 abs_value = -value;
160 negative = true;
161 }
162
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000163 // If abs_value has more than kMaxDigitsBeforePoint digits before the point
164 // use the non-fixed conversion routine.
165 if (abs_value >= kFirstNonFixed) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000166 char arr[100];
167 Vector<char> buffer(arr, ARRAY_SIZE(arr));
168 return StrDup(DoubleToCString(value, buffer));
169 }
170
171 // Find a sufficiently precise decimal representation of n.
172 int decimal_point;
173 int sign;
whesse@chromium.orgf0ac72d2010-11-08 12:47:26 +0000174 // Add space for the '\0' byte.
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000175 const int kDecimalRepCapacity =
whesse@chromium.orgf0ac72d2010-11-08 12:47:26 +0000176 kMaxDigitsBeforePoint + kMaxDigitsAfterPoint + 1;
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000177 char decimal_rep[kDecimalRepCapacity];
178 int decimal_rep_length;
erik.corry@gmail.com4a6c3272010-11-18 12:04:40 +0000179 DoubleToAscii(value, DTOA_FIXED, f,
180 Vector<char>(decimal_rep, kDecimalRepCapacity),
181 &sign, &decimal_rep_length, &decimal_point);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000182
183 // Create a representation that is padded with zeros if needed.
184 int zero_prefix_length = 0;
185 int zero_postfix_length = 0;
186
187 if (decimal_point <= 0) {
188 zero_prefix_length = -decimal_point + 1;
189 decimal_point = 1;
190 }
191
192 if (zero_prefix_length + decimal_rep_length < decimal_point + f) {
193 zero_postfix_length = decimal_point + f - decimal_rep_length -
194 zero_prefix_length;
195 }
196
197 unsigned rep_length =
198 zero_prefix_length + decimal_rep_length + zero_postfix_length;
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +0000199 SimpleStringBuilder rep_builder(rep_length + 1);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000200 rep_builder.AddPadding('0', zero_prefix_length);
201 rep_builder.AddString(decimal_rep);
202 rep_builder.AddPadding('0', zero_postfix_length);
203 char* rep = rep_builder.Finalize();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000204
205 // Create the result string by appending a minus and putting in a
206 // decimal point if needed.
207 unsigned result_size = decimal_point + f + 2;
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +0000208 SimpleStringBuilder builder(result_size + 1);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000209 if (negative) builder.AddCharacter('-');
210 builder.AddSubstring(rep, decimal_point);
211 if (f > 0) {
212 builder.AddCharacter('.');
213 builder.AddSubstring(rep + decimal_point, f);
214 }
215 DeleteArray(rep);
216 return builder.Finalize();
217}
218
219
220static char* CreateExponentialRepresentation(char* decimal_rep,
221 int exponent,
222 bool negative,
223 int significant_digits) {
224 bool negative_exponent = false;
225 if (exponent < 0) {
226 negative_exponent = true;
227 exponent = -exponent;
228 }
229
230 // Leave room in the result for appending a minus, for a period, the
231 // letter 'e', a minus or a plus depending on the exponent, and a
232 // three digit exponent.
233 unsigned result_size = significant_digits + 7;
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +0000234 SimpleStringBuilder builder(result_size + 1);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000235
236 if (negative) builder.AddCharacter('-');
237 builder.AddCharacter(decimal_rep[0]);
238 if (significant_digits != 1) {
239 builder.AddCharacter('.');
240 builder.AddString(decimal_rep + 1);
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000241 int rep_length = StrLength(decimal_rep);
242 builder.AddPadding('0', significant_digits - rep_length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000243 }
244
245 builder.AddCharacter('e');
246 builder.AddCharacter(negative_exponent ? '-' : '+');
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +0000247 builder.AddDecimalInteger(exponent);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000248 return builder.Finalize();
249}
250
251
252
253char* DoubleToExponentialCString(double value, int f) {
fschneider@chromium.orgc20610a2010-09-22 09:44:58 +0000254 const int kMaxDigitsAfterPoint = 20;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000255 // f might be -1 to signal that f was undefined in JavaScript.
fschneider@chromium.orgc20610a2010-09-22 09:44:58 +0000256 ASSERT(f >= -1 && f <= kMaxDigitsAfterPoint);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000257
258 bool negative = false;
259 if (value < 0) {
260 value = -value;
261 negative = true;
262 }
263
264 // Find a sufficiently precise decimal representation of n.
265 int decimal_point;
266 int sign;
fschneider@chromium.orgc20610a2010-09-22 09:44:58 +0000267 // f corresponds to the digits after the point. There is always one digit
268 // before the point. The number of requested_digits equals hence f + 1.
269 // And we have to add one character for the null-terminator.
270 const int kV8DtoaBufferCapacity = kMaxDigitsAfterPoint + 1 + 1;
271 // Make sure that the buffer is big enough, even if we fall back to the
272 // shortest representation (which happens when f equals -1).
273 ASSERT(kBase10MaximalLength <= kMaxDigitsAfterPoint + 1);
erik.corry@gmail.com4a6c3272010-11-18 12:04:40 +0000274 char decimal_rep[kV8DtoaBufferCapacity];
fschneider@chromium.orgc20610a2010-09-22 09:44:58 +0000275 int decimal_rep_length;
276
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000277 if (f == -1) {
erik.corry@gmail.com4a6c3272010-11-18 12:04:40 +0000278 DoubleToAscii(value, DTOA_SHORTEST, 0,
279 Vector<char>(decimal_rep, kV8DtoaBufferCapacity),
280 &sign, &decimal_rep_length, &decimal_point);
281 f = decimal_rep_length - 1;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000282 } else {
erik.corry@gmail.com4a6c3272010-11-18 12:04:40 +0000283 DoubleToAscii(value, DTOA_PRECISION, f + 1,
284 Vector<char>(decimal_rep, kV8DtoaBufferCapacity),
285 &sign, &decimal_rep_length, &decimal_point);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000286 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000287 ASSERT(decimal_rep_length > 0);
288 ASSERT(decimal_rep_length <= f + 1);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000289
290 int exponent = decimal_point - 1;
291 char* result =
292 CreateExponentialRepresentation(decimal_rep, exponent, negative, f+1);
293
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000294 return result;
295}
296
297
298char* DoubleToPrecisionCString(double value, int p) {
fschneider@chromium.orgc20610a2010-09-22 09:44:58 +0000299 const int kMinimalDigits = 1;
300 const int kMaximalDigits = 21;
301 ASSERT(p >= kMinimalDigits && p <= kMaximalDigits);
302 USE(kMinimalDigits);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000303
304 bool negative = false;
305 if (value < 0) {
306 value = -value;
307 negative = true;
308 }
309
310 // Find a sufficiently precise decimal representation of n.
311 int decimal_point;
312 int sign;
fschneider@chromium.orgc20610a2010-09-22 09:44:58 +0000313 // Add one for the terminating null character.
314 const int kV8DtoaBufferCapacity = kMaximalDigits + 1;
erik.corry@gmail.com4a6c3272010-11-18 12:04:40 +0000315 char decimal_rep[kV8DtoaBufferCapacity];
fschneider@chromium.orgc20610a2010-09-22 09:44:58 +0000316 int decimal_rep_length;
317
erik.corry@gmail.com4a6c3272010-11-18 12:04:40 +0000318 DoubleToAscii(value, DTOA_PRECISION, p,
319 Vector<char>(decimal_rep, kV8DtoaBufferCapacity),
320 &sign, &decimal_rep_length, &decimal_point);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000321 ASSERT(decimal_rep_length <= p);
322
323 int exponent = decimal_point - 1;
324
325 char* result = NULL;
326
327 if (exponent < -6 || exponent >= p) {
328 result =
329 CreateExponentialRepresentation(decimal_rep, exponent, negative, p);
330 } else {
331 // Use fixed notation.
332 //
333 // Leave room in the result for appending a minus, a period and in
334 // the case where decimal_point is not positive for a zero in
335 // front of the period.
336 unsigned result_size = (decimal_point <= 0)
337 ? -decimal_point + p + 3
338 : p + 2;
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +0000339 SimpleStringBuilder builder(result_size + 1);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000340 if (negative) builder.AddCharacter('-');
341 if (decimal_point <= 0) {
342 builder.AddString("0.");
343 builder.AddPadding('0', -decimal_point);
344 builder.AddString(decimal_rep);
345 builder.AddPadding('0', p - decimal_rep_length);
346 } else {
347 const int m = Min(decimal_rep_length, decimal_point);
348 builder.AddSubstring(decimal_rep, m);
349 builder.AddPadding('0', decimal_point - decimal_rep_length);
350 if (decimal_point < p) {
351 builder.AddCharacter('.');
352 const int extra = negative ? 2 : 1;
353 if (decimal_rep_length > decimal_point) {
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000354 const int len = StrLength(decimal_rep + decimal_point);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000355 const int n = Min(len, p - (builder.position() - extra));
356 builder.AddSubstring(decimal_rep + decimal_point, n);
357 }
358 builder.AddPadding('0', extra + (p - builder.position()));
359 }
360 }
361 result = builder.Finalize();
362 }
363
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000364 return result;
365}
366
367
368char* DoubleToRadixCString(double value, int radix) {
369 ASSERT(radix >= 2 && radix <= 36);
370
371 // Character array used for conversion.
372 static const char chars[] = "0123456789abcdefghijklmnopqrstuvwxyz";
373
374 // Buffer for the integer part of the result. 1024 chars is enough
375 // for max integer value in radix 2. We need room for a sign too.
376 static const int kBufferSize = 1100;
377 char integer_buffer[kBufferSize];
378 integer_buffer[kBufferSize - 1] = '\0';
379
380 // Buffer for the decimal part of the result. We only generate up
381 // to kBufferSize - 1 chars for the decimal part.
382 char decimal_buffer[kBufferSize];
383 decimal_buffer[kBufferSize - 1] = '\0';
384
385 // Make sure the value is positive.
386 bool is_negative = value < 0.0;
387 if (is_negative) value = -value;
388
389 // Get the integer part and the decimal part.
390 double integer_part = floor(value);
391 double decimal_part = value - integer_part;
392
393 // Convert the integer part starting from the back. Always generate
394 // at least one digit.
395 int integer_pos = kBufferSize - 2;
396 do {
397 integer_buffer[integer_pos--] =
ricow@chromium.org55ee8072011-09-08 16:33:10 +0000398 chars[static_cast<int>(fmod(integer_part, radix))];
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000399 integer_part /= radix;
400 } while (integer_part >= 1.0);
401 // Sanity check.
402 ASSERT(integer_pos > 0);
403 // Add sign if needed.
404 if (is_negative) integer_buffer[integer_pos--] = '-';
405
406 // Convert the decimal part. Repeatedly multiply by the radix to
407 // generate the next char. Never generate more than kBufferSize - 1
408 // chars.
409 //
410 // TODO(1093998): We will often generate a full decimal_buffer of
411 // chars because hitting zero will often not happen. The right
412 // solution would be to continue until the string representation can
413 // be read back and yield the original value. To implement this
414 // efficiently, we probably have to modify dtoa.
415 int decimal_pos = 0;
416 while ((decimal_part > 0.0) && (decimal_pos < kBufferSize - 1)) {
417 decimal_part *= radix;
418 decimal_buffer[decimal_pos++] =
419 chars[static_cast<int>(floor(decimal_part))];
420 decimal_part -= floor(decimal_part);
421 }
422 decimal_buffer[decimal_pos] = '\0';
423
424 // Compute the result size.
425 int integer_part_size = kBufferSize - 2 - integer_pos;
426 // Make room for zero termination.
427 unsigned result_size = integer_part_size + decimal_pos;
428 // If the number has a decimal part, leave room for the period.
429 if (decimal_pos > 0) result_size++;
430 // Allocate result and fill in the parts.
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +0000431 SimpleStringBuilder builder(result_size + 1);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000432 builder.AddSubstring(integer_buffer + integer_pos + 1, integer_part_size);
433 if (decimal_pos > 0) builder.AddCharacter('.');
434 builder.AddSubstring(decimal_buffer, decimal_pos);
435 return builder.Finalize();
436}
437
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000438} } // namespace v8::internal