Imported Upstream version 1.0.0
[platform/upstream/js.git] / js / src / jsnum.cpp
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2  *
3  * ***** BEGIN LICENSE BLOCK *****
4  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5  *
6  * The contents of this file are subject to the Mozilla Public License Version
7  * 1.1 (the "License"); you may not use this file except in compliance with
8  * the License. You may obtain a copy of the License at
9  * http://www.mozilla.org/MPL/
10  *
11  * Software distributed under the License is distributed on an "AS IS" basis,
12  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13  * for the specific language governing rights and limitations under the
14  * License.
15  *
16  * The Original Code is Mozilla Communicator client code, released
17  * March 31, 1998.
18  *
19  * The Initial Developer of the Original Code is
20  * Netscape Communications Corporation.
21  * Portions created by the Initial Developer are Copyright (C) 1998
22  * the Initial Developer. All Rights Reserved.
23  *
24  * Contributor(s):
25  *   IBM Corp.
26  *
27  * Alternatively, the contents of this file may be used under the terms of
28  * either of the GNU General Public License Version 2 or later (the "GPL"),
29  * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
30  * in which case the provisions of the GPL or the LGPL are applicable instead
31  * of those above. If you wish to allow use of your version of this file only
32  * under the terms of either the GPL or the LGPL, and not to allow others to
33  * use your version of this file under the terms of the MPL, indicate your
34  * decision by deleting the provisions above and replace them with the notice
35  * and other provisions required by the GPL or the LGPL. If you do not delete
36  * the provisions above, a recipient may use your version of this file under
37  * the terms of any one of the MPL, the GPL or the LGPL.
38  *
39  * ***** END LICENSE BLOCK ***** */
40
41 /*
42  * JS number type and wrapper class.
43  */
44 #ifdef XP_OS2
45 #define _PC_53  PC_53
46 #define _MCW_EM MCW_EM
47 #define _MCW_PC MCW_PC
48 #endif
49 #include <locale.h>
50 #include <limits.h>
51 #include <math.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include "jstypes.h"
55 #include "jsstdint.h"
56 #include "jsutil.h"
57 #include "jsapi.h"
58 #include "jsatom.h"
59 #include "jsbuiltins.h"
60 #include "jscntxt.h"
61 #include "jsversion.h"
62 #include "jsdtoa.h"
63 #include "jsgc.h"
64 #include "jsinterp.h"
65 #include "jsnum.h"
66 #include "jsobj.h"
67 #include "jsopcode.h"
68 #include "jsprf.h"
69 #include "jsscope.h"
70 #include "jsstr.h"
71 #include "jstracer.h"
72 #include "jsvector.h"
73
74 #include "jsinterpinlines.h"
75 #include "jsobjinlines.h"
76 #include "jsstrinlines.h"
77
78 using namespace js;
79
80 #ifndef JS_HAVE_STDINT_H /* Native support is innocent until proven guilty. */
81
82 JS_STATIC_ASSERT(uint8_t(-1) == UINT8_MAX);
83 JS_STATIC_ASSERT(uint16_t(-1) == UINT16_MAX);
84 JS_STATIC_ASSERT(uint32_t(-1) == UINT32_MAX);
85 JS_STATIC_ASSERT(uint64_t(-1) == UINT64_MAX);
86
87 JS_STATIC_ASSERT(INT8_MAX > INT8_MIN);
88 JS_STATIC_ASSERT(uint8_t(INT8_MAX) + uint8_t(1) == uint8_t(INT8_MIN));
89 JS_STATIC_ASSERT(INT16_MAX > INT16_MIN);
90 JS_STATIC_ASSERT(uint16_t(INT16_MAX) + uint16_t(1) == uint16_t(INT16_MIN));
91 JS_STATIC_ASSERT(INT32_MAX > INT32_MIN);
92 JS_STATIC_ASSERT(uint32_t(INT32_MAX) + uint32_t(1) == uint32_t(INT32_MIN));
93 JS_STATIC_ASSERT(INT64_MAX > INT64_MIN);
94 JS_STATIC_ASSERT(uint64_t(INT64_MAX) + uint64_t(1) == uint64_t(INT64_MIN));
95
96 JS_STATIC_ASSERT(INTPTR_MAX > INTPTR_MIN);
97 JS_STATIC_ASSERT(uintptr_t(INTPTR_MAX) + uintptr_t(1) == uintptr_t(INTPTR_MIN));
98 JS_STATIC_ASSERT(uintptr_t(-1) == UINTPTR_MAX);
99 JS_STATIC_ASSERT(size_t(-1) == SIZE_MAX);
100 JS_STATIC_ASSERT(PTRDIFF_MAX > PTRDIFF_MIN);
101 JS_STATIC_ASSERT(ptrdiff_t(PTRDIFF_MAX) == PTRDIFF_MAX);
102 JS_STATIC_ASSERT(ptrdiff_t(PTRDIFF_MIN) == PTRDIFF_MIN);
103 JS_STATIC_ASSERT(uintptr_t(PTRDIFF_MAX) + uintptr_t(1) == uintptr_t(PTRDIFF_MIN));
104
105 #endif /* JS_HAVE_STDINT_H */
106
107 /*
108  * If we're accumulating a decimal number and the number is >= 2^53, then the
109  * fast result from the loop in GetPrefixInteger may be inaccurate. Call
110  * js_strtod_harder to get the correct answer.
111  */
112 static bool
113 ComputeAccurateDecimalInteger(JSContext *cx, const jschar *start, const jschar *end, jsdouble *dp)
114 {
115     size_t length = end - start;
116     char *cstr = static_cast<char *>(cx->malloc(length + 1));
117     if (!cstr)
118         return false;
119
120     for (size_t i = 0; i < length; i++) {
121         char c = char(start[i]);
122         JS_ASSERT(('0' <= c && c <= '9') || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'));
123         cstr[i] = c;
124     }
125     cstr[length] = 0;
126
127     char *estr;
128     int err = 0;
129     *dp = js_strtod_harder(JS_THREAD_DATA(cx)->dtoaState, cstr, &estr, &err);
130     if (err == JS_DTOA_ENOMEM) {
131         JS_ReportOutOfMemory(cx);
132         cx->free(cstr);
133         return false;
134     }
135     if (err == JS_DTOA_ERANGE && *dp == HUGE_VAL)
136         *dp = js_PositiveInfinity;
137     cx->free(cstr);
138     return true;
139 }
140
141 class BinaryDigitReader
142 {
143     const int base;      /* Base of number; must be a power of 2 */
144     int digit;           /* Current digit value in radix given by base */
145     int digitMask;       /* Mask to extract the next bit from digit */
146     const jschar *start; /* Pointer to the remaining digits */
147     const jschar *end;   /* Pointer to first non-digit */
148
149   public:
150     BinaryDigitReader(int base, const jschar *start, const jschar *end)
151       : base(base), digit(0), digitMask(0), start(start), end(end)
152     {
153     }
154
155     /* Return the next binary digit from the number, or -1 if done. */
156     int nextDigit() {
157         if (digitMask == 0) {
158             if (start == end)
159                 return -1;
160
161             int c = *start++;
162             JS_ASSERT(('0' <= c && c <= '9') || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'));
163             if ('0' <= c && c <= '9')
164                 digit = c - '0';
165             else if ('a' <= c && c <= 'z')
166                 digit = c - 'a' + 10;
167             else
168                 digit = c - 'A' + 10;
169             digitMask = base >> 1;
170         }
171
172         int bit = (digit & digitMask) != 0;
173         digitMask >>= 1;
174         return bit;
175     }
176 };
177
178 /*
179  * The fast result might also have been inaccurate for power-of-two bases. This
180  * happens if the addition in value * 2 + digit causes a round-down to an even
181  * least significant mantissa bit when the first dropped bit is a one.  If any
182  * of the following digits in the number (which haven't been added in yet) are
183  * nonzero, then the correct action would have been to round up instead of
184  * down.  An example occurs when reading the number 0x1000000000000081, which
185  * rounds to 0x1000000000000000 instead of 0x1000000000000100.
186  */
187 static jsdouble
188 ComputeAccurateBinaryBaseInteger(JSContext *cx, const jschar *start, const jschar *end, int base)
189 {
190     BinaryDigitReader bdr(base, start, end);
191
192     /* Skip leading zeroes. */
193     int bit;
194     do {
195         bit = bdr.nextDigit();
196     } while (bit == 0);
197
198     JS_ASSERT(bit == 1); // guaranteed by GetPrefixInteger
199
200     /* Gather the 53 significant bits (including the leading 1). */
201     jsdouble value = 1.0;
202     for (int j = 52; j > 0; j--) {
203         bit = bdr.nextDigit();
204         if (bit < 0)
205             return value;
206         value = value * 2 + bit;
207     }
208
209     /* bit2 is the 54th bit (the first dropped from the mantissa). */
210     int bit2 = bdr.nextDigit();
211     if (bit2 >= 0) {
212         jsdouble factor = 2.0;
213         int sticky = 0;  /* sticky is 1 if any bit beyond the 54th is 1 */
214         int bit3;
215
216         while ((bit3 = bdr.nextDigit()) >= 0) {
217             sticky |= bit3;
218             factor *= 2;
219         }
220         value += bit2 & (bit | sticky);
221         value *= factor;
222     }
223
224     return value;
225 }
226
227 namespace js {
228
229 bool
230 GetPrefixInteger(JSContext *cx, const jschar *start, const jschar *end, int base,
231                  const jschar **endp, jsdouble *dp)
232 {
233     JS_ASSERT(start <= end);
234     JS_ASSERT(2 <= base && base <= 36);
235
236     const jschar *s = start;
237     jsdouble d = 0.0;
238     for (; s < end; s++) {
239         int digit;
240         jschar c = *s;
241         if ('0' <= c && c <= '9')
242             digit = c - '0';
243         else if ('a' <= c && c <= 'z')
244             digit = c - 'a' + 10;
245         else if ('A' <= c && c <= 'Z')
246             digit = c - 'A' + 10;
247         else
248             break;
249         if (digit >= base)
250             break;
251         d = d * base + digit;
252     }
253
254     *endp = s;
255     *dp = d;
256
257     /* If we haven't reached the limit of integer precision, we're done. */
258     if (d < DOUBLE_INTEGRAL_PRECISION_LIMIT)
259         return true;
260
261     /*
262      * Otherwise compute the correct integer from the prefix of valid digits
263      * if we're computing for base ten or a power of two.  Don't worry about
264      * other bases; see 15.1.2.2 step 13.
265      */
266     if (base == 10)
267         return ComputeAccurateDecimalInteger(cx, start, s, dp);
268     if ((base & (base - 1)) == 0)
269         *dp = ComputeAccurateBinaryBaseInteger(cx, start, s, base);
270
271     return true;
272 }
273
274 } // namespace js
275
276 static JSBool
277 num_isNaN(JSContext *cx, uintN argc, Value *vp)
278 {
279     if (argc == 0) {
280         vp->setBoolean(true);
281         return JS_TRUE;
282     }
283     jsdouble x;
284     if (!ValueToNumber(cx, vp[2], &x))
285         return false;
286     vp->setBoolean(JSDOUBLE_IS_NaN(x));
287     return JS_TRUE;
288 }
289
290 static JSBool
291 num_isFinite(JSContext *cx, uintN argc, Value *vp)
292 {
293     if (argc == 0) {
294         vp->setBoolean(false);
295         return JS_TRUE;
296     }
297     jsdouble x;
298     if (!ValueToNumber(cx, vp[2], &x))
299         return JS_FALSE;
300     vp->setBoolean(JSDOUBLE_IS_FINITE(x));
301     return JS_TRUE;
302 }
303
304 static JSBool
305 num_parseFloat(JSContext *cx, uintN argc, Value *vp)
306 {
307     JSString *str;
308     jsdouble d;
309     const jschar *bp, *end, *ep;
310
311     if (argc == 0) {
312         vp->setDouble(js_NaN);
313         return JS_TRUE;
314     }
315     str = js_ValueToString(cx, vp[2]);
316     if (!str)
317         return JS_FALSE;
318     bp = str->getChars(cx);
319     if (!bp)
320         return JS_FALSE;
321     end = bp + str->length();
322     if (!js_strtod(cx, bp, end, &ep, &d))
323         return JS_FALSE;
324     if (ep == bp) {
325         vp->setDouble(js_NaN);
326         return JS_TRUE;
327     }
328     vp->setNumber(d);
329     return JS_TRUE;
330 }
331
332 #ifdef JS_TRACER
333 static jsdouble FASTCALL
334 ParseFloat(JSContext* cx, JSString* str)
335 {
336     TraceMonitor *tm = JS_TRACE_MONITOR_ON_TRACE(cx);
337
338     const jschar *bp = str->getChars(cx);
339     if (!bp) {
340         SetBuiltinError(tm);
341         return js_NaN;
342     }
343     const jschar *end = bp + str->length();
344
345     const jschar *ep;
346     double d;
347     if (!js_strtod(cx, bp, end, &ep, &d) || ep == bp)
348         return js_NaN;
349     return d;
350 }
351 #endif
352
353 static bool
354 ParseIntStringHelper(JSContext *cx, const jschar *ws, const jschar *end, int maybeRadix,
355                      bool stripPrefix, jsdouble *dp)
356 {
357     JS_ASSERT(maybeRadix == 0 || (2 <= maybeRadix && maybeRadix <= 36));
358     JS_ASSERT(ws <= end);
359
360     const jschar *s = js_SkipWhiteSpace(ws, end);
361     JS_ASSERT(ws <= s);
362     JS_ASSERT(s <= end);
363
364     /* 15.1.2.2 steps 3-4. */
365     bool negative = (s != end && s[0] == '-');
366
367     /* 15.1.2.2 step 5. */
368     if (s != end && (s[0] == '-' || s[0] == '+'))
369         s++;
370
371     /* 15.1.2.2 step 9. */
372     int radix = maybeRadix;
373     if (radix == 0) {
374         if (end - s >= 2 && s[0] == '0' && (s[1] != 'x' && s[1] != 'X')) {
375             /*
376              * Non-standard: ES5 requires that parseInt interpret leading-zero
377              * strings not starting with "0x" or "0X" as decimal (absent an
378              * explicitly specified non-zero radix), but we continue to
379              * interpret such strings as octal, as per ES3 and web practice.
380              */
381             radix = 8;
382         } else {
383             radix = 10;
384         }
385     }
386
387     /* 15.1.2.2 step 10. */
388     if (stripPrefix) {
389         if (end - s >= 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) {
390             s += 2;
391             radix = 16;
392         }
393     }
394
395     /* 15.1.2.2 steps 11-14. */
396     const jschar *actualEnd;
397     if (!GetPrefixInteger(cx, s, end, radix, &actualEnd, dp))
398         return false;
399     if (s == actualEnd)
400         *dp = js_NaN;
401     else if (negative)
402         *dp = -*dp;
403     return true;
404 }
405
406 static jsdouble
407 ParseIntDoubleHelper(jsdouble d)
408 {
409     if (!JSDOUBLE_IS_FINITE(d))
410         return js_NaN;
411     if (d > 0)
412         return floor(d);
413     if (d < 0)
414         return -floor(-d);
415     return 0;
416 }
417
418 /* See ECMA 15.1.2.2. */
419 static JSBool
420 num_parseInt(JSContext *cx, uintN argc, Value *vp)
421 {
422     /* Fast paths and exceptional cases. */
423     if (argc == 0) {
424         vp->setDouble(js_NaN);
425         return true;
426     }
427
428     if (argc == 1 || (vp[3].isInt32() && (vp[3].toInt32() == 0 || vp[3].toInt32() == 10))) {
429         if (vp[2].isInt32()) {
430             *vp = vp[2];
431             return true;
432         }
433         if (vp[2].isDouble()) {
434             vp->setDouble(ParseIntDoubleHelper(vp[2].toDouble()));
435             return true;
436         }
437     }
438
439     /* Step 1. */
440     JSString *inputString = js_ValueToString(cx, vp[2]);
441     if (!inputString)
442         return false;
443     vp[2].setString(inputString);
444
445     /* 15.1.2.2 steps 6-8. */
446     bool stripPrefix = true;
447     int32_t radix = 0;
448     if (argc > 1) {
449         if (!ValueToECMAInt32(cx, vp[3], &radix))
450             return false;
451         if (radix != 0) {
452             if (radix < 2 || radix > 36) {
453                 vp->setDouble(js_NaN);
454                 return true;
455             }
456             if (radix != 16)
457                 stripPrefix = false;
458         }
459     }
460
461     /* Steps 2-5, 9-14. */
462     const jschar *ws = inputString->getChars(cx);
463     if (!ws)
464         return false;
465     const jschar *end = ws + inputString->length();
466
467     jsdouble number;
468     if (!ParseIntStringHelper(cx, ws, end, radix, stripPrefix, &number))
469         return false;
470
471     /* Step 15. */
472     vp->setNumber(number);
473     return true;
474 }
475
476 #ifdef JS_TRACER
477 static jsdouble FASTCALL
478 ParseInt(JSContext* cx, JSString* str)
479 {
480     TraceMonitor *tm = JS_TRACE_MONITOR_ON_TRACE(cx);
481
482     const jschar *start = str->getChars(cx);
483     if (!start) {
484         SetBuiltinError(tm);
485         return js_NaN;
486     }
487     const jschar *end = start + str->length();
488
489     jsdouble d;
490     if (!ParseIntStringHelper(cx, start, end, 0, true, &d)) {
491         SetBuiltinError(tm);
492         return js_NaN;
493     }
494     return d;
495 }
496
497 static jsdouble FASTCALL
498 ParseIntDouble(jsdouble d)
499 {
500     return ParseIntDoubleHelper(d);
501 }
502 #endif
503
504 const char js_Infinity_str[]   = "Infinity";
505 const char js_NaN_str[]        = "NaN";
506 const char js_isNaN_str[]      = "isNaN";
507 const char js_isFinite_str[]   = "isFinite";
508 const char js_parseFloat_str[] = "parseFloat";
509 const char js_parseInt_str[]   = "parseInt";
510
511 #ifdef JS_TRACER
512
513 JS_DEFINE_TRCINFO_2(num_parseInt,
514     (2, (static, DOUBLE_FAIL, ParseInt, CONTEXT, STRING,1, nanojit::ACCSET_NONE)),
515     (1, (static, DOUBLE, ParseIntDouble, DOUBLE,        1, nanojit::ACCSET_NONE)))
516
517 JS_DEFINE_TRCINFO_1(num_parseFloat,
518     (2, (static, DOUBLE_FAIL, ParseFloat, CONTEXT, STRING,   1, nanojit::ACCSET_NONE)))
519
520 #endif /* JS_TRACER */
521
522 static JSFunctionSpec number_functions[] = {
523     JS_FN(js_isNaN_str,         num_isNaN,           1,0),
524     JS_FN(js_isFinite_str,      num_isFinite,        1,0),
525     JS_TN(js_parseFloat_str,    num_parseFloat,      1,0, &num_parseFloat_trcinfo),
526     JS_TN(js_parseInt_str,      num_parseInt,        2,0, &num_parseInt_trcinfo),
527     JS_FS_END
528 };
529
530 Class js_NumberClass = {
531     js_Number_str,
532     JSCLASS_HAS_RESERVED_SLOTS(1) | JSCLASS_HAS_CACHED_PROTO(JSProto_Number),
533     PropertyStub,         /* addProperty */
534     PropertyStub,         /* delProperty */
535     PropertyStub,         /* getProperty */
536     StrictPropertyStub,   /* setProperty */
537     EnumerateStub,
538     ResolveStub,
539     ConvertStub
540 };
541
542 static JSBool
543 Number(JSContext *cx, uintN argc, Value *vp)
544 {
545     /* Sample JS_CALLEE before clobbering. */
546     bool isConstructing = IsConstructing(vp);
547
548     if (argc > 0) {
549         if (!ValueToNumber(cx, &vp[2]))
550             return false;
551         vp[0] = vp[2];
552     } else {
553         vp[0].setInt32(0);
554     }
555
556     if (!isConstructing)
557         return true;
558     
559     JSObject *obj = NewBuiltinClassInstance(cx, &js_NumberClass);
560     if (!obj)
561         return false;
562     obj->setPrimitiveThis(vp[0]);
563     vp->setObject(*obj);
564     return true;
565 }
566
567 #if JS_HAS_TOSOURCE
568 static JSBool
569 num_toSource(JSContext *cx, uintN argc, Value *vp)
570 {
571     double d;
572     if (!GetPrimitiveThis(cx, vp, &d))
573         return false;
574
575     ToCStringBuf cbuf;
576     char *numStr = NumberToCString(cx, &cbuf, d);
577     if (!numStr) {
578         JS_ReportOutOfMemory(cx);
579         return false;
580     }
581
582     char buf[64];
583     JS_snprintf(buf, sizeof buf, "(new %s(%s))", js_NumberClass.name, numStr);
584     JSString *str = js_NewStringCopyZ(cx, buf);
585     if (!str)
586         return false;
587     vp->setString(str);
588     return true;
589 }
590 #endif
591
592 ToCStringBuf::ToCStringBuf() :dbuf(NULL)
593 {
594     JS_STATIC_ASSERT(sbufSize >= DTOSTR_STANDARD_BUFFER_SIZE);
595 }
596
597 ToCStringBuf::~ToCStringBuf()
598 {
599     if (dbuf)
600         js_free(dbuf);
601 }
602
603 JSString * JS_FASTCALL
604 js_IntToString(JSContext *cx, int32 si)
605 {
606     uint32 ui;
607     if (si >= 0) {
608         if (si < INT_STRING_LIMIT)
609             return JSString::intString(si);
610         ui = si;
611     } else {
612         ui = uint32(-si);
613         JS_ASSERT_IF(si == INT32_MIN, ui == uint32(INT32_MAX) + 1);
614     }
615
616     JSCompartment *c = cx->compartment;
617     if (JSString *str = c->dtoaCache.lookup(10, si))
618         return str;
619
620     JSShortString *str = js_NewGCShortString(cx);
621     if (!str)
622         return NULL;
623
624     /* +1, since MAX_SHORT_STRING_LENGTH does not count the null char. */
625     JS_STATIC_ASSERT(JSShortString::MAX_SHORT_STRING_LENGTH + 1 >= sizeof("-2147483648"));
626
627     jschar *end = str->getInlineStorageBeforeInit() + JSShortString::MAX_SHORT_STRING_LENGTH;
628     jschar *cp = end;
629     *cp = 0;
630
631     do {
632         jsuint newui = ui / 10, digit = ui % 10;  /* optimizers are our friends */
633         *--cp = '0' + digit;
634         ui = newui;
635     } while (ui != 0);
636
637     if (si < 0)
638         *--cp = '-';
639
640     str->initAtOffsetInBuffer(cp, end - cp);
641
642     JSString *ret = str->header();
643     c->dtoaCache.cache(10, si, ret);
644     return ret;
645 }
646
647 /* Returns a non-NULL pointer to inside cbuf.  */
648 static char *
649 IntToCString(ToCStringBuf *cbuf, jsint i, jsint base = 10)
650 {
651     char *cp;
652     jsuint u;
653
654     u = (i < 0) ? -i : i;
655
656     cp = cbuf->sbuf + cbuf->sbufSize;   /* one past last buffer cell */
657     *--cp = '\0';                       /* null terminate the string to be */
658
659     /*
660      * Build the string from behind. We use multiply and subtraction
661      * instead of modulus because that's much faster.
662      */
663     switch (base) {
664     case 10:
665       do {
666           jsuint newu = u / 10;
667           *--cp = (char)(u - newu * 10) + '0';
668           u = newu;
669       } while (u != 0);
670       break;
671     case 16:
672       do {
673           jsuint newu = u / 16;
674           *--cp = "0123456789abcdef"[u - newu * 16];
675           u = newu;
676       } while (u != 0);
677       break;
678     default:
679       JS_ASSERT(base >= 2 && base <= 36);
680       do {
681           jsuint newu = u / base;
682           *--cp = "0123456789abcdefghijklmnopqrstuvwxyz"[u - newu * base];
683           u = newu;
684       } while (u != 0);
685       break;
686     }
687     if (i < 0)
688         *--cp = '-';
689
690     JS_ASSERT(cp >= cbuf->sbuf);
691     return cp;
692 }
693
694 static JSString * JS_FASTCALL
695 js_NumberToStringWithBase(JSContext *cx, jsdouble d, jsint base);
696
697 static JSBool
698 num_toString(JSContext *cx, uintN argc, Value *vp)
699 {
700     double d;
701     if (!GetPrimitiveThis(cx, vp, &d))
702         return false;
703
704     int32_t base = 10;
705     if (argc != 0 && !vp[2].isUndefined()) {
706         if (!ValueToECMAInt32(cx, vp[2], &base))
707             return JS_FALSE;
708
709         if (base < 2 || base > 36) {
710             ToCStringBuf cbuf;
711             char *numStr = IntToCString(&cbuf, base);   /* convert the base itself to a string */
712             JS_ASSERT(numStr);
713             JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_RADIX,
714                                  numStr);
715             return JS_FALSE;
716         }
717     }
718     JSString *str = js_NumberToStringWithBase(cx, d, base);
719     if (!str) {
720         JS_ReportOutOfMemory(cx);
721         return JS_FALSE;
722     }
723     vp->setString(str);
724     return JS_TRUE;
725 }
726
727 static JSBool
728 num_toLocaleString(JSContext *cx, uintN argc, Value *vp)
729 {
730     size_t thousandsLength, decimalLength;
731     const char *numGrouping, *tmpGroup;
732     JSRuntime *rt;
733     JSString *str;
734     const char *num, *end, *tmpSrc;
735     char *buf, *tmpDest;
736     const char *nint;
737     int digits, buflen, remainder, nrepeat;
738
739     /*
740      * Create the string, move back to bytes to make string twiddling
741      * a bit easier and so we can insert platform charset seperators.
742      */
743     if (!num_toString(cx, 0, vp))
744         return JS_FALSE;
745     JS_ASSERT(vp->isString());
746     JSAutoByteString numBytes(cx, vp->toString());
747     if (!numBytes)
748         return JS_FALSE;
749     num = numBytes.ptr();
750     if (!num)
751         return JS_FALSE;
752
753     /*
754      * Find the first non-integer value, whether it be a letter as in
755      * 'Infinity', a decimal point, or an 'e' from exponential notation.
756      */
757     nint = num;
758     if (*nint == '-')
759         nint++;
760     while (*nint >= '0' && *nint <= '9')
761         nint++;
762     digits = nint - num;
763     end = num + digits;
764     if (!digits)
765         return JS_TRUE;
766
767     rt = cx->runtime;
768     thousandsLength = strlen(rt->thousandsSeparator);
769     decimalLength = strlen(rt->decimalSeparator);
770
771     /* Figure out how long resulting string will be. */
772     buflen = strlen(num);
773     if (*nint == '.')
774         buflen += decimalLength - 1; /* -1 to account for existing '.' */
775
776     numGrouping = tmpGroup = rt->numGrouping;
777     remainder = digits;
778     if (*num == '-')
779         remainder--;
780
781     while (*tmpGroup != CHAR_MAX && *tmpGroup != '\0') {
782         if (*tmpGroup >= remainder)
783             break;
784         buflen += thousandsLength;
785         remainder -= *tmpGroup;
786         tmpGroup++;
787     }
788     if (*tmpGroup == '\0' && *numGrouping != '\0') {
789         nrepeat = (remainder - 1) / tmpGroup[-1];
790         buflen += thousandsLength * nrepeat;
791         remainder -= nrepeat * tmpGroup[-1];
792     } else {
793         nrepeat = 0;
794     }
795     tmpGroup--;
796
797     buf = (char *)cx->malloc(buflen + 1);
798     if (!buf)
799         return JS_FALSE;
800
801     tmpDest = buf;
802     tmpSrc = num;
803
804     while (*tmpSrc == '-' || remainder--) {
805         JS_ASSERT(tmpDest - buf < buflen);
806         *tmpDest++ = *tmpSrc++;
807     }
808     while (tmpSrc < end) {
809         JS_ASSERT(tmpDest - buf + ptrdiff_t(thousandsLength) <= buflen);
810         strcpy(tmpDest, rt->thousandsSeparator);
811         tmpDest += thousandsLength;
812         JS_ASSERT(tmpDest - buf + *tmpGroup <= buflen);
813         memcpy(tmpDest, tmpSrc, *tmpGroup);
814         tmpDest += *tmpGroup;
815         tmpSrc += *tmpGroup;
816         if (--nrepeat < 0)
817             tmpGroup--;
818     }
819
820     if (*nint == '.') {
821         JS_ASSERT(tmpDest - buf + ptrdiff_t(decimalLength) <= buflen);
822         strcpy(tmpDest, rt->decimalSeparator);
823         tmpDest += decimalLength;
824         JS_ASSERT(tmpDest - buf + ptrdiff_t(strlen(nint + 1)) <= buflen);
825         strcpy(tmpDest, nint + 1);
826     } else {
827         JS_ASSERT(tmpDest - buf + ptrdiff_t(strlen(nint)) <= buflen);
828         strcpy(tmpDest, nint);
829     }
830
831     if (cx->localeCallbacks && cx->localeCallbacks->localeToUnicode) {
832         JSBool ok = cx->localeCallbacks->localeToUnicode(cx, buf, Jsvalify(vp));
833         cx->free(buf);
834         return ok;
835     }
836
837     str = js_NewStringCopyN(cx, buf, buflen);
838     cx->free(buf);
839     if (!str)
840         return JS_FALSE;
841
842     vp->setString(str);
843     return JS_TRUE;
844 }
845
846 JSBool
847 js_num_valueOf(JSContext *cx, uintN argc, Value *vp)
848 {
849     double d;
850     if (!GetPrimitiveThis(cx, vp, &d))
851         return false;
852
853     vp->setNumber(d);
854     return true;
855 }
856
857
858 #define MAX_PRECISION 100
859
860 static JSBool
861 num_to(JSContext *cx, JSDToStrMode zeroArgMode, JSDToStrMode oneArgMode,
862        jsint precisionMin, jsint precisionMax, jsint precisionOffset,
863        uintN argc, Value *vp)
864 {
865     /* Use MAX_PRECISION+1 because precisionOffset can be 1. */
866     char buf[DTOSTR_VARIABLE_BUFFER_SIZE(MAX_PRECISION+1)];
867     char *numStr;
868
869     double d;
870     if (!GetPrimitiveThis(cx, vp, &d))
871         return false;
872
873     double precision;
874     if (argc == 0) {
875         precision = 0.0;
876         oneArgMode = zeroArgMode;
877     } else {
878         if (!ValueToNumber(cx, vp[2], &precision))
879             return JS_FALSE;
880         precision = js_DoubleToInteger(precision);
881         if (precision < precisionMin || precision > precisionMax) {
882             ToCStringBuf cbuf;
883             numStr = IntToCString(&cbuf, jsint(precision));
884             JS_ASSERT(numStr);
885             JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_PRECISION_RANGE, numStr);
886             return JS_FALSE;
887         }
888     }
889
890     numStr = js_dtostr(JS_THREAD_DATA(cx)->dtoaState, buf, sizeof buf,
891                        oneArgMode, (jsint)precision + precisionOffset, d);
892     if (!numStr) {
893         JS_ReportOutOfMemory(cx);
894         return JS_FALSE;
895     }
896     JSString *str = js_NewStringCopyZ(cx, numStr);
897     if (!str)
898         return JS_FALSE;
899     vp->setString(str);
900     return JS_TRUE;
901 }
902
903 /*
904  * In the following three implementations, we allow a larger range of precision
905  * than ECMA requires; this is permitted by ECMA-262.
906  */
907 static JSBool
908 num_toFixed(JSContext *cx, uintN argc, Value *vp)
909 {
910     return num_to(cx, DTOSTR_FIXED, DTOSTR_FIXED, -20, MAX_PRECISION, 0,
911                   argc, vp);
912 }
913
914 static JSBool
915 num_toExponential(JSContext *cx, uintN argc, Value *vp)
916 {
917     return num_to(cx, DTOSTR_STANDARD_EXPONENTIAL, DTOSTR_EXPONENTIAL, 0, MAX_PRECISION, 1,
918                   argc, vp);
919 }
920
921 static JSBool
922 num_toPrecision(JSContext *cx, uintN argc, Value *vp)
923 {
924     if (argc == 0 || vp[2].isUndefined())
925         return num_toString(cx, 0, vp);
926     return num_to(cx, DTOSTR_STANDARD, DTOSTR_PRECISION, 1, MAX_PRECISION, 0,
927                   argc, vp);
928 }
929
930 #ifdef JS_TRACER
931
932 JS_DEFINE_TRCINFO_2(num_toString,
933     (2, (extern, STRING_RETRY, js_NumberToString,         CONTEXT, THIS_DOUBLE,
934          1, nanojit::ACCSET_NONE)),
935     (3, (static, STRING_RETRY, js_NumberToStringWithBase, CONTEXT, THIS_DOUBLE, INT32,
936          1, nanojit::ACCSET_NONE)))
937
938 #endif /* JS_TRACER */
939
940 static JSFunctionSpec number_methods[] = {
941 #if JS_HAS_TOSOURCE
942     JS_FN(js_toSource_str,       num_toSource,          0, 0),
943 #endif
944     JS_TN(js_toString_str,       num_toString,          1, 0, &num_toString_trcinfo),
945     JS_FN(js_toLocaleString_str, num_toLocaleString,    0, 0),
946     JS_FN(js_valueOf_str,        js_num_valueOf,        0, 0),
947     JS_FN(js_toJSON_str,         js_num_valueOf,        0, 0),
948     JS_FN("toFixed",             num_toFixed,           1, 0),
949     JS_FN("toExponential",       num_toExponential,     1, 0),
950     JS_FN("toPrecision",         num_toPrecision,       1, 0),
951     JS_FS_END
952 };
953
954 /* NB: Keep this in synch with number_constants[]. */
955 enum nc_slot {
956     NC_NaN,
957     NC_POSITIVE_INFINITY,
958     NC_NEGATIVE_INFINITY,
959     NC_MAX_VALUE,
960     NC_MIN_VALUE,
961     NC_LIMIT
962 };
963
964 /*
965  * Some to most C compilers forbid spelling these at compile time, or barf
966  * if you try, so all but MAX_VALUE are set up by js_InitRuntimeNumberState
967  * using union jsdpun.
968  */
969 static JSConstDoubleSpec number_constants[] = {
970     {0,                         js_NaN_str,          0,{0,0,0}},
971     {0,                         "POSITIVE_INFINITY", 0,{0,0,0}},
972     {0,                         "NEGATIVE_INFINITY", 0,{0,0,0}},
973     {1.7976931348623157E+308,   "MAX_VALUE",         0,{0,0,0}},
974     {0,                         "MIN_VALUE",         0,{0,0,0}},
975     {0,0,0,{0,0,0}}
976 };
977
978 jsdouble js_NaN;
979 jsdouble js_PositiveInfinity;
980 jsdouble js_NegativeInfinity;
981
982 #if (defined __GNUC__ && defined __i386__) || \
983     (defined __SUNPRO_CC && defined __i386)
984
985 /*
986  * Set the exception mask to mask all exceptions and set the FPU precision
987  * to 53 bit mantissa (64 bit doubles).
988  */
989 inline void FIX_FPU() {
990     short control;
991     asm("fstcw %0" : "=m" (control) : );
992     control &= ~0x300; // Lower bits 8 and 9 (precision control).
993     control |= 0x2f3;  // Raise bits 0-5 (exception masks) and 9 (64-bit precision).
994     asm("fldcw %0" : : "m" (control) );
995 }
996
997 #else
998
999 #define FIX_FPU() ((void)0)
1000
1001 #endif
1002
1003 JSBool
1004 js_InitRuntimeNumberState(JSContext *cx)
1005 {
1006     JSRuntime *rt = cx->runtime;
1007
1008     FIX_FPU();
1009
1010     jsdpun u;
1011     u.s.hi = JSDOUBLE_HI32_NAN;
1012     u.s.lo = JSDOUBLE_LO32_NAN;
1013     number_constants[NC_NaN].dval = js_NaN = u.d;
1014     rt->NaNValue.setDouble(u.d);
1015
1016     u.s.hi = JSDOUBLE_HI32_EXPMASK;
1017     u.s.lo = 0x00000000;
1018     number_constants[NC_POSITIVE_INFINITY].dval = js_PositiveInfinity = u.d;
1019     rt->positiveInfinityValue.setDouble(u.d);
1020
1021     u.s.hi = JSDOUBLE_HI32_SIGNBIT | JSDOUBLE_HI32_EXPMASK;
1022     u.s.lo = 0x00000000;
1023     number_constants[NC_NEGATIVE_INFINITY].dval = js_NegativeInfinity = u.d;
1024     rt->negativeInfinityValue.setDouble(u.d);
1025
1026     u.s.hi = 0;
1027     u.s.lo = 1;
1028     number_constants[NC_MIN_VALUE].dval = u.d;
1029
1030 #ifndef HAVE_LOCALECONV
1031     const char* thousands_sep = getenv("LOCALE_THOUSANDS_SEP");
1032     const char* decimal_point = getenv("LOCALE_DECIMAL_POINT");
1033     const char* grouping = getenv("LOCALE_GROUPING");
1034
1035     rt->thousandsSeparator =
1036         JS_strdup(cx, thousands_sep ? thousands_sep : "'");
1037     rt->decimalSeparator =
1038         JS_strdup(cx, decimal_point ? decimal_point : ".");
1039     rt->numGrouping =
1040         JS_strdup(cx, grouping ? grouping : "\3\0");
1041 #else
1042     struct lconv *locale = localeconv();
1043     rt->thousandsSeparator =
1044         JS_strdup(cx, locale->thousands_sep ? locale->thousands_sep : "'");
1045     rt->decimalSeparator =
1046         JS_strdup(cx, locale->decimal_point ? locale->decimal_point : ".");
1047     rt->numGrouping =
1048         JS_strdup(cx, locale->grouping ? locale->grouping : "\3\0");
1049 #endif
1050
1051     return rt->thousandsSeparator && rt->decimalSeparator && rt->numGrouping;
1052 }
1053
1054 void
1055 js_FinishRuntimeNumberState(JSContext *cx)
1056 {
1057     JSRuntime *rt = cx->runtime;
1058
1059     cx->free((void *) rt->thousandsSeparator);
1060     cx->free((void *) rt->decimalSeparator);
1061     cx->free((void *) rt->numGrouping);
1062     rt->thousandsSeparator = rt->decimalSeparator = rt->numGrouping = NULL;
1063 }
1064
1065 JSObject *
1066 js_InitNumberClass(JSContext *cx, JSObject *obj)
1067 {
1068     JSObject *proto, *ctor;
1069     JSRuntime *rt;
1070
1071     /* XXX must do at least once per new thread, so do it per JSContext... */
1072     FIX_FPU();
1073
1074     if (!JS_DefineFunctions(cx, obj, number_functions))
1075         return NULL;
1076
1077     proto = js_InitClass(cx, obj, NULL, &js_NumberClass, Number, 1,
1078                          NULL, number_methods, NULL, NULL);
1079     if (!proto || !(ctor = JS_GetConstructor(cx, proto)))
1080         return NULL;
1081     proto->setPrimitiveThis(Int32Value(0));
1082     if (!JS_DefineConstDoubles(cx, ctor, number_constants))
1083         return NULL;
1084
1085     /* ECMA 15.1.1.1 */
1086     rt = cx->runtime;
1087     if (!JS_DefineProperty(cx, obj, js_NaN_str, Jsvalify(rt->NaNValue),
1088                            JS_PropertyStub, JS_StrictPropertyStub,
1089                            JSPROP_PERMANENT | JSPROP_READONLY)) {
1090         return NULL;
1091     }
1092
1093     /* ECMA 15.1.1.2 */
1094     if (!JS_DefineProperty(cx, obj, js_Infinity_str, Jsvalify(rt->positiveInfinityValue),
1095                            JS_PropertyStub, JS_StrictPropertyStub,
1096                            JSPROP_PERMANENT | JSPROP_READONLY)) {
1097         return NULL;
1098     }
1099     return proto;
1100 }
1101
1102 namespace v8 {
1103 namespace internal {
1104 extern char* DoubleToCString(double v, char* buffer, int buflen);
1105 }
1106 }
1107
1108 namespace js {
1109
1110 static char *
1111 FracNumberToCString(JSContext *cx, ToCStringBuf *cbuf, jsdouble d, jsint base = 10)
1112 {
1113 #ifdef DEBUG
1114     {
1115         int32_t _;
1116         JS_ASSERT(!JSDOUBLE_IS_INT32(d, &_));
1117     }
1118 #endif
1119
1120     char* numStr;
1121     if (base == 10) {
1122         /*
1123          * This is V8's implementation of the algorithm described in the
1124          * following paper:
1125          *
1126          *   Printing floating-point numbers quickly and accurately with integers. 
1127          *   Florian Loitsch, PLDI 2010.
1128          *
1129          * It fails on a small number of cases, whereupon we fall back to
1130          * js_dtostr() (which uses David Gay's dtoa).
1131          */
1132         numStr = v8::internal::DoubleToCString(d, cbuf->sbuf, cbuf->sbufSize);
1133         if (!numStr)
1134             numStr = js_dtostr(JS_THREAD_DATA(cx)->dtoaState, cbuf->sbuf, cbuf->sbufSize,
1135                                DTOSTR_STANDARD, 0, d);
1136     } else {
1137         numStr = cbuf->dbuf = js_dtobasestr(JS_THREAD_DATA(cx)->dtoaState, base, d);
1138     }
1139     return numStr;
1140 }
1141
1142 char *
1143 NumberToCString(JSContext *cx, ToCStringBuf *cbuf, jsdouble d, jsint base/* = 10*/)
1144 {
1145     int32_t i;
1146     return (JSDOUBLE_IS_INT32(d, &i))
1147            ? IntToCString(cbuf, i, base)
1148            : FracNumberToCString(cx, cbuf, d, base);
1149 }
1150
1151 }
1152
1153 static JSString * JS_FASTCALL
1154 js_NumberToStringWithBase(JSContext *cx, jsdouble d, jsint base)
1155 {
1156     ToCStringBuf cbuf;
1157     char *numStr;
1158     JSString *s;
1159
1160     /*
1161      * Caller is responsible for error reporting. When called from trace,
1162      * returning NULL here will cause us to fall of trace and then retry
1163      * from the interpreter (which will report the error).
1164      */
1165     if (base < 2 || base > 36)
1166         return NULL;
1167
1168     JSCompartment *c = cx->compartment;
1169
1170     int32_t i;
1171     if (JSDOUBLE_IS_INT32(d, &i)) {
1172         if (base == 10 && jsuint(i) < INT_STRING_LIMIT)
1173             return JSString::intString(i);
1174         if (jsuint(i) < jsuint(base)) {
1175             if (i < 10)
1176                 return JSString::intString(i);
1177             return JSString::unitString(jschar('a' + i - 10));
1178         }
1179
1180         if (JSString *str = c->dtoaCache.lookup(base, d))
1181             return str;
1182
1183         numStr = IntToCString(&cbuf, i, base);
1184         JS_ASSERT(!cbuf.dbuf && numStr >= cbuf.sbuf && numStr < cbuf.sbuf + cbuf.sbufSize);
1185     } else {
1186         if (JSString *str = c->dtoaCache.lookup(base, d))
1187             return str;
1188
1189         numStr = FracNumberToCString(cx, &cbuf, d, base);
1190         if (!numStr) {
1191             JS_ReportOutOfMemory(cx);
1192             return NULL;
1193         }
1194         JS_ASSERT_IF(base == 10,
1195                      !cbuf.dbuf && numStr >= cbuf.sbuf && numStr < cbuf.sbuf + cbuf.sbufSize);
1196         JS_ASSERT_IF(base != 10,
1197                      cbuf.dbuf && cbuf.dbuf == numStr);
1198     }
1199
1200     s = js_NewStringCopyZ(cx, numStr);
1201
1202     c->dtoaCache.cache(base, d, s);
1203     return s;
1204 }
1205
1206 JSString * JS_FASTCALL
1207 js_NumberToString(JSContext *cx, jsdouble d)
1208 {
1209     return js_NumberToStringWithBase(cx, d, 10);
1210 }
1211
1212 namespace js {
1213
1214 JSFlatString *
1215 NumberToString(JSContext *cx, jsdouble d)
1216 {
1217     if (JSString *str = js_NumberToStringWithBase(cx, d, 10))
1218         return str->assertIsFlat();
1219     return NULL;
1220 }
1221
1222 bool JS_FASTCALL
1223 NumberValueToStringBuffer(JSContext *cx, const Value &v, StringBuffer &sb)
1224 {
1225     /* Convert to C-string. */
1226     ToCStringBuf cbuf;
1227     const char *cstr;
1228     if (v.isInt32()) {
1229         cstr = IntToCString(&cbuf, v.toInt32());
1230     } else {
1231         cstr = NumberToCString(cx, &cbuf, v.toDouble());
1232         if (!cstr) {
1233             JS_ReportOutOfMemory(cx);
1234             return JS_FALSE;
1235         }
1236     }
1237
1238     /*
1239      * Inflate to jschar string.  The input C-string characters are < 127, so
1240      * even if jschars are UTF-8, all chars should map to one jschar.
1241      */
1242     size_t cstrlen = strlen(cstr);
1243     JS_ASSERT(!cbuf.dbuf && cstrlen < cbuf.sbufSize);
1244     return sb.appendInflated(cstr, cstrlen);
1245 }
1246
1247 bool
1248 ValueToNumberSlow(JSContext *cx, Value v, double *out)
1249 {
1250     JS_ASSERT(!v.isNumber());
1251     goto skip_int_double;
1252     for (;;) {
1253         if (v.isNumber()) {
1254             *out = v.toNumber();
1255             return true;
1256         }
1257       skip_int_double:
1258         if (v.isString())
1259             return StringToNumberType<jsdouble>(cx, v.toString(), out);
1260         if (v.isBoolean()) {
1261             if (v.toBoolean()) {
1262                 *out = 1.0;
1263                 return true;
1264             }
1265             *out = 0.0;
1266             return true;
1267         }
1268         if (v.isNull()) {
1269             *out = 0.0;
1270             return true;
1271         }
1272         if (v.isUndefined())
1273             break;
1274
1275         JS_ASSERT(v.isObject());
1276         if (!DefaultValue(cx, &v.toObject(), JSTYPE_NUMBER, &v))
1277             return false;
1278         if (v.isObject())
1279             break;
1280     }
1281
1282     *out = js_NaN;
1283     return true;
1284 }
1285
1286 bool
1287 ValueToECMAInt32Slow(JSContext *cx, const Value &v, int32_t *out)
1288 {
1289     JS_ASSERT(!v.isInt32());
1290     jsdouble d;
1291     if (v.isDouble()) {
1292         d = v.toDouble();
1293     } else {
1294         if (!ValueToNumberSlow(cx, v, &d))
1295             return false;
1296     }
1297     *out = js_DoubleToECMAInt32(d);
1298     return true;
1299 }
1300
1301 bool
1302 ValueToECMAUint32Slow(JSContext *cx, const Value &v, uint32_t *out)
1303 {
1304     JS_ASSERT(!v.isInt32());
1305     jsdouble d;
1306     if (v.isDouble()) {
1307         d = v.toDouble();
1308     } else {
1309         if (!ValueToNumberSlow(cx, v, &d))
1310             return false;
1311     }
1312     *out = js_DoubleToECMAUint32(d);
1313     return true;
1314 }
1315
1316 }  /* namespace js */
1317
1318 uint32
1319 js_DoubleToECMAUint32(jsdouble d)
1320 {
1321     int32 i;
1322     JSBool neg;
1323     jsdouble two32;
1324
1325     if (!JSDOUBLE_IS_FINITE(d))
1326         return 0;
1327
1328     /*
1329      * We check whether d fits int32, not uint32, as all but the ">>>" bit
1330      * manipulation bytecode stores the result as int, not uint. When the
1331      * result does not fit int Value, it will be stored as a negative double.
1332      */
1333     i = (int32) d;
1334     if ((jsdouble) i == d)
1335         return (int32)i;
1336
1337     neg = (d < 0);
1338     d = floor(neg ? -d : d);
1339     d = neg ? -d : d;
1340
1341     two32 = 4294967296.0;
1342     d = fmod(d, two32);
1343
1344     return (uint32) (d >= 0 ? d : d + two32);
1345 }
1346
1347 namespace js {
1348
1349 bool
1350 ValueToInt32Slow(JSContext *cx, const Value &v, int32_t *out)
1351 {
1352     JS_ASSERT(!v.isInt32());
1353     jsdouble d;
1354     if (v.isDouble()) {
1355         d = v.toDouble();
1356     } else if (!ValueToNumberSlow(cx, v, &d)) {
1357         return false;
1358     }
1359
1360     if (JSDOUBLE_IS_NaN(d) || d <= -2147483649.0 || 2147483648.0 <= d) {
1361         js_ReportValueError(cx, JSMSG_CANT_CONVERT,
1362                             JSDVG_SEARCH_STACK, v, NULL);
1363         return false;
1364     }
1365     *out = (int32) floor(d + 0.5);  /* Round to nearest */
1366     return true;
1367 }
1368
1369 bool
1370 ValueToUint16Slow(JSContext *cx, const Value &v, uint16_t *out)
1371 {
1372     JS_ASSERT(!v.isInt32());
1373     jsdouble d;
1374     if (v.isDouble()) {
1375         d = v.toDouble();
1376     } else if (!ValueToNumberSlow(cx, v, &d)) {
1377         return false;
1378     }
1379
1380     if (d == 0 || !JSDOUBLE_IS_FINITE(d)) {
1381         *out = 0;
1382         return true;
1383     }
1384
1385     uint16 u = (uint16) d;
1386     if ((jsdouble)u == d) {
1387         *out = u;
1388         return true;
1389     }
1390
1391     bool neg = (d < 0);
1392     d = floor(neg ? -d : d);
1393     d = neg ? -d : d;
1394     jsuint m = JS_BIT(16);
1395     d = fmod(d, (double) m);
1396     if (d < 0)
1397         d += m;
1398     *out = (uint16_t) d;
1399     return true;
1400 }
1401
1402 }  /* namespace js */
1403
1404 JSBool
1405 js_strtod(JSContext *cx, const jschar *s, const jschar *send,
1406           const jschar **ep, jsdouble *dp)
1407 {
1408     const jschar *s1;
1409     size_t length, i;
1410     char cbuf[32];
1411     char *cstr, *istr, *estr;
1412     JSBool negative;
1413     jsdouble d;
1414
1415     s1 = js_SkipWhiteSpace(s, send);
1416     length = send - s1;
1417
1418     /* Use cbuf to avoid malloc */
1419     if (length >= sizeof cbuf) {
1420         cstr = (char *) cx->malloc(length + 1);
1421         if (!cstr)
1422            return JS_FALSE;
1423     } else {
1424         cstr = cbuf;
1425     }
1426
1427     for (i = 0; i != length; i++) {
1428         if (s1[i] >> 8)
1429             break;
1430         cstr[i] = (char)s1[i];
1431     }
1432     cstr[i] = 0;
1433
1434     istr = cstr;
1435     if ((negative = (*istr == '-')) != 0 || *istr == '+')
1436         istr++;
1437     if (*istr == 'I' && !strncmp(istr, js_Infinity_str, sizeof js_Infinity_str - 1)) {
1438         d = negative ? js_NegativeInfinity : js_PositiveInfinity;
1439         estr = istr + 8;
1440     } else {
1441         int err;
1442         d = js_strtod_harder(JS_THREAD_DATA(cx)->dtoaState, cstr, &estr, &err);
1443         if (d == HUGE_VAL)
1444             d = js_PositiveInfinity;
1445         else if (d == -HUGE_VAL)
1446             d = js_NegativeInfinity;
1447     }
1448
1449     i = estr - cstr;
1450     if (cstr != cbuf)
1451         cx->free(cstr);
1452     *ep = i ? s1 + i : s;
1453     *dp = d;
1454     return JS_TRUE;
1455 }