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  *
26  * Alternatively, the contents of this file may be used under the terms of
27  * either of the GNU General Public License Version 2 or later (the "GPL"),
28  * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
29  * in which case the provisions of the GPL or the LGPL are applicable instead
30  * of those above. If you wish to allow use of your version of this file only
31  * under the terms of either the GPL or the LGPL, and not to allow others to
32  * use your version of this file under the terms of the MPL, indicate your
33  * decision by deleting the provisions above and replace them with the notice
34  * and other provisions required by the GPL or the LGPL. If you do not delete
35  * the provisions above, a recipient may use your version of this file under
36  * the terms of any one of the MPL, the GPL or the LGPL.
37  *
38  * ***** END LICENSE BLOCK ***** */
39
40 /*
41  * Portable double to alphanumeric string and back converters.
42  */
43 #include "jsstddef.h"
44 #include "jslibmath.h"
45 #include "jstypes.h"
46 #include "jsdtoa.h"
47 #include "jsprf.h"
48 #include "jsutil.h" /* Added by JSIFY */
49 #include "jspubtd.h"
50 #include "jsnum.h"
51
52 #ifdef JS_THREADSAFE
53 #include "prlock.h"
54 #endif
55
56 /****************************************************************
57  *
58  * The author of this software is David M. Gay.
59  *
60  * Copyright (c) 1991 by Lucent Technologies.
61  *
62  * Permission to use, copy, modify, and distribute this software for any
63  * purpose without fee is hereby granted, provided that this entire notice
64  * is included in all copies of any software which is or includes a copy
65  * or modification of this software and in all copies of the supporting
66  * documentation for such software.
67  *
68  * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
69  * WARRANTY.  IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
70  * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
71  * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
72  *
73  ***************************************************************/
74
75 /* Please send bug reports to
76     David M. Gay
77     Bell Laboratories, Room 2C-463
78     600 Mountain Avenue
79     Murray Hill, NJ 07974-0636
80     U.S.A.
81     dmg@bell-labs.com
82  */
83
84 /* On a machine with IEEE extended-precision registers, it is
85  * necessary to specify double-precision (53-bit) rounding precision
86  * before invoking strtod or dtoa.  If the machine uses (the equivalent
87  * of) Intel 80x87 arithmetic, the call
88  *  _control87(PC_53, MCW_PC);
89  * does this with many compilers.  Whether this or another call is
90  * appropriate depends on the compiler; for this to work, it may be
91  * necessary to #include "float.h" or another system-dependent header
92  * file.
93  */
94
95 /* strtod for IEEE-arithmetic machines.
96  *
97  * This strtod returns a nearest machine number to the input decimal
98  * string (or sets err to JS_DTOA_ERANGE or JS_DTOA_ENOMEM).  With IEEE
99  * arithmetic, ties are broken by the IEEE round-even rule.  Otherwise
100  * ties are broken by biased rounding (add half and chop).
101  *
102  * Inspired loosely by William D. Clinger's paper "How to Read Floating
103  * Point Numbers Accurately" [Proc. ACM SIGPLAN '90, pp. 92-101].
104  *
105  * Modifications:
106  *
107  *  1. We only require IEEE double-precision
108  *      arithmetic (not IEEE double-extended).
109  *  2. We get by with floating-point arithmetic in a case that
110  *      Clinger missed -- when we're computing d * 10^n
111  *      for a small integer d and the integer n is not too
112  *      much larger than 22 (the maximum integer k for which
113  *      we can represent 10^k exactly), we may be able to
114  *      compute (d*10^k) * 10^(e-k) with just one roundoff.
115  *  3. Rather than a bit-at-a-time adjustment of the binary
116  *      result in the hard case, we use floating-point
117  *      arithmetic to determine the adjustment to within
118  *      one bit; only in really hard cases do we need to
119  *      compute a second residual.
120  *  4. Because of 3., we don't need a large table of powers of 10
121  *      for ten-to-e (just some small tables, e.g. of 10^k
122  *      for 0 <= k <= 22).
123  */
124
125 /*
126  * #define IEEE_8087 for IEEE-arithmetic machines where the least
127  *  significant byte has the lowest address.
128  * #define IEEE_MC68k for IEEE-arithmetic machines where the most
129  *  significant byte has the lowest address.
130  * #define Long int on machines with 32-bit ints and 64-bit longs.
131  * #define Sudden_Underflow for IEEE-format machines without gradual
132  *  underflow (i.e., that flush to zero on underflow).
133  * #define No_leftright to omit left-right logic in fast floating-point
134  *  computation of js_dtoa.
135  * #define Check_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3.
136  * #define RND_PRODQUOT to use rnd_prod and rnd_quot (assembly routines
137  *  that use extended-precision instructions to compute rounded
138  *  products and quotients) with IBM.
139  * #define ROUND_BIASED for IEEE-format with biased rounding.
140  * #define Inaccurate_Divide for IEEE-format with correctly rounded
141  *  products but inaccurate quotients, e.g., for Intel i860.
142  * #define JS_HAVE_LONG_LONG on machines that have a "long long"
143  *  integer type (of >= 64 bits).  If long long is available and the name is
144  *  something other than "long long", #define Llong to be the name,
145  *  and if "unsigned Llong" does not work as an unsigned version of
146  *  Llong, #define #ULLong to be the corresponding unsigned type.
147  * #define Bad_float_h if your system lacks a float.h or if it does not
148  *  define some or all of DBL_DIG, DBL_MAX_10_EXP, DBL_MAX_EXP,
149  *  FLT_RADIX, FLT_ROUNDS, and DBL_MAX.
150  * #define MALLOC your_malloc, where your_malloc(n) acts like malloc(n)
151  *  if memory is available and otherwise does something you deem
152  *  appropriate.  If MALLOC is undefined, malloc will be invoked
153  *  directly -- and assumed always to succeed.
154  * #define Omit_Private_Memory to omit logic (added Jan. 1998) for making
155  *  memory allocations from a private pool of memory when possible.
156  *  When used, the private pool is PRIVATE_MEM bytes long: 2000 bytes,
157  *  unless #defined to be a different length.  This default length
158  *  suffices to get rid of MALLOC calls except for unusual cases,
159  *  such as decimal-to-binary conversion of a very long string of
160  *  digits.
161  * #define INFNAN_CHECK on IEEE systems to cause strtod to check for
162  *  Infinity and NaN (case insensitively).  On some systems (e.g.,
163  *  some HP systems), it may be necessary to #define NAN_WORD0
164  *  appropriately -- to the most significant word of a quiet NaN.
165  *  (On HP Series 700/800 machines, -DNAN_WORD0=0x7ff40000 works.)
166  * #define MULTIPLE_THREADS if the system offers preemptively scheduled
167  *  multiple threads.  In this case, you must provide (or suitably
168  *  #define) two locks, acquired by ACQUIRE_DTOA_LOCK() and released
169  *  by RELEASE_DTOA_LOCK().  (The second lock, accessed
170  *  in pow5mult, ensures lazy evaluation of only one copy of high
171  *  powers of 5; omitting this lock would introduce a small
172  *  probability of wasting memory, but would otherwise be harmless.)
173  *  You must also invoke freedtoa(s) to free the value s returned by
174  *  dtoa.  You may do so whether or not MULTIPLE_THREADS is #defined.
175  * #define NO_IEEE_Scale to disable new (Feb. 1997) logic in strtod that
176  *  avoids underflows on inputs whose result does not underflow.
177  */
178 #ifdef IS_LITTLE_ENDIAN
179 #define IEEE_8087
180 #else
181 #define IEEE_MC68k
182 #endif
183
184 #ifndef Long
185 #define Long int32
186 #endif
187
188 #ifndef ULong
189 #define ULong uint32
190 #endif
191
192 #define Bug(errorMessageString) JS_ASSERT(!errorMessageString)
193
194 #include "stdlib.h"
195 #include "string.h"
196
197 #ifdef MALLOC
198 extern void *MALLOC(size_t);
199 #else
200 #define MALLOC malloc
201 #endif
202
203 #define Omit_Private_Memory
204 /* Private memory currently doesn't work with JS_THREADSAFE */
205 #ifndef Omit_Private_Memory
206 #ifndef PRIVATE_MEM
207 #define PRIVATE_MEM 2000
208 #endif
209 #define PRIVATE_mem ((PRIVATE_MEM+sizeof(double)-1)/sizeof(double))
210 static double private_mem[PRIVATE_mem], *pmem_next = private_mem;
211 #endif
212
213 #ifdef Bad_float_h
214 #undef __STDC__
215
216 #define DBL_DIG 15
217 #define DBL_MAX_10_EXP 308
218 #define DBL_MAX_EXP 1024
219 #define FLT_RADIX 2
220 #define FLT_ROUNDS 1
221 #define DBL_MAX 1.7976931348623157e+308
222
223
224
225 #ifndef LONG_MAX
226 #define LONG_MAX 2147483647
227 #endif
228
229 #else /* ifndef Bad_float_h */
230 #include "float.h"
231 #endif /* Bad_float_h */
232
233 #ifndef __MATH_H__
234 #include "math.h"
235 #endif
236
237 #ifndef CONST
238 #define CONST const
239 #endif
240
241 #if defined(IEEE_8087) + defined(IEEE_MC68k) != 1
242 Exactly one of IEEE_8087 or IEEE_MC68k should be defined.
243 #endif
244
245 #define word0(x)        JSDOUBLE_HI32(x)
246 #define set_word0(x, y) JSDOUBLE_SET_HI32(x, y)
247 #define word1(x)        JSDOUBLE_LO32(x)
248 #define set_word1(x, y) JSDOUBLE_SET_LO32(x, y)
249
250 #define Storeinc(a,b,c) (*(a)++ = (b) << 16 | (c) & 0xffff)
251
252 /* #define P DBL_MANT_DIG */
253 /* Ten_pmax = floor(P*log(2)/log(5)) */
254 /* Bletch = (highest power of 2 < DBL_MAX_10_EXP) / 16 */
255 /* Quick_max = floor((P-1)*log(FLT_RADIX)/log(10) - 1) */
256 /* Int_max = floor(P*log(FLT_RADIX)/log(10) - 1) */
257
258 #define Exp_shift  20
259 #define Exp_shift1 20
260 #define Exp_msk1    0x100000
261 #define Exp_msk11   0x100000
262 #define Exp_mask  0x7ff00000
263 #define P 53
264 #define Bias 1023
265 #define Emin (-1022)
266 #define Exp_1  0x3ff00000
267 #define Exp_11 0x3ff00000
268 #define Ebits 11
269 #define Frac_mask  0xfffff
270 #define Frac_mask1 0xfffff
271 #define Ten_pmax 22
272 #define Bletch 0x10
273 #define Bndry_mask  0xfffff
274 #define Bndry_mask1 0xfffff
275 #define LSB 1
276 #define Sign_bit 0x80000000
277 #define Log2P 1
278 #define Tiny0 0
279 #define Tiny1 1
280 #define Quick_max 14
281 #define Int_max 14
282 #define Infinite(x) (word0(x) == 0x7ff00000) /* sufficient test for here */
283 #ifndef NO_IEEE_Scale
284 #define Avoid_Underflow
285 #endif
286
287
288
289 #ifdef RND_PRODQUOT
290 #define rounded_product(a,b) a = rnd_prod(a, b)
291 #define rounded_quotient(a,b) a = rnd_quot(a, b)
292 extern double rnd_prod(double, double), rnd_quot(double, double);
293 #else
294 #define rounded_product(a,b) a *= b
295 #define rounded_quotient(a,b) a /= b
296 #endif
297
298 #define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
299 #define Big1 0xffffffff
300
301 #ifndef JS_HAVE_LONG_LONG
302 #undef ULLong
303 #else   /* long long available */
304 #ifndef Llong
305 #define Llong JSInt64
306 #endif
307 #ifndef ULLong
308 #define ULLong JSUint64
309 #endif
310 #endif /* JS_HAVE_LONG_LONG */
311
312 #ifdef JS_THREADSAFE
313 #define MULTIPLE_THREADS
314 static PRLock *freelist_lock;
315 #define ACQUIRE_DTOA_LOCK()                                                   \
316     JS_BEGIN_MACRO                                                            \
317         if (!initialized)                                                     \
318             InitDtoa();                                                       \
319         PR_Lock(freelist_lock);                                               \
320     JS_END_MACRO
321 #define RELEASE_DTOA_LOCK() PR_Unlock(freelist_lock)
322 #else
323 #undef MULTIPLE_THREADS
324 #define ACQUIRE_DTOA_LOCK()   /*nothing*/
325 #define RELEASE_DTOA_LOCK()   /*nothing*/
326 #endif
327
328 #define Kmax 15
329
330 struct Bigint {
331     struct Bigint *next;  /* Free list link */
332     int32 k;              /* lg2(maxwds) */
333     int32 maxwds;         /* Number of words allocated for x */
334     int32 sign;           /* Zero if positive, 1 if negative.  Ignored by most Bigint routines! */
335     int32 wds;            /* Actual number of words.  If value is nonzero, the most significant word must be nonzero. */
336     ULong x[1];           /* wds words of number in little endian order */
337 };
338
339 #ifdef ENABLE_OOM_TESTING
340 /* Out-of-memory testing.  Use a good testcase (over and over) and then use
341  * these routines to cause a memory failure on every possible Balloc allocation,
342  * to make sure that all out-of-memory paths can be followed.  See bug 14044.
343  */
344
345 static int allocationNum;               /* which allocation is next? */
346 static int desiredFailure;              /* which allocation should fail? */
347
348 /**
349  * js_BigintTestingReset
350  *
351  * Call at the beginning of a test run to set the allocation failure position.
352  * (Set to 0 to just have the engine count allocations without failing.)
353  */
354 JS_PUBLIC_API(void)
355 js_BigintTestingReset(int newFailure)
356 {
357     allocationNum = 0;
358     desiredFailure = newFailure;
359 }
360
361 /**
362  * js_BigintTestingWhere
363  *
364  * Report the current allocation position.  This is really only useful when you
365  * want to learn how many allocations a test run has.
366  */
367 JS_PUBLIC_API(int)
368 js_BigintTestingWhere()
369 {
370     return allocationNum;
371 }
372
373
374 /*
375  * So here's what you do: Set up a fantastic test case that exercises the
376  * elements of the code you wish.  Set the failure point at 0 and run the test,
377  * then get the allocation position.  This number is the number of allocations
378  * your test makes.  Now loop from 1 to that number, setting the failure point
379  * at each loop count, and run the test over and over, causing failures at each
380  * step.  Any memory failure *should* cause a Out-Of-Memory exception; if it
381  * doesn't, then there's still an error here.
382  */
383 #endif
384
385 typedef struct Bigint Bigint;
386
387 static Bigint *freelist[Kmax+1];
388
389 /*
390  * Allocate a Bigint with 2^k words.
391  * This is not threadsafe. The caller must use thread locks
392  */
393 static Bigint *Balloc(int32 k)
394 0 {
395 0     int32 x;
396 0     Bigint *rv;
397 #ifndef Omit_Private_Memory
398     uint32 len;
399 #endif
400
401 #ifdef ENABLE_OOM_TESTING
402     if (++allocationNum == desiredFailure) {
403         printf("Forced Failing Allocation number %d\n", allocationNum);
404         return NULL;
405     }
406 #endif
407
408 0     if ((rv = freelist[k]) != NULL)
409 0         freelist[k] = rv->next;
410 0     if (rv == NULL) {
411 0         x = 1 << k;
412 #ifdef Omit_Private_Memory
413 0         rv = (Bigint *)MALLOC(sizeof(Bigint) + (x-1)*sizeof(ULong));
414 #else
415         len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)
416             /sizeof(double);
417         if (pmem_next - private_mem + len <= PRIVATE_mem) {
418             rv = (Bigint*)pmem_next;
419             pmem_next += len;
420             }
421         else
422             rv = (Bigint*)MALLOC(len*sizeof(double));
423 #endif
424 0         if (!rv)
425 0             return NULL;
426 0         rv->k = k;
427 0         rv->maxwds = x;
428     }
429 0     rv->sign = rv->wds = 0;
430 0     return rv;
431 }
432
433 static void Bfree(Bigint *v)
434 0 {
435 0     if (v) {
436 0         v->next = freelist[v->k];
437 0         freelist[v->k] = v;
438     }
439 }
440
441 #define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign, \
442                           y->wds*sizeof(Long) + 2*sizeof(int32))
443
444 /* Return b*m + a.  Deallocate the old b.  Both a and m must be between 0 and
445  * 65535 inclusive.  NOTE: old b is deallocated on memory failure.
446  */
447 static Bigint *multadd(Bigint *b, int32 m, int32 a)
448 0 {
449 0     int32 i, wds;
450 #ifdef ULLong
451 0     ULong *x;
452 0     ULLong carry, y;
453 #else
454     ULong carry, *x, y;
455     ULong xi, z;
456 #endif
457 0     Bigint *b1;
458
459 #ifdef ENABLE_OOM_TESTING
460     if (++allocationNum == desiredFailure) {
461         /* Faux allocation, because I'm not getting all of the failure paths
462          * without it.
463          */
464         printf("Forced Failing Allocation number %d\n", allocationNum);
465         Bfree(b);
466         return NULL;
467     }
468 #endif
469
470 0     wds = b->wds;
471 0     x = b->x;
472 0     i = 0;
473 0     carry = a;
474 0     do {
475 #ifdef ULLong
476 0         y = *x * (ULLong)m + carry;
477 0         carry = y >> 32;
478 0         *x++ = (ULong)(y & 0xffffffffUL);
479 #else
480         xi = *x;
481         y = (xi & 0xffff) * m + carry;
482         z = (xi >> 16) * m + (y >> 16);
483         carry = z >> 16;
484         *x++ = (z << 16) + (y & 0xffff);
485 #endif
486 0     }
487     while(++i < wds);
488 0     if (carry) {
489 0         if (wds >= b->maxwds) {
490 0             b1 = Balloc(b->k+1);
491 0             if (!b1) {
492 0                 Bfree(b);
493 0                 return NULL;
494             }
495 0             Bcopy(b1, b);
496 0             Bfree(b);
497 0             b = b1;
498         }
499 0         b->x[wds++] = (ULong)carry;
500 0         b->wds = wds;
501     }
502 0     return b;
503 }
504
505 static Bigint *s2b(CONST char *s, int32 nd0, int32 nd, ULong y9)
506 0 {
507 0     Bigint *b;
508 0     int32 i, k;
509 0     Long x, y;
510
511 0     x = (nd + 8) / 9;
512 0     for(k = 0, y = 1; x > y; y <<= 1, k++) ;
513 0     b = Balloc(k);
514 0     if (!b)
515 0         return NULL;
516 0     b->x[0] = y9;
517 0     b->wds = 1;
518
519 0     i = 9;
520 0     if (9 < nd0) {
521 0         s += 9;
522 0         do {
523 0             b = multadd(b, 10, *s++ - '0');
524 0             if (!b)
525 0                 return NULL;
526 0         } while(++i < nd0);
527 0         s++;
528     }
529     else
530 0         s += 10;
531 0     for(; i < nd; i++) {
532 0         b = multadd(b, 10, *s++ - '0');
533 0         if (!b)
534 0             return NULL;
535     }
536 0     return b;
537 }
538
539
540 /* Return the number (0 through 32) of most significant zero bits in x. */
541 static int32 hi0bits(register ULong x)
542 0 {
543 0     register int32 k = 0;
544
545 0     if (!(x & 0xffff0000)) {
546 0         k = 16;
547 0         x <<= 16;
548     }
549 0     if (!(x & 0xff000000)) {
550 0         k += 8;
551 0         x <<= 8;
552     }
553 0     if (!(x & 0xf0000000)) {
554 0         k += 4;
555 0         x <<= 4;
556     }
557 0     if (!(x & 0xc0000000)) {
558 0         k += 2;
559 0         x <<= 2;
560     }
561 0     if (!(x & 0x80000000)) {
562 0         k++;
563 0         if (!(x & 0x40000000))
564 0             return 32;
565     }
566 0     return k;
567 }
568
569
570 /* Return the number (0 through 32) of least significant zero bits in y.
571  * Also shift y to the right past these 0 through 32 zeros so that y's
572  * least significant bit will be set unless y was originally zero. */
573 static int32 lo0bits(ULong *y)
574 0 {
575 0     register int32 k;
576 0     register ULong x = *y;
577
578 0     if (x & 7) {
579 0         if (x & 1)
580 0             return 0;
581 0         if (x & 2) {
582 0             *y = x >> 1;
583 0             return 1;
584         }
585 0         *y = x >> 2;
586 0         return 2;
587     }
588 0     k = 0;
589 0     if (!(x & 0xffff)) {
590 0         k = 16;
591 0         x >>= 16;
592     }
593 0     if (!(x & 0xff)) {
594 0         k += 8;
595 0         x >>= 8;
596     }
597 0     if (!(x & 0xf)) {
598 0         k += 4;
599 0         x >>= 4;
600     }
601 0     if (!(x & 0x3)) {
602 0         k += 2;
603 0         x >>= 2;
604     }
605 0     if (!(x & 1)) {
606 0         k++;
607 0         x >>= 1;
608 0         if (!x & 1)
609 0             return 32;
610     }
611 0     *y = x;
612 0     return k;
613 }
614
615 /* Return a new Bigint with the given integer value, which must be nonnegative. */
616 static Bigint *i2b(int32 i)
617 0 {
618 0     Bigint *b;
619
620 0     b = Balloc(1);
621 0     if (!b)
622 0         return NULL;
623 0     b->x[0] = i;
624 0     b->wds = 1;
625 0     return b;
626 }
627
628 /* Return a newly allocated product of a and b. */
629 static Bigint *mult(CONST Bigint *a, CONST Bigint *b)
630 0 {
631 0     CONST Bigint *t;
632 0     Bigint *c;
633 0     int32 k, wa, wb, wc;
634 0     ULong y;
635 0     ULong *xc, *xc0, *xce;
636 0     CONST ULong *x, *xa, *xae, *xb, *xbe;
637 #ifdef ULLong
638 0     ULLong carry, z;
639 #else
640     ULong carry, z;
641     ULong z2;
642 #endif
643
644 0     if (a->wds < b->wds) {
645 0         t = a;
646 0         a = b;
647 0         b = t;
648     }
649 0     k = a->k;
650 0     wa = a->wds;
651 0     wb = b->wds;
652 0     wc = wa + wb;
653 0     if (wc > a->maxwds)
654 0         k++;
655 0     c = Balloc(k);
656 0     if (!c)
657 0         return NULL;
658 0     for(xc = c->x, xce = xc + wc; xc < xce; xc++)
659 0         *xc = 0;
660 0     xa = a->x;
661 0     xae = xa + wa;
662 0     xb = b->x;
663 0     xbe = xb + wb;
664 0     xc0 = c->x;
665 #ifdef ULLong
666 0     for(; xb < xbe; xc0++) {
667 0         if ((y = *xb++) != 0) {
668 0             x = xa;
669 0             xc = xc0;
670 0             carry = 0;
671 0             do {
672 0                 z = *x++ * (ULLong)y + *xc + carry;
673 0                 carry = z >> 32;
674 0                 *xc++ = (ULong)(z & 0xffffffffUL);
675 0                 }
676                 while(x < xae);
677 0             *xc = (ULong)carry;
678             }
679         }
680 #else
681     for(; xb < xbe; xb++, xc0++) {
682         if ((y = *xb & 0xffff) != 0) {
683             x = xa;
684             xc = xc0;
685             carry = 0;
686             do {
687                 z = (*x & 0xffff) * y + (*xc & 0xffff) + carry;
688                 carry = z >> 16;
689                 z2 = (*x++ >> 16) * y + (*xc >> 16) + carry;
690                 carry = z2 >> 16;
691                 Storeinc(xc, z2, z);
692             }
693             while(x < xae);
694             *xc = carry;
695         }
696         if ((y = *xb >> 16) != 0) {
697             x = xa;
698             xc = xc0;
699             carry = 0;
700             z2 = *xc;
701             do {
702                 z = (*x & 0xffff) * y + (*xc >> 16) + carry;
703                 carry = z >> 16;
704                 Storeinc(xc, z, z2);
705                 z2 = (*x++ >> 16) * y + (*xc & 0xffff) + carry;
706                 carry = z2 >> 16;
707             }
708             while(x < xae);
709             *xc = z2;
710         }
711     }
712 #endif
713 0     for(xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ;
714 0     c->wds = wc;
715 0     return c;
716 }
717
718 /*
719  * 'p5s' points to a linked list of Bigints that are powers of 5.
720  * This list grows on demand, and it can only grow: it won't change
721  * in any other way.  So if we read 'p5s' or the 'next' field of
722  * some Bigint on the list, and it is not NULL, we know it won't
723  * change to NULL or some other value.  Only when the value of
724  * 'p5s' or 'next' is NULL do we need to acquire the lock and add
725  * a new Bigint to the list.
726  */
727
728 static Bigint *p5s;
729
730 #ifdef JS_THREADSAFE
731 static PRLock *p5s_lock;
732 #endif
733
734 /* Return b * 5^k.  Deallocate the old b.  k must be nonnegative. */
735 /* NOTE: old b is deallocated on memory failure. */
736 static Bigint *pow5mult(Bigint *b, int32 k)
737 0 {
738 0     Bigint *b1, *p5, *p51;
739 0     int32 i;
740 0     static CONST int32 p05[3] = { 5, 25, 125 };
741
742 0     if ((i = k & 3) != 0) {
743 0         b = multadd(b, p05[i-1], 0);
744 0         if (!b)
745 0             return NULL;
746     }
747
748 0     if (!(k >>= 2))
749 0         return b;
750 0     if (!(p5 = p5s)) {
751 #ifdef JS_THREADSAFE
752         /*
753          * We take great care to not call i2b() and Bfree()
754          * while holding the lock.
755          */
756         Bigint *wasted_effort = NULL;
757         p5 = i2b(625);
758         if (!p5) {
759             Bfree(b);
760             return NULL;
761         }
762         /* lock and check again */
763         PR_Lock(p5s_lock);
764         if (!p5s) {
765             /* first time */
766             p5s = p5;
767             p5->next = 0;
768         } else {
769             /* some other thread just beat us */
770             wasted_effort = p5;
771             p5 = p5s;
772         }
773         PR_Unlock(p5s_lock);
774         if (wasted_effort) {
775             Bfree(wasted_effort);
776         }
777 #else
778         /* first time */
779 0         p5 = p5s = i2b(625);
780 0         if (!p5) {
781 0             Bfree(b);
782 0             return NULL;
783         }
784 0         p5->next = 0;
785 #endif
786     }
787 0     for(;;) {
788 0         if (k & 1) {
789 0             b1 = mult(b, p5);
790 0             Bfree(b);
791 0             if (!b1)
792 0                 return NULL;
793 0             b = b1;
794         }
795 0         if (!(k >>= 1))
796 0             break;
797 0         if (!(p51 = p5->next)) {
798 #ifdef JS_THREADSAFE
799             Bigint *wasted_effort = NULL;
800             p51 = mult(p5, p5);
801             if (!p51) {
802                 Bfree(b);
803                 return NULL;
804             }
805             PR_Lock(p5s_lock);
806             if (!p5->next) {
807                 p5->next = p51;
808                 p51->next = 0;
809             } else {
810                 wasted_effort = p51;
811                 p51 = p5->next;
812             }
813             PR_Unlock(p5s_lock);
814             if (wasted_effort) {
815                 Bfree(wasted_effort);
816             }
817 #else
818 0             p51 = mult(p5,p5);
819 0             if (!p51) {
820 0                 Bfree(b);
821 0                 return NULL;
822             }
823 0             p51->next = 0;
824 0             p5->next = p51;
825 #endif
826         }
827 0         p5 = p51;
828     }
829 0     return b;
830 }
831
832 /* Return b * 2^k.  Deallocate the old b.  k must be nonnegative.
833  * NOTE: on memory failure, old b is deallocated. */
834 static Bigint *lshift(Bigint *b, int32 k)
835 0 {
836 0     int32 i, k1, n, n1;
837 0     Bigint *b1;
838 0     ULong *x, *x1, *xe, z;
839
840 0     n = k >> 5;
841 0     k1 = b->k;
842 0     n1 = n + b->wds + 1;
843 0     for(i = b->maxwds; n1 > i; i <<= 1)
844 0         k1++;
845 0     b1 = Balloc(k1);
846 0     if (!b1)
847 0         goto done;
848 0     x1 = b1->x;
849 0     for(i = 0; i < n; i++)
850 0         *x1++ = 0;
851 0     x = b->x;
852 0     xe = x + b->wds;
853 0     if (k &= 0x1f) {
854 0         k1 = 32 - k;
855 0         z = 0;
856 0         do {
857 0             *x1++ = *x << k | z;
858 0             z = *x++ >> k1;
859 0         }
860         while(x < xe);
861 0         if ((*x1 = z) != 0)
862 0             ++n1;
863     }
864 0     else do
865 0         *x1++ = *x++;
866          while(x < xe);
867 0     b1->wds = n1 - 1;
868 done:
869 0     Bfree(b);
870 0     return b1;
871 }
872
873 /* Return -1, 0, or 1 depending on whether a<b, a==b, or a>b, respectively. */
874 static int32 cmp(Bigint *a, Bigint *b)
875 0 {
876 0     ULong *xa, *xa0, *xb, *xb0;
877 0     int32 i, j;
878
879 0     i = a->wds;
880 0     j = b->wds;
881 #ifdef DEBUG
882     if (i > 1 && !a->x[i-1])
883         Bug("cmp called with a->x[a->wds-1] == 0");
884     if (j > 1 && !b->x[j-1])
885         Bug("cmp called with b->x[b->wds-1] == 0");
886 #endif
887 0     if (i -= j)
888 0         return i;
889 0     xa0 = a->x;
890 0     xa = xa0 + j;
891 0     xb0 = b->x;
892 0     xb = xb0 + j;
893 0     for(;;) {
894 0         if (*--xa != *--xb)
895 0             return *xa < *xb ? -1 : 1;
896 0         if (xa <= xa0)
897 0             break;
898     }
899 0     return 0;
900 }
901
902 static Bigint *diff(Bigint *a, Bigint *b)
903 0 {
904 0     Bigint *c;
905 0     int32 i, wa, wb;
906 0     ULong *xa, *xae, *xb, *xbe, *xc;
907 #ifdef ULLong
908 0     ULLong borrow, y;
909 #else
910     ULong borrow, y;
911     ULong z;
912 #endif
913
914 0     i = cmp(a,b);
915 0     if (!i) {
916 0         c = Balloc(0);
917 0         if (!c)
918 0             return NULL;
919 0         c->wds = 1;
920 0         c->x[0] = 0;
921 0         return c;
922     }
923 0     if (i < 0) {
924 0         c = a;
925 0         a = b;
926 0         b = c;
927 0         i = 1;
928     }
929     else
930 0         i = 0;
931 0     c = Balloc(a->k);
932 0     if (!c)
933 0         return NULL;
934 0     c->sign = i;
935 0     wa = a->wds;
936 0     xa = a->x;
937 0     xae = xa + wa;
938 0     wb = b->wds;
939 0     xb = b->x;
940 0     xbe = xb + wb;
941 0     xc = c->x;
942 0     borrow = 0;
943 #ifdef ULLong
944 0     do {
945 0         y = (ULLong)*xa++ - *xb++ - borrow;
946 0         borrow = y >> 32 & 1UL;
947 0         *xc++ = (ULong)(y & 0xffffffffUL);
948 0         }
949         while(xb < xbe);
950 0     while(xa < xae) {
951 0         y = *xa++ - borrow;
952 0         borrow = y >> 32 & 1UL;
953 0         *xc++ = (ULong)(y & 0xffffffffUL);
954         }
955 #else
956     do {
957         y = (*xa & 0xffff) - (*xb & 0xffff) - borrow;
958         borrow = (y & 0x10000) >> 16;
959         z = (*xa++ >> 16) - (*xb++ >> 16) - borrow;
960         borrow = (z & 0x10000) >> 16;
961         Storeinc(xc, z, y);
962         }
963         while(xb < xbe);
964     while(xa < xae) {
965         y = (*xa & 0xffff) - borrow;
966         borrow = (y & 0x10000) >> 16;
967         z = (*xa++ >> 16) - borrow;
968         borrow = (z & 0x10000) >> 16;
969         Storeinc(xc, z, y);
970         }
971 #endif
972 0     while(!*--xc)
973 0         wa--;
974 0     c->wds = wa;
975 0     return c;
976 }
977
978 /* Return the absolute difference between x and the adjacent greater-magnitude double number (ignoring exponent overflows). */
979 static double ulp(double x)
980 0 {
981 0     register Long L;
982 0     double a = 0;
983
984 0     L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1;
985 #ifndef Sudden_Underflow
986 0     if (L > 0) {
987 #endif
988 0         set_word0(a, L);
989 0         set_word1(a, 0);
990 #ifndef Sudden_Underflow
991     }
992     else {
993 0         L = -L >> Exp_shift;
994 0         if (L < Exp_shift) {
995 0             set_word0(a, 0x80000 >> L);
996 0             set_word1(a, 0);
997         }
998         else {
999 0             set_word0(a, 0);
1000 0             L -= Exp_shift;
1001 0             set_word1(a, L >= 31 ? 1 : 1 << (31 - L));
1002         }
1003     }
1004 #endif
1005 0     return a;
1006 }
1007
1008
1009 static double b2d(Bigint *a, int32 *e)
1010 0 {
1011 0     ULong *xa, *xa0, w, y, z;
1012 0     int32 k;
1013 0     double d = 0;
1014 #define d0 word0(d)
1015 #define d1 word1(d)
1016 #define set_d0(x) set_word0(d, x)
1017 #define set_d1(x) set_word1(d, x)
1018
1019 0     xa0 = a->x;
1020 0     xa = xa0 + a->wds;
1021 0     y = *--xa;
1022 #ifdef DEBUG
1023     if (!y) Bug("zero y in b2d");
1024 #endif
1025 0     k = hi0bits(y);
1026 0     *e = 32 - k;
1027 0     if (k < Ebits) {
1028 0         set_d0(Exp_1 | y >> (Ebits - k));
1029 0         w = xa > xa0 ? *--xa : 0;
1030 0         set_d1(y << (32-Ebits + k) | w >> (Ebits - k));
1031 0         goto ret_d;
1032     }
1033 0     z = xa > xa0 ? *--xa : 0;
1034 0     if (k -= Ebits) {
1035 0         set_d0(Exp_1 | y << k | z >> (32 - k));
1036 0         y = xa > xa0 ? *--xa : 0;
1037 0         set_d1(z << k | y >> (32 - k));
1038     }
1039     else {
1040 0         set_d0(Exp_1 | y);
1041 0         set_d1(z);
1042     }
1043   ret_d:
1044 #undef d0
1045 #undef d1
1046 #undef set_d0
1047 #undef set_d1
1048 0     return d;
1049 }
1050
1051
1052 /* Convert d into the form b*2^e, where b is an odd integer.  b is the returned
1053  * Bigint and e is the returned binary exponent.  Return the number of significant
1054  * bits in b in bits.  d must be finite and nonzero. */
1055 static Bigint *d2b(double d, int32 *e, int32 *bits)
1056 0 {
1057 0     Bigint *b;
1058 0     int32 de, i, k;
1059 0     ULong *x, y, z;
1060 #define d0 word0(d)
1061 #define d1 word1(d)
1062 #define set_d0(x) set_word0(d, x)
1063 #define set_d1(x) set_word1(d, x)
1064
1065 0     b = Balloc(1);
1066 0     if (!b)
1067 0         return NULL;
1068 0     x = b->x;
1069
1070 0     z = d0 & Frac_mask;
1071 0     set_d0(d0 & 0x7fffffff);  /* clear sign bit, which we ignore */
1072 #ifdef Sudden_Underflow
1073     de = (int32)(d0 >> Exp_shift);
1074     z |= Exp_msk11;
1075 #else
1076 0     if ((de = (int32)(d0 >> Exp_shift)) != 0)
1077 0         z |= Exp_msk1;
1078 #endif
1079 0     if ((y = d1) != 0) {
1080 0         if ((k = lo0bits(&y)) != 0) {
1081 0             x[0] = y | z << (32 - k);
1082 0             z >>= k;
1083         }
1084         else
1085 0             x[0] = y;
1086 0         i = b->wds = (x[1] = z) ? 2 : 1;
1087     }
1088     else {
1089 0         JS_ASSERT(z);
1090 0         k = lo0bits(&z);
1091 0         x[0] = z;
1092 0         i = b->wds = 1;
1093 0         k += 32;
1094     }
1095 #ifndef Sudden_Underflow
1096 0     if (de) {
1097 #endif
1098 0         *e = de - Bias - (P-1) + k;
1099 0         *bits = P - k;
1100 #ifndef Sudden_Underflow
1101     }
1102     else {
1103 0         *e = de - Bias - (P-1) + 1 + k;
1104 0         *bits = 32*i - hi0bits(x[i-1]);
1105     }
1106 #endif
1107 0     return b;
1108 }
1109 #undef d0
1110 #undef d1
1111 #undef set_d0
1112 #undef set_d1
1113
1114
1115 static double ratio(Bigint *a, Bigint *b)
1116 0 {
1117 0     double da, db;
1118 0     int32 k, ka, kb;
1119
1120 0     da = b2d(a, &ka);
1121 0     db = b2d(b, &kb);
1122 0     k = ka - kb + 32*(a->wds - b->wds);
1123 0     if (k > 0)
1124 0         set_word0(da, word0(da) + k*Exp_msk1);
1125     else {
1126 0         k = -k;
1127 0         set_word0(db, word0(db) + k*Exp_msk1);
1128     }
1129 0     return da / db;
1130 }
1131
1132 static CONST double
1133 tens[] = {
1134     1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
1135     1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
1136     1e20, 1e21, 1e22
1137 };
1138
1139 static CONST double bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 };
1140 static CONST double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128,
1141 #ifdef Avoid_Underflow
1142         9007199254740992.e-256
1143 #else
1144         1e-256
1145 #endif
1146         };
1147 /* The factor of 2^53 in tinytens[4] helps us avoid setting the underflow */
1148 /* flag unnecessarily.  It leads to a song and dance at the end of strtod. */
1149 #define Scale_Bit 0x10
1150 #define n_bigtens 5
1151
1152
1153 #ifdef INFNAN_CHECK
1154
1155 #ifndef NAN_WORD0
1156 #define NAN_WORD0 0x7ff80000
1157 #endif
1158
1159 #ifndef NAN_WORD1
1160 #define NAN_WORD1 0
1161 #endif
1162
1163 static int match(CONST char **sp, char *t)
1164 {
1165     int c, d;
1166     CONST char *s = *sp;
1167
1168     while(d = *t++) {
1169         if ((c = *++s) >= 'A' && c <= 'Z')
1170             c += 'a' - 'A';
1171         if (c != d)
1172             return 0;
1173         }
1174     *sp = s + 1;
1175     return 1;
1176     }
1177 #endif /* INFNAN_CHECK */
1178
1179
1180 #ifdef JS_THREADSAFE
1181 static JSBool initialized = JS_FALSE;
1182
1183 /* hacked replica of nspr _PR_InitDtoa */
1184 static void InitDtoa(void)
1185 {
1186     freelist_lock = PR_NewLock();
1187         p5s_lock = PR_NewLock();
1188     initialized = JS_TRUE;
1189 }
1190 #endif
1191
1192 void js_FinishDtoa(void)
1193 0 {
1194 0     int count;
1195 0     Bigint *temp;
1196
1197 #ifdef JS_THREADSAFE
1198     if (initialized == JS_TRUE) {
1199         PR_DestroyLock(freelist_lock);
1200         PR_DestroyLock(p5s_lock);
1201         initialized = JS_FALSE;
1202     }
1203 #endif
1204
1205     /* clear down the freelist array and p5s */
1206
1207     /* static Bigint *freelist[Kmax+1]; */
1208 0     for (count = 0; count <= Kmax; count++) {
1209 0         Bigint **listp = &freelist[count];
1210 0         while ((temp = *listp) != NULL) {
1211 0             *listp = temp->next;
1212 0             free(temp);
1213         }
1214 0         freelist[count] = NULL;
1215     }
1216
1217     /* static Bigint *p5s; */
1218 0     while (p5s) {
1219 0         temp = p5s;
1220 0         p5s = p5s->next;
1221 0         free(temp);
1222     }
1223 }
1224
1225 /* nspr2 watcom bug ifdef omitted */
1226
1227 JS_FRIEND_API(double)
1228 JS_strtod(CONST char *s00, char **se, int *err)
1229 16401 {
1230 16401     int32 scale;
1231 16401     int32 bb2, bb5, bbe, bd2, bd5, bbbits, bs2, c, dsign,
1232 16401         e, e1, esign, i, j, k, nd, nd0, nf, nz, nz0, sign;
1233 16401     CONST char *s, *s0, *s1;
1234 16401     double aadj, aadj1, adj, rv, rv0;
1235 16401     Long L;
1236 16401     ULong y, z;
1237 16401     Bigint *bb, *bb1, *bd, *bd0, *bs, *delta;
1238
1239 16401     *err = 0;
1240
1241 16401     bb = bd = bs = delta = NULL;
1242 16401     sign = nz0 = nz = 0;
1243 16401     rv = 0.;
1244
1245     /* Locking for Balloc's shared buffers that will be used in this block */
1246     ACQUIRE_DTOA_LOCK();
1247
1248 16401     for(s = s00;;s++) switch(*s) {
1249     case '-':
1250 0         sign = 1;
1251         /* no break */
1252     case '+':
1253 0         if (*++s)
1254 0             goto break2;
1255         /* no break */
1256     case 0:
1257 0         s = s00;
1258 0         goto ret;
1259     case '\t':
1260     case '\n':
1261     case '\v':
1262     case '\f':
1263     case '\r':
1264     case ' ':
1265 0         continue;
1266     default:
1267 0         goto break2;
1268     }
1269 break2:
1270
1271 16401     if (*s == '0') {
1272 7006         nz0 = 1;
1273 7006         while(*++s == '0') ;
1274 7006         if (!*s)
1275 7006             goto ret;
1276     }
1277 9395     s0 = s;
1278 9395     y = z = 0;
1279 18705     for(nd = nf = 0; (c = *s) >= '0' && c <= '9'; nd++, s++)
1280 9310         if (nd < 9)
1281 9310             y = 10*y + c - '0';
1282 0         else if (nd < 16)
1283 0             z = 10*z + c - '0';
1284 9395     nd0 = nd;
1285 9395     if (c == '.') {
1286 0         c = *++s;
1287 0         if (!nd) {
1288 0             for(; c == '0'; c = *++s)
1289 0                 nz++;
1290 0             if (c > '0' && c <= '9') {
1291 0                 s0 = s;
1292 0                 nf += nz;
1293 0                 nz = 0;
1294 0                 goto have_dig;
1295             }
1296 0             goto dig_done;
1297         }
1298 0         for(; c >= '0' && c <= '9'; c = *++s) {
1299         have_dig:
1300 0             nz++;
1301 0             if (c -= '0') {
1302 0                 nf += nz;
1303 0                 for(i = 1; i < nz; i++)
1304 0                     if (nd++ < 9)
1305 0                         y *= 10;
1306 0                     else if (nd <= DBL_DIG + 1)
1307 0                         z *= 10;
1308 0                 if (nd++ < 9)
1309 0                     y = 10*y + c;
1310 0                 else if (nd <= DBL_DIG + 1)
1311 0                     z = 10*z + c;
1312 0                 nz = 0;
1313             }
1314         }
1315     }
1316 dig_done:
1317 9395     e = 0;
1318 9395     if (c == 'e' || c == 'E') {
1319 0         if (!nd && !nz && !nz0) {
1320 0             s = s00;
1321 0             goto ret;
1322         }
1323 0         s00 = s;
1324 0         esign = 0;
1325 0         switch(c = *++s) {
1326         case '-':
1327 0             esign = 1;
1328         case '+':
1329 0             c = *++s;
1330         }
1331 0         if (c >= '0' && c <= '9') {
1332 0             while(c == '0')
1333 0                 c = *++s;
1334 0             if (c > '0' && c <= '9') {
1335 0                 L = c - '0';
1336 0                 s1 = s;
1337 0                 while((c = *++s) >= '0' && c <= '9')
1338 0                     L = 10*L + c - '0';
1339 0                 if (s - s1 > 8 || L > 19999)
1340                     /* Avoid confusion from exponents
1341                      * so large that e might overflow.
1342                      */
1343 0                     e = 19999; /* safe for 16 bit ints */
1344                 else
1345 0                     e = (int32)L;
1346 0                 if (esign)
1347 0                     e = -e;
1348             }
1349             else
1350 0                 e = 0;
1351         }
1352         else
1353 0             s = s00;
1354     }
1355 9395     if (!nd) {
1356 85         if (!nz && !nz0) {
1357 #ifdef INFNAN_CHECK
1358             /* Check for Nan and Infinity */
1359             switch(c) {
1360               case 'i':
1361               case 'I':
1362                 if (match(&s,"nfinity")) {
1363                     word0(rv) = 0x7ff00000;
1364                     word1(rv) = 0;
1365                     goto ret;
1366                     }
1367                 break;
1368               case 'n':
1369               case 'N':
1370                 if (match(&s, "an")) {
1371                     word0(rv) = NAN_WORD0;
1372                     word1(rv) = NAN_WORD1;
1373                     goto ret;
1374                     }
1375               }
1376 #endif /* INFNAN_CHECK */
1377 85             s = s00;
1378             }
1379 85         goto ret;
1380     }
1381 9310     e1 = e -= nf;
1382
1383     /* Now we have nd0 digits, starting at s0, followed by a
1384      * decimal point, followed by nd-nd0 digits.  The number we're
1385      * after is the integer represented by those digits times
1386      * 10**e */
1387
1388 9310     if (!nd0)
1389 0         nd0 = nd;
1390 9310     k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;
1391 9310     rv = y;
1392 9310     if (k > 9)
1393 0         rv = tens[k - 9] * rv + z;
1394 9310     bd0 = 0;
1395 9310     if (nd <= DBL_DIG
1396 #ifndef RND_PRODQUOT
1397         && FLT_ROUNDS == 1
1398 #endif
1399         ) {
1400 9310         if (!e)
1401 9310             goto ret;
1402 0         if (e > 0) {
1403 0             if (e <= Ten_pmax) {
1404 0                 /* rv = */ rounded_product(rv, tens[e]);
1405 0                 goto ret;
1406             }
1407 0             i = DBL_DIG - nd;
1408 0             if (e <= Ten_pmax + i) {
1409                 /* A fancier test would sometimes let us do
1410                  * this for larger i values.
1411                  */
1412 0                 e -= i;
1413 0                 rv *= tens[i];
1414 0                 /* rv = */ rounded_product(rv, tens[e]);
1415 0                 goto ret;
1416             }
1417         }
1418 #ifndef Inaccurate_Divide
1419 0         else if (e >= -Ten_pmax) {
1420 0             /* rv = */ rounded_quotient(rv, tens[-e]);
1421 0             goto ret;
1422         }
1423 #endif
1424     }
1425 0     e1 += nd - k;
1426
1427 0     scale = 0;
1428
1429     /* Get starting approximation = rv * 10**e1 */
1430
1431 0     if (e1 > 0) {
1432 0         if ((i = e1 & 15) != 0)
1433 0             rv *= tens[i];
1434 0         if (e1 &= ~15) {
1435 0             if (e1 > DBL_MAX_10_EXP) {
1436             ovfl:
1437 0                 *err = JS_DTOA_ERANGE;
1438 #ifdef __STDC__
1439 0                 rv = HUGE_VAL;
1440 #else
1441                 /* Can't trust HUGE_VAL */
1442                 word0(rv) = Exp_mask;
1443                 word1(rv) = 0;
1444 #endif
1445 0                 if (bd0)
1446 0                     goto retfree;
1447 0                 goto ret;
1448             }
1449 0             e1 >>= 4;
1450 0             for(j = 0; e1 > 1; j++, e1 >>= 1)
1451 0                 if (e1 & 1)
1452 0                     rv *= bigtens[j];
1453             /* The last multiplication could overflow. */
1454 0             set_word0(rv, word0(rv) - P*Exp_msk1);
1455 0             rv *= bigtens[j];
1456 0             if ((z = word0(rv) & Exp_mask) > Exp_msk1*(DBL_MAX_EXP+Bias-P))
1457 0                 goto ovfl;
1458 0             if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) {
1459                 /* set to largest number */
1460                 /* (Can't trust DBL_MAX) */
1461 0                 set_word0(rv, Big0);
1462 0                 set_word1(rv, Big1);
1463                 }
1464             else
1465 0                 set_word0(rv, word0(rv) + P*Exp_msk1);
1466             }
1467     }
1468 0     else if (e1 < 0) {
1469 0         e1 = -e1;
1470 0         if ((i = e1 & 15) != 0)
1471 0             rv /= tens[i];
1472 0         if (e1 &= ~15) {
1473 0             e1 >>= 4;
1474 0             if (e1 >= 1 << n_bigtens)
1475 0                 goto undfl;
1476 #ifdef Avoid_Underflow
1477 0             if (e1 & Scale_Bit)
1478 0                 scale = P;
1479 0             for(j = 0; e1 > 0; j++, e1 >>= 1)
1480 0                 if (e1 & 1)
1481 0                     rv *= tinytens[j];
1482 0             if (scale && (j = P + 1 - ((word0(rv) & Exp_mask)
1483                         >> Exp_shift)) > 0) {
1484                 /* scaled rv is denormal; zap j low bits */
1485 0                 if (j >= 32) {
1486 0                     set_word1(rv, 0);
1487 0                     set_word0(rv, word0(rv) & (0xffffffff << (j-32)));
1488 0                     if (!word0(rv))
1489 0                         set_word0(rv, 1);
1490                     }
1491                 else
1492 0                     set_word1(rv, word1(rv) & (0xffffffff << j));
1493                 }
1494 #else
1495             for(j = 0; e1 > 1; j++, e1 >>= 1)
1496                 if (e1 & 1)
1497                     rv *= tinytens[j];
1498             /* The last multiplication could underflow. */
1499             rv0 = rv;
1500             rv *= tinytens[j];
1501             if (!rv) {
1502                 rv = 2.*rv0;
1503                 rv *= tinytens[j];
1504 #endif
1505 0                 if (!rv) {
1506                 undfl:
1507 0                     rv = 0.;
1508 0                     *err = JS_DTOA_ERANGE;
1509 0                     if (bd0)
1510 0                         goto retfree;
1511 0                     goto ret;
1512                 }
1513 #ifndef Avoid_Underflow
1514                 set_word0(rv, Tiny0);
1515                 set_word1(rv, Tiny1);
1516                 /* The refinement below will clean
1517                  * this approximation up.
1518                  */
1519             }
1520 #endif
1521         }
1522     }
1523
1524     /* Now the hard part -- adjusting rv to the correct value.*/
1525
1526     /* Put digits into bd: true value = bd * 10^e */
1527
1528 0     bd0 = s2b(s0, nd0, nd, y);
1529 0     if (!bd0)
1530 0         goto nomem;
1531
1532 0     for(;;) {
1533 0         bd = Balloc(bd0->k);
1534 0         if (!bd)
1535 0             goto nomem;
1536 0         Bcopy(bd, bd0);
1537 0         bb = d2b(rv, &bbe, &bbbits);    /* rv = bb * 2^bbe */
1538 0         if (!bb)
1539 0             goto nomem;
1540 0         bs = i2b(1);
1541 0         if (!bs)
1542 0             goto nomem;
1543
1544 0         if (e >= 0) {
1545 0             bb2 = bb5 = 0;
1546 0             bd2 = bd5 = e;
1547         }
1548         else {
1549 0             bb2 = bb5 = -e;
1550 0             bd2 = bd5 = 0;
1551         }
1552 0         if (bbe >= 0)
1553 0             bb2 += bbe;
1554         else
1555 0             bd2 -= bbe;
1556 0         bs2 = bb2;
1557 #ifdef Sudden_Underflow
1558         j = P + 1 - bbbits;
1559 #else
1560 #ifdef Avoid_Underflow
1561 0         j = bbe - scale;
1562 #else
1563         j = bbe;
1564 #endif
1565 0         i = j + bbbits - 1; /* logb(rv) */
1566 0         if (i < Emin)   /* denormal */
1567 0             j += P - Emin;
1568         else
1569 0             j = P + 1 - bbbits;
1570 #endif
1571 0         bb2 += j;
1572 0         bd2 += j;
1573 #ifdef Avoid_Underflow
1574 0         bd2 += scale;
1575 #endif
1576 0         i = bb2 < bd2 ? bb2 : bd2;
1577 0         if (i > bs2)
1578 0             i = bs2;
1579 0         if (i > 0) {
1580 0             bb2 -= i;
1581 0             bd2 -= i;
1582 0             bs2 -= i;
1583         }
1584 0         if (bb5 > 0) {
1585 0             bs = pow5mult(bs, bb5);
1586 0             if (!bs)
1587 0                 goto nomem;
1588 0             bb1 = mult(bs, bb);
1589 0             if (!bb1)
1590 0                 goto nomem;
1591 0             Bfree(bb);
1592 0             bb = bb1;
1593         }
1594 0         if (bb2 > 0) {
1595 0             bb = lshift(bb, bb2);
1596 0             if (!bb)
1597 0                 goto nomem;
1598         }
1599 0         if (bd5 > 0) {
1600 0             bd = pow5mult(bd, bd5);
1601 0             if (!bd)
1602 0                 goto nomem;
1603         }
1604 0         if (bd2 > 0) {
1605 0             bd = lshift(bd, bd2);
1606 0             if (!bd)
1607 0                 goto nomem;
1608         }
1609 0         if (bs2 > 0) {
1610 0             bs = lshift(bs, bs2);
1611 0             if (!bs)
1612 0                 goto nomem;
1613         }
1614 0         delta = diff(bb, bd);
1615 0         if (!delta)
1616 0             goto nomem;
1617 0         dsign = delta->sign;
1618 0         delta->sign = 0;
1619 0         i = cmp(delta, bs);
1620 0         if (i < 0) {
1621             /* Error is less than half an ulp -- check for
1622              * special case of mantissa a power of two.
1623              */
1624 0             if (dsign || word1(rv) || word0(rv) & Bndry_mask
1625 #ifdef Avoid_Underflow
1626 0              || (word0(rv) & Exp_mask) <= Exp_msk1 + P*Exp_msk1
1627 #else
1628              || (word0(rv) & Exp_mask) <= Exp_msk1
1629 #endif
1630                 ) {
1631 #ifdef Avoid_Underflow
1632 0                 if (!delta->x[0] && delta->wds == 1)
1633 0                     dsign = 2;
1634 #endif
1635 0                 break;
1636                 }
1637 0             delta = lshift(delta,Log2P);
1638 0             if (!delta)
1639 0                 goto nomem;
1640 0             if (cmp(delta, bs) > 0)
1641 0                 goto drop_down;
1642 0             break;
1643         }
1644 0         if (i == 0) {
1645             /* exactly half-way between */
1646 0             if (dsign) {
1647 0                 if ((word0(rv) & Bndry_mask1) == Bndry_mask1
1648 0                     &&  word1(rv) == 0xffffffff) {
1649                     /*boundary case -- increment exponent*/
1650 0                     set_word0(rv, (word0(rv) & Exp_mask) + Exp_msk1);
1651 0                     set_word1(rv, 0);
1652 #ifdef Avoid_Underflow
1653 0                     dsign = 0;
1654 #endif
1655 0                     break;
1656                 }
1657             }
1658 0             else if (!(word0(rv) & Bndry_mask) && !word1(rv)) {
1659 #ifdef Avoid_Underflow
1660 0                 dsign = 2;
1661 #endif
1662             drop_down:
1663                 /* boundary case -- decrement exponent */
1664 #ifdef Sudden_Underflow
1665                 L = word0(rv) & Exp_mask;
1666                 if (L <= Exp_msk1)
1667                     goto undfl;
1668                 L -= Exp_msk1;
1669 #else
1670 0                 L = (word0(rv) & Exp_mask) - Exp_msk1;
1671 #endif
1672 0                 set_word0(rv, L | Bndry_mask1);
1673 0                 set_word1(rv, 0xffffffff);
1674 0                 break;
1675             }
1676 #ifndef ROUND_BIASED
1677 0             if (!(word1(rv) & LSB))
1678 0                 break;
1679 #endif
1680 0             if (dsign)
1681 0                 rv += ulp(rv);
1682 #ifndef ROUND_BIASED
1683             else {
1684 0                 rv -= ulp(rv);
1685 #ifndef Sudden_Underflow
1686 0                 if (!rv)
1687 0                     goto undfl;
1688 #endif
1689             }
1690 #ifdef Avoid_Underflow
1691 0             dsign = 1 - dsign;
1692 #endif
1693 #endif
1694 0             break;
1695         }
1696 0         if ((aadj = ratio(delta, bs)) <= 2.) {
1697 0             if (dsign)
1698 0                 aadj = aadj1 = 1.;
1699 0             else if (word1(rv) || word0(rv) & Bndry_mask) {
1700 #ifndef Sudden_Underflow
1701 0                 if (word1(rv) == Tiny1 && !word0(rv))
1702 0                     goto undfl;
1703 #endif
1704 0                 aadj = 1.;
1705 0                 aadj1 = -1.;
1706             }
1707             else {
1708                 /* special case -- power of FLT_RADIX to be */
1709                 /* rounded down... */
1710
1711 0                 if (aadj < 2./FLT_RADIX)
1712 0                     aadj = 1./FLT_RADIX;
1713                 else
1714 0                     aadj *= 0.5;
1715 0                 aadj1 = -aadj;
1716             }
1717         }
1718         else {
1719 0             aadj *= 0.5;
1720 0             aadj1 = dsign ? aadj : -aadj;
1721 #ifdef Check_FLT_ROUNDS
1722             switch(FLT_ROUNDS) {
1723             case 2: /* towards +infinity */
1724                 aadj1 -= 0.5;
1725                 break;
1726             case 0: /* towards 0 */
1727             case 3: /* towards -infinity */
1728                 aadj1 += 0.5;
1729             }
1730 #else
1731 0             if (FLT_ROUNDS == 0)
1732 0                 aadj1 += 0.5;
1733 #endif
1734         }
1735 0         y = word0(rv) & Exp_mask;
1736
1737         /* Check for overflow */
1738
1739 0         if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) {
1740 0             rv0 = rv;
1741 0             set_word0(rv, word0(rv) - P*Exp_msk1);
1742 0             adj = aadj1 * ulp(rv);
1743 0             rv += adj;
1744 0             if ((word0(rv) & Exp_mask) >=
1745                 Exp_msk1*(DBL_MAX_EXP+Bias-P)) {
1746 0                 if (word0(rv0) == Big0 && word1(rv0) == Big1)
1747 0                     goto ovfl;
1748 0                 set_word0(rv, Big0);
1749 0                 set_word1(rv, Big1);
1750 0                 goto cont;
1751             }
1752             else
1753 0                 set_word0(rv, word0(rv) + P*Exp_msk1);
1754         }
1755         else {
1756 #ifdef Sudden_Underflow
1757             if ((word0(rv) & Exp_mask) <= P*Exp_msk1) {
1758                 rv0 = rv;
1759                 set_word0(rv, word0(rv) + P*Exp_msk1);
1760                 adj = aadj1 * ulp(rv);
1761                 rv += adj;
1762                     if ((word0(rv) & Exp_mask) <= P*Exp_msk1)
1763                         {
1764                             if (word0(rv0) == Tiny0
1765                                 && word1(rv0) == Tiny1)
1766                                 goto undfl;
1767                             set_word0(rv, Tiny0);
1768                             set_word1(rv, Tiny1);
1769                             goto cont;
1770                         }
1771                     else
1772                         set_word0(rv, word0(rv) - P*Exp_msk1);
1773             }
1774             else {
1775                 adj = aadj1 * ulp(rv);
1776                 rv += adj;
1777             }
1778 #else
1779             /* Compute adj so that the IEEE rounding rules will
1780              * correctly round rv + adj in some half-way cases.
1781              * If rv * ulp(rv) is denormalized (i.e.,
1782              * y <= (P-1)*Exp_msk1), we must adjust aadj to avoid
1783              * trouble from bits lost to denormalization;
1784              * example: 1.2e-307 .
1785              */
1786 #ifdef Avoid_Underflow
1787 0             if (y <= P*Exp_msk1 && aadj > 1.)
1788 #else
1789             if (y <= (P-1)*Exp_msk1 && aadj > 1.)
1790 #endif
1791                 {
1792 0                 aadj1 = (double)(int32)(aadj + 0.5);
1793 0                 if (!dsign)
1794 0                     aadj1 = -aadj1;
1795             }
1796 #ifdef Avoid_Underflow
1797 0             if (scale && y <= P*Exp_msk1)
1798 0                 set_word0(aadj1, word0(aadj1) + (P+1)*Exp_msk1 - y);
1799 #endif
1800 0             adj = aadj1 * ulp(rv);
1801 0             rv += adj;
1802 #endif
1803         }
1804 0         z = word0(rv) & Exp_mask;
1805 #ifdef Avoid_Underflow
1806 0         if (!scale)
1807 #endif
1808 0         if (y == z) {
1809             /* Can we stop now? */
1810 0             L = (Long)aadj;
1811 0             aadj -= L;
1812             /* The tolerances below are conservative. */
1813 0             if (dsign || word1(rv) || word0(rv) & Bndry_mask) {
1814 0                 if (aadj < .4999999 || aadj > .5000001)
1815 0                     break;
1816             }
1817 0             else if (aadj < .4999999/FLT_RADIX)
1818 0                 break;
1819         }
1820     cont:
1821 0         Bfree(bb);
1822 0         Bfree(bd);
1823 0         Bfree(bs);
1824 0         Bfree(delta);
1825 0         bb = bd = bs = delta = NULL;
1826     }
1827 #ifdef Avoid_Underflow
1828 0     if (scale) {
1829 0         set_word0(rv0, Exp_1 - P*Exp_msk1);
1830 0         set_word1(rv0, 0);
1831 0         if ((word0(rv) & Exp_mask) <= P*Exp_msk1
1832 0               && word1(rv) & 1
1833               && dsign != 2) {
1834 0             if (dsign) {
1835 #ifdef Sudden_Underflow
1836                 /* rv will be 0, but this would give the  */
1837                 /* right result if only rv *= rv0 worked. */
1838                 set_word0(rv, word0(rv) + P*Exp_msk1);
1839                 set_word0(rv0, Exp_1 - 2*P*Exp_msk1);
1840 #endif
1841 0                 rv += ulp(rv);
1842                 }
1843             else
1844 0                 set_word1(rv, word1(rv) & ~1);
1845         }
1846 0         rv *= rv0;
1847     }
1848 #endif /* Avoid_Underflow */
1849 retfree:
1850 0     Bfree(bb);
1851 0     Bfree(bd);
1852 0     Bfree(bs);
1853 0     Bfree(bd0);
1854 0     Bfree(delta);
1855 ret:
1856     RELEASE_DTOA_LOCK();
1857 16401     if (se)
1858 16401         *se = (char *)s;
1859 16401     return sign ? -rv : rv;
1860
1861 nomem:
1862 0     Bfree(bb);
1863 0     Bfree(bd);
1864 0     Bfree(bs);
1865 0     Bfree(bd0);
1866 0     Bfree(delta);
1867 0     *err = JS_DTOA_ENOMEM;
1868 0     return 0;
1869 }
1870
1871
1872 /* Return floor(b/2^k) and set b to be the remainder.  The returned quotient must be less than 2^32. */
1873 static uint32 quorem2(Bigint *b, int32 k)
1874 0 {
1875 0     ULong mask;
1876 0     ULong result;
1877 0     ULong *bx, *bxe;
1878 0     int32 w;
1879 0     int32 n = k >> 5;
1880 0     k &= 0x1F;
1881 0     mask = (1<<k) - 1;
1882
1883 0     w = b->wds - n;
1884 0     if (w <= 0)
1885 0         return 0;
1886 0     JS_ASSERT(w <= 2);
1887 0     bx = b->x;
1888 0     bxe = bx + n;
1889 0     result = *bxe >> k;
1890 0     *bxe &= mask;
1891 0     if (w == 2) {
1892 0         JS_ASSERT(!(bxe[1] & ~mask));
1893 0         if (k)
1894 0             result |= bxe[1] << (32 - k);
1895     }
1896 0     n++;
1897 0     while (!*bxe && bxe != bx) {
1898 0         n--;
1899 0         bxe--;
1900     }
1901 0     b->wds = n;
1902 0     return result;
1903 }
1904
1905 /* Return floor(b/S) and set b to be the remainder.  As added restrictions, b must not have
1906  * more words than S, the most significant word of S must not start with a 1 bit, and the
1907  * returned quotient must be less than 36. */
1908 static int32 quorem(Bigint *b, Bigint *S)
1909 0 {
1910 0     int32 n;
1911 0     ULong *bx, *bxe, q, *sx, *sxe;
1912 #ifdef ULLong
1913 0     ULLong borrow, carry, y, ys;
1914 #else
1915     ULong borrow, carry, y, ys;
1916     ULong si, z, zs;
1917 #endif
1918
1919 0     n = S->wds;
1920 0     JS_ASSERT(b->wds <= n);
1921 0     if (b->wds < n)
1922 0         return 0;
1923 0     sx = S->x;
1924 0     sxe = sx + --n;
1925 0     bx = b->x;
1926 0     bxe = bx + n;
1927 0     JS_ASSERT(*sxe <= 0x7FFFFFFF);
1928 0     q = *bxe / (*sxe + 1);  /* ensure q <= true quotient */
1929 0     JS_ASSERT(q < 36);
1930 0     if (q) {
1931 0         borrow = 0;
1932 0         carry = 0;
1933 0         do {
1934 #ifdef ULLong
1935 0             ys = *sx++ * (ULLong)q + carry;
1936 0             carry = ys >> 32;
1937 0             y = *bx - (ys & 0xffffffffUL) - borrow;
1938 0             borrow = y >> 32 & 1UL;
1939 0             *bx++ = (ULong)(y & 0xffffffffUL);
1940 #else
1941             si = *sx++;
1942             ys = (si & 0xffff) * q + carry;
1943             zs = (si >> 16) * q + (ys >> 16);
1944             carry = zs >> 16;
1945             y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
1946             borrow = (y & 0x10000) >> 16;
1947             z = (*bx >> 16) - (zs & 0xffff) - borrow;
1948             borrow = (z & 0x10000) >> 16;
1949             Storeinc(bx, z, y);
1950 #endif
1951 0         }
1952         while(sx <= sxe);
1953 0         if (!*bxe) {
1954 0             bx = b->x;
1955 0             while(--bxe > bx && !*bxe)
1956 0                 --n;
1957 0             b->wds = n;
1958         }
1959     }
1960 0     if (cmp(b, S) >= 0) {
1961 0         q++;
1962 0         borrow = 0;
1963 0         carry = 0;
1964 0         bx = b->x;
1965 0         sx = S->x;
1966 0         do {
1967 #ifdef ULLong
1968 0             ys = *sx++ + carry;
1969 0             carry = ys >> 32;
1970 0             y = *bx - (ys & 0xffffffffUL) - borrow;
1971 0             borrow = y >> 32 & 1UL;
1972 0             *bx++ = (ULong)(y & 0xffffffffUL);
1973 #else
1974             si = *sx++;
1975             ys = (si & 0xffff) + carry;
1976             zs = (si >> 16) + (ys >> 16);
1977             carry = zs >> 16;
1978             y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
1979             borrow = (y & 0x10000) >> 16;
1980             z = (*bx >> 16) - (zs & 0xffff) - borrow;
1981             borrow = (z & 0x10000) >> 16;
1982             Storeinc(bx, z, y);
1983 #endif
1984 0         } while(sx <= sxe);
1985 0         bx = b->x;
1986 0         bxe = bx + n;
1987 0         if (!*bxe) {
1988 0             while(--bxe > bx && !*bxe)
1989 0                 --n;
1990 0             b->wds = n;
1991         }
1992     }
1993 0     return (int32)q;
1994 }
1995
1996 /* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
1997  *
1998  * Inspired by "How to Print Floating-Point Numbers Accurately" by
1999  * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 92-101].
2000  *
2001  * Modifications:
2002  *  1. Rather than iterating, we use a simple numeric overestimate
2003  *     to determine k = floor(log10(d)).  We scale relevant
2004  *     quantities using O(log2(k)) rather than O(k) multiplications.
2005  *  2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
2006  *     try to generate digits strictly left to right.  Instead, we
2007  *     compute with fewer bits and propagate the carry if necessary
2008  *     when rounding the final digit up.  This is often faster.
2009  *  3. Under the assumption that input will be rounded nearest,
2010  *     mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
2011  *     That is, we allow equality in stopping tests when the
2012  *     round-nearest rule will give the same floating-point value
2013  *     as would satisfaction of the stopping test with strict
2014  *     inequality.
2015  *  4. We remove common factors of powers of 2 from relevant
2016  *     quantities.
2017  *  5. When converting floating-point integers less than 1e16,
2018  *     we use floating-point arithmetic rather than resorting
2019  *     to multiple-precision integers.
2020  *  6. When asked to produce fewer than 15 digits, we first try
2021  *     to get by with floating-point arithmetic; we resort to
2022  *     multiple-precision integer arithmetic only if we cannot
2023  *     guarantee that the floating-point calculation has given
2024  *     the correctly rounded result.  For k requested digits and
2025  *     "uniformly" distributed input, the probability is
2026  *     something like 10^(k-15) that we must resort to the Long
2027  *     calculation.
2028  */
2029
2030 /* Always emits at least one digit. */
2031 /* If biasUp is set, then rounding in modes 2 and 3 will round away from zero
2032  * when the number is exactly halfway between two representable values.  For example,
2033  * rounding 2.5 to zero digits after the decimal point will return 3 and not 2.
2034  * 2.49 will still round to 2, and 2.51 will still round to 3. */
2035 /* bufsize should be at least 20 for modes 0 and 1.  For the other modes,
2036  * bufsize should be two greater than the maximum number of output characters expected. */
2037 static JSBool
2038 js_dtoa(double d, int mode, JSBool biasUp, int ndigits,
2039     int *decpt, int *sign, char **rve, char *buf, size_t bufsize)
2040 111 {
2041     /*  Arguments ndigits, decpt, sign are similar to those
2042         of ecvt and fcvt; trailing zeros are suppressed from
2043         the returned string.  If not null, *rve is set to point
2044         to the end of the return value.  If d is +-Infinity or NaN,
2045         then *decpt is set to 9999.
2046
2047         mode:
2048         0 ==> shortest string that yields d when read in
2049         and rounded to nearest.
2050         1 ==> like 0, but with Steele & White stopping rule;
2051         e.g. with IEEE P754 arithmetic , mode 0 gives
2052         1e23 whereas mode 1 gives 9.999999999999999e22.
2053         2 ==> max(1,ndigits) significant digits.  This gives a
2054         return value similar to that of ecvt, except
2055         that trailing zeros are suppressed.
2056         3 ==> through ndigits past the decimal point.  This
2057         gives a return value similar to that from fcvt,
2058         except that trailing zeros are suppressed, and
2059         ndigits can be negative.
2060         4-9 should give the same return values as 2-3, i.e.,
2061         4 <= mode <= 9 ==> same return as mode
2062         2 + (mode & 1).  These modes are mainly for
2063         debugging; often they run slower but sometimes
2064         faster than modes 2-3.
2065         4,5,8,9 ==> left-to-right digit generation.
2066         6-9 ==> don't try fast floating-point estimate
2067         (if applicable).
2068
2069         Values of mode other than 0-9 are treated as mode 0.
2070
2071         Sufficient space is allocated to the return value
2072         to hold the suppressed trailing zeros.
2073     */
2074
2075 111     int32 bbits, b2, b5, be, dig, i, ieps, ilim, ilim0, ilim1,
2076 111         j, j1, k, k0, k_check, leftright, m2, m5, s2, s5,
2077 111         spec_case, try_quick;
2078 111     Long L;
2079 #ifndef Sudden_Underflow
2080 111     int32 denorm;
2081 111     ULong x;
2082 #endif
2083 111     Bigint *b, *b1, *delta, *mlo, *mhi, *S;
2084 111     double d2, ds, eps;
2085 111     char *s;
2086
2087 111     if (word0(d) & Sign_bit) {
2088         /* set sign for everything, including 0's and NaNs */
2089 0         *sign = 1;
2090 0         set_word0(d, word0(d) & ~Sign_bit);  /* clear sign bit */
2091     }
2092     else
2093 111         *sign = 0;
2094
2095 111     if ((word0(d) & Exp_mask) == Exp_mask) {
2096         /* Infinity or NaN */
2097 111         *decpt = 9999;
2098 111         s = !word1(d) && !(word0(d) & Frac_mask) ? "Infinity" : "NaN";
2099 111         if ((s[0] == 'I' && bufsize < 9) || (s[0] == 'N' && bufsize < 4)) {
2100 0             JS_ASSERT(JS_FALSE);
2101 /*          JS_SetError(JS_BUFFER_OVERFLOW_ERROR, 0); */
2102 0             return JS_FALSE;
2103         }
2104 111         strcpy(buf, s);
2105 111         if (rve) {
2106 111             *rve = buf[3] ? buf + 8 : buf + 3;
2107 111             JS_ASSERT(**rve == '\0');
2108         }
2109 111         return JS_TRUE;
2110     }
2111
2112 0     b = NULL;                           /* initialize for abort protection */
2113 0     S = NULL;
2114 0     mlo = mhi = NULL;
2115
2116 0     if (!d) {
2117       no_digits:
2118 0         *decpt = 1;
2119 0         if (bufsize < 2) {
2120 0             JS_ASSERT(JS_FALSE);
2121 /*          JS_SetError(JS_BUFFER_OVERFLOW_ERROR, 0); */
2122 0             return JS_FALSE;
2123         }
2124 0         buf[0] = '0'; buf[1] = '\0';  /* copy "0" to buffer */
2125 0         if (rve)
2126 0             *rve = buf + 1;
2127         /* We might have jumped to "no_digits" from below, so we need
2128          * to be sure to free the potentially allocated Bigints to avoid
2129          * memory leaks. */
2130 0         Bfree(b);
2131 0         Bfree(S);
2132 0         if (mlo != mhi)
2133 0             Bfree(mlo);
2134 0         Bfree(mhi);
2135 0         return JS_TRUE;
2136     }
2137
2138 0     b = d2b(d, &be, &bbits);
2139 0     if (!b)
2140 0         goto nomem;
2141 #ifdef Sudden_Underflow
2142     i = (int32)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1));
2143 #else
2144 0     if ((i = (int32)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1))) != 0) {
2145 #endif
2146 0         d2 = d;
2147 0         set_word0(d2, word0(d2) & Frac_mask1);
2148 0         set_word0(d2, word0(d2) | Exp_11);
2149
2150         /* log(x)   ~=~ log(1.5) + (x-1.5)/1.5
2151          * log10(x)  =  log(x) / log(10)
2152          *      ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
2153          * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2)
2154          *
2155          * This suggests computing an approximation k to log10(d) by
2156          *
2157          * k = (i - Bias)*0.301029995663981
2158          *  + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
2159          *
2160          * We want k to be too large rather than too small.
2161          * The error in the first-order Taylor series approximation
2162          * is in our favor, so we just round up the constant enough
2163          * to compensate for any error in the multiplication of
2164          * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
2165          * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
2166          * adding 1e-13 to the constant term more than suffices.
2167          * Hence we adjust the constant term to 0.1760912590558.
2168          * (We could get a more accurate k by invoking log10,
2169          *  but this is probably not worthwhile.)
2170          */
2171
2172 0         i -= Bias;
2173 #ifndef Sudden_Underflow
2174 0         denorm = 0;
2175     }
2176     else {
2177         /* d is denormalized */
2178
2179 0         i = bbits + be + (Bias + (P-1) - 1);
2180 0         x = i > 32 ? word0(d) << (64 - i) | word1(d) >> (i - 32) : word1(d) << (32 - i);
2181 0         d2 = x;
2182 0         set_word0(d2, word0(d2) - 31*Exp_msk1); /* adjust exponent */
2183 0         i -= (Bias + (P-1) - 1) + 1;
2184 0         denorm = 1;
2185     }
2186 #endif
2187     /* At this point d = f*2^i, where 1 <= f < 2.  d2 is an approximation of f. */
2188 0     ds = (d2-1.5)*0.289529654602168 + 0.1760912590558 + i*0.301029995663981;
2189 0     k = (int32)ds;
2190 0     if (ds < 0. && ds != k)
2191 0         k--;    /* want k = floor(ds) */
2192 0     k_check = 1;
2193 0     if (k >= 0 && k <= Ten_pmax) {
2194 0         if (d < tens[k])
2195 0             k--;
2196 0         k_check = 0;
2197     }
2198     /* At this point floor(log10(d)) <= k <= floor(log10(d))+1.
2199        If k_check is zero, we're guaranteed that k = floor(log10(d)). */
2200 0     j = bbits - i - 1;
2201     /* At this point d = b/2^j, where b is an odd integer. */
2202 0     if (j >= 0) {
2203 0         b2 = 0;
2204 0         s2 = j;
2205     }
2206     else {
2207 0         b2 = -j;
2208 0         s2 = 0;
2209     }
2210 0     if (k >= 0) {
2211 0         b5 = 0;
2212 0         s5 = k;
2213 0         s2 += k;
2214     }
2215     else {
2216 0         b2 -= k;
2217 0         b5 = -k;
2218 0         s5 = 0;
2219     }
2220     /* At this point d/10^k = (b * 2^b2 * 5^b5) / (2^s2 * 5^s5), where b is an odd integer,
2221        b2 >= 0, b5 >= 0, s2 >= 0, and s5 >= 0. */
2222 0     if (mode < 0 || mode > 9)
2223 0         mode = 0;
2224 0     try_quick = 1;
2225 0     if (mode > 5) {
2226 0         mode -= 4;
2227 0         try_quick = 0;
2228     }
2229 0     leftright = 1;
2230 0     ilim = ilim1 = 0;
2231 0     switch(mode) {
2232     case 0:
2233     case 1:
2234 0         ilim = ilim1 = -1;
2235 0         i = 18;
2236 0         ndigits = 0;
2237 0         break;
2238     case 2:
2239 0         leftright = 0;
2240         /* no break */
2241     case 4:
2242 0         if (ndigits <= 0)
2243 0             ndigits = 1;
2244 0         ilim = ilim1 = i = ndigits;
2245 0         break;
2246     case 3:
2247 0         leftright = 0;
2248         /* no break */
2249     case 5:
2250 0         i = ndigits + k + 1;
2251 0         ilim = i;
2252 0         ilim1 = i - 1;
2253 0         if (i <= 0)
2254 0             i = 1;
2255     }
2256     /* ilim is the maximum number of significant digits we want, based on k and ndigits. */
2257     /* ilim1 is the maximum number of significant digits we want, based on k and ndigits,
2258        when it turns out that k was computed too high by one. */
2259
2260     /* Ensure space for at least i+1 characters, including trailing null. */
2261 0     if (bufsize <= (size_t)i) {
2262 0         Bfree(b);
2263 0         JS_ASSERT(JS_FALSE);
2264 0         return JS_FALSE;
2265     }
2266 0     s = buf;
2267
2268 0     if (ilim >= 0 && ilim <= Quick_max && try_quick) {
2269
2270         /* Try to get by with floating-point arithmetic. */
2271
2272 0         i = 0;
2273 0         d2 = d;
2274 0         k0 = k;
2275 0         ilim0 = ilim;
2276 0         ieps = 2; /* conservative */
2277         /* Divide d by 10^k, keeping track of the roundoff error and avoiding overflows. */
2278 0         if (k > 0) {
2279 0             ds = tens[k&0xf];
2280 0             j = k >> 4;
2281 0             if (j & Bletch) {
2282                 /* prevent overflows */
2283 0                 j &= Bletch - 1;
2284 0                 d /= bigtens[n_bigtens-1];
2285 0                 ieps++;
2286             }
2287 0             for(; j; j >>= 1, i++)
2288 0                 if (j & 1) {
2289 0                     ieps++;
2290 0                     ds *= bigtens[i];
2291                 }
2292 0             d /= ds;
2293         }
2294 0         else if ((j1 = -k) != 0) {
2295 0             d *= tens[j1 & 0xf];
2296 0             for(j = j1 >> 4; j; j >>= 1, i++)
2297 0                 if (j & 1) {
2298 0                     ieps++;
2299 0                     d *= bigtens[i];
2300                 }
2301         }
2302         /* Check that k was computed correctly. */
2303 0         if (k_check && d < 1. && ilim > 0) {
2304 0             if (ilim1 <= 0)
2305 0                 goto fast_failed;
2306 0             ilim = ilim1;
2307 0             k--;
2308 0             d *= 10.;
2309 0             ieps++;
2310         }
2311         /* eps bounds the cumulative error. */
2312 0         eps = ieps*d + 7.;
2313 0         set_word0(eps, word0(eps) - (P-1)*Exp_msk1);
2314 0         if (ilim == 0) {
2315 0             S = mhi = 0;
2316 0             d -= 5.;
2317 0             if (d > eps)
2318 0                 goto one_digit;
2319 0             if (d < -eps)
2320 0                 goto no_digits;
2321 0             goto fast_failed;
2322         }
2323 #ifndef No_leftright
2324 0         if (leftright) {
2325             /* Use Steele & White method of only
2326              * generating digits needed.
2327              */
2328 0             eps = 0.5/tens[ilim-1] - eps;
2329 0             for(i = 0;;) {
2330 0                 L = (Long)d;
2331 0                 d -= L;
2332 0                 *s++ = '0' + (char)L;
2333 0                 if (d < eps)
2334 0                     goto ret1;
2335 0                 if (1. - d < eps)
2336 0                     goto bump_up;
2337 0                 if (++i >= ilim)
2338 0                     break;
2339 0                 eps *= 10.;
2340 0                 d *= 10.;
2341             }
2342         }
2343         else {
2344 #endif
2345             /* Generate ilim digits, then fix them up. */
2346 0             eps *= tens[ilim-1];
2347 0             for(i = 1;; i++, d *= 10.) {
2348 0                 L = (Long)d;
2349 0                 d -= L;
2350 0                 *s++ = '0' + (char)L;
2351 0                 if (i == ilim) {
2352 0                     if (d > 0.5 + eps)
2353 0                         goto bump_up;
2354 0                     else if (d < 0.5 - eps) {
2355 0                         while(*--s == '0') ;
2356 0                         s++;
2357 0                         goto ret1;
2358                     }
2359 0                     break;
2360                 }
2361             }
2362 #ifndef No_leftright
2363         }
2364 #endif
2365     fast_failed:
2366 0         s = buf;
2367 0         d = d2;
2368 0         k = k0;
2369 0         ilim = ilim0;
2370     }
2371
2372     /* Do we have a "small" integer? */
2373
2374 0     if (be >= 0 && k <= Int_max) {
2375         /* Yes. */
2376 0         ds = tens[k];
2377 0         if (ndigits < 0 && ilim <= 0) {
2378 0             S = mhi = 0;
2379 0             if (ilim < 0 || d < 5*ds || (!biasUp && d == 5*ds))
2380 0                 goto no_digits;
2381 0             goto one_digit;
2382         }
2383
2384         /* Use true number of digits to limit looping. */
2385 0         for(i = 1; i<=k+1; i++) {
2386 0             L = (Long) (d / ds);
2387 0             d -= L*ds;
2388 #ifdef Check_FLT_ROUNDS
2389             /* If FLT_ROUNDS == 2, L will usually be high by 1 */
2390             if (d < 0) {
2391                 L--;
2392                 d += ds;
2393             }
2394 #endif
2395 0             *s++ = '0' + (char)L;
2396 0             if (i == ilim) {
2397 0                 d += d;
2398 0                 if ((d > ds) || (d == ds && (L & 1 || biasUp))) {
2399                 bump_up:
2400 0                     while(*--s == '9')
2401 0                         if (s == buf) {
2402 0                             k++;
2403 0                             *s = '0';
2404                             break;
2405                         }
2406 0                     ++*s++;
2407                 }
2408 0                 break;
2409             }
2410 0             d *= 10.;
2411         }
2412 0         goto ret1;
2413     }
2414
2415 0     m2 = b2;
2416 0     m5 = b5;
2417 0     if (leftright) {
2418 0         if (mode < 2) {
2419 0             i =
2420 #ifndef Sudden_Underflow
2421                 denorm ? be + (Bias + (P-1) - 1 + 1) :
2422 #endif
2423             1 + P - bbits;
2424             /* i is 1 plus the number of trailing zero bits in d's significand. Thus,
2425                (2^m2 * 5^m5) / (2^(s2+i) * 5^s5) = (1/2 lsb of d)/10^k. */
2426         }
2427         else {
2428 0             j = ilim - 1;
2429 0             if (m5 >= j)
2430 0                 m5 -= j;
2431             else {
2432 0                 s5 += j -= m5;
2433 0                 b5 += j;
2434 0                 m5 = 0;
2435             }
2436 0             if ((i = ilim) < 0) {
2437 0                 m2 -= i;
2438 0                 i = 0;
2439             }
2440             /* (2^m2 * 5^m5) / (2^(s2+i) * 5^s5) = (1/2 * 10^(1-ilim))/10^k. */
2441         }
2442 0         b2 += i;
2443 0         s2 += i;
2444 0         mhi = i2b(1);
2445 0         if (!mhi)
2446 0             goto nomem;
2447         /* (mhi * 2^m2 * 5^m5) / (2^s2 * 5^s5) = one-half of last printed (when mode >= 2) or
2448            input (when mode < 2) significant digit, divided by 10^k. */
2449     }
2450     /* We still have d/10^k = (b * 2^b2 * 5^b5) / (2^s2 * 5^s5).  Reduce common factors in
2451        b2, m2, and s2 without changing the equalities. */
2452 0     if (m2 > 0 && s2 > 0) {
2453 0         i = m2 < s2 ? m2 : s2;
2454 0         b2 -= i;
2455 0         m2 -= i;
2456 0         s2 -= i;
2457     }
2458
2459     /* Fold b5 into b and m5 into mhi. */
2460 0     if (b5 > 0) {
2461 0         if (leftright) {
2462 0             if (m5 > 0) {
2463 0                 mhi = pow5mult(mhi, m5);
2464 0                 if (!mhi)
2465 0                     goto nomem;
2466 0                 b1 = mult(mhi, b);
2467 0                 if (!b1)
2468 0                     goto nomem;
2469 0                 Bfree(b);
2470 0                 b = b1;
2471             }
2472 0             if ((j = b5 - m5) != 0) {
2473 0                 b = pow5mult(b, j);
2474 0                 if (!b)
2475 0                     goto nomem;
2476             }
2477         }
2478         else {
2479 0             b = pow5mult(b, b5);
2480 0             if (!b)
2481 0                 goto nomem;
2482         }
2483     }
2484     /* Now we have d/10^k = (b * 2^b2) / (2^s2 * 5^s5) and
2485        (mhi * 2^m2) / (2^s2 * 5^s5) = one-half of last printed or input significant digit, divided by 10^k. */
2486
2487 0     S = i2b(1);
2488 0     if (!S)
2489 0         goto nomem;
2490 0     if (s5 > 0) {
2491 0         S = pow5mult(S, s5);
2492 0         if (!S)
2493 0             goto nomem;
2494     }
2495     /* Now we have d/10^k = (b * 2^b2) / (S * 2^s2) and
2496        (mhi * 2^m2) / (S * 2^s2) = one-half of last printed or input significant digit, divided by 10^k. */
2497
2498     /* Check for special case that d is a normalized power of 2. */
2499 0     spec_case = 0;
2500 0     if (mode < 2) {
2501 0         if (!word1(d) && !(word0(d) & Bndry_mask)
2502 #ifndef Sudden_Underflow
2503 0             && word0(d) & (Exp_mask & Exp_mask << 1)
2504 #endif
2505             ) {
2506             /* The special case.  Here we want to be within a quarter of the last input
2507                significant digit instead of one half of it when the decimal output string's value is less than d.  */
2508 0             b2 += Log2P;
2509 0             s2 += Log2P;
2510 0             spec_case = 1;
2511         }
2512     }
2513
2514     /* Arrange for convenient computation of quotients:
2515      * shift left if necessary so divisor has 4 leading 0 bits.
2516      *
2517      * Perhaps we should just compute leading 28 bits of S once
2518      * and for all and pass them and a shift to quorem, so it
2519      * can do shifts and ors to compute the numerator for q.
2520      */
2521 0     if ((i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0x1f) != 0)
2522 0         i = 32 - i;
2523     /* i is the number of leading zero bits in the most significant word of S*2^s2. */
2524 0     if (i > 4) {
2525 0         i -= 4;
2526 0         b2 += i;
2527 0         m2 += i;
2528 0         s2 += i;
2529     }
2530 0     else if (i < 4) {
2531 0         i += 28;
2532 0         b2 += i;
2533 0         m2 += i;
2534 0         s2 += i;
2535     }
2536     /* Now S*2^s2 has exactly four leading zero bits in its most significant word. */
2537 0     if (b2 > 0) {
2538 0         b = lshift(b, b2);
2539 0         if (!b)
2540 0             goto nomem;
2541     }
2542 0     if (s2 > 0) {
2543 0         S = lshift(S, s2);
2544 0         if (!S)
2545 0             goto nomem;
2546     }
2547     /* Now we have d/10^k = b/S and
2548        (mhi * 2^m2) / S = maximum acceptable error, divided by 10^k. */
2549 0     if (k_check) {
2550 0         if (cmp(b,S) < 0) {
2551 0             k--;
2552 0             b = multadd(b, 10, 0);  /* we botched the k estimate */
2553 0             if (!b)
2554 0                 goto nomem;
2555 0             if (leftright) {
2556 0                 mhi = multadd(mhi, 10, 0);
2557 0                 if (!mhi)
2558 0                     goto nomem;
2559             }
2560 0             ilim = ilim1;
2561         }
2562     }
2563     /* At this point 1 <= d/10^k = b/S < 10. */
2564
2565 0     if (ilim <= 0 && mode > 2) {
2566         /* We're doing fixed-mode output and d is less than the minimum nonzero output in this mode.
2567            Output either zero or the minimum nonzero output depending on which is closer to d. */
2568 0         if (ilim < 0)
2569 0             goto no_digits;
2570 0         S = multadd(S,5,0);
2571 0         if (!S)
2572 0             goto nomem;
2573 0         i = cmp(b,S);
2574 0         if (i < 0 || (i == 0 && !biasUp)) {
2575         /* Always emit at least one digit.  If the number appears to be zero
2576            using the current mode, then emit one '0' digit and set decpt to 1. */
2577         /*no_digits:
2578             k = -1 - ndigits;
2579             goto ret; */
2580 0             goto no_digits;
2581         }
2582     one_digit:
2583 0         *s++ = '1';
2584 0         k++;
2585 0         goto ret;
2586     }
2587 0     if (leftright) {
2588 0         if (m2 > 0) {
2589 0             mhi = lshift(mhi, m2);
2590 0             if (!mhi)
2591 0                 goto nomem;
2592         }
2593
2594         /* Compute mlo -- check for special case
2595          * that d is a normalized power of 2.
2596          */
2597
2598 0         mlo = mhi;
2599 0         if (spec_case) {
2600 0             mhi = Balloc(mhi->k);
2601 0             if (!mhi)
2602 0                 goto nomem;
2603 0             Bcopy(mhi, mlo);
2604 0             mhi = lshift(mhi, Log2P);
2605 0             if (!mhi)
2606 0                 goto nomem;
2607         }
2608         /* mlo/S = maximum acceptable error, divided by 10^k, if the output is less than d. */
2609         /* mhi/S = maximum acceptable error, divided by 10^k, if the output is greater than d. */
2610
2611 0         for(i = 1;;i++) {
2612 0             dig = quorem(b,S) + '0';
2613             /* Do we yet have the shortest decimal string
2614              * that will round to d?
2615              */
2616 0             j = cmp(b, mlo);
2617             /* j is b/S compared with mlo/S. */
2618 0             delta = diff(S, mhi);
2619 0             if (!delta)
2620 0                 goto nomem;
2621 0             j1 = delta->sign ? 1 : cmp(b, delta);
2622 0             Bfree(delta);
2623             /* j1 is b/S compared with 1 - mhi/S. */
2624 #ifndef ROUND_BIASED
2625 0             if (j1 == 0 && !mode && !(word1(d) & 1)) {
2626 0                 if (dig == '9')
2627 0                     goto round_9_up;
2628 0                 if (j > 0)
2629 0                     dig++;
2630 0                 *s++ = (char)dig;
2631 0                 goto ret;
2632             }
2633 #endif
2634 0             if ((j < 0) || (j == 0 && !mode
2635 #ifndef ROUND_BIASED
2636 0                 && !(word1(d) & 1)
2637 #endif
2638                 )) {
2639 0                 if (j1 > 0) {
2640                     /* Either dig or dig+1 would work here as the least significant decimal digit.
2641                        Use whichever would produce a decimal value closer to d. */
2642 0                     b = lshift(b, 1);
2643 0                     if (!b)
2644 0                         goto nomem;
2645 0                     j1 = cmp(b, S);
2646 0                     if (((j1 > 0) || (j1 == 0 && (dig & 1 || biasUp)))
2647                         && (dig++ == '9'))
2648 0                         goto round_9_up;
2649                 }
2650 0                 *s++ = (char)dig;
2651 0                 goto ret;
2652             }
2653 0             if (j1 > 0) {
2654 0                 if (dig == '9') { /* possible if i == 1 */
2655                 round_9_up:
2656 0                     *s++ = '9';
2657 0                     goto roundoff;
2658                 }
2659 0                 *s++ = (char)dig + 1;
2660 0                 goto ret;
2661             }
2662 0             *s++ = (char)dig;
2663 0             if (i == ilim)
2664 0                 break;
2665 0             b = multadd(b, 10, 0);
2666 0             if (!b)
2667 0                 goto nomem;
2668 0             if (mlo == mhi) {
2669 0                 mlo = mhi = multadd(mhi, 10, 0);
2670 0                 if (!mhi)
2671 0                     goto nomem;
2672             }
2673             else {
2674 0                 mlo = multadd(mlo, 10, 0);
2675 0                 if (!mlo)
2676 0                     goto nomem;
2677 0                 mhi = multadd(mhi, 10, 0);
2678 0                 if (!mhi)
2679 0                     goto nomem;
2680             }
2681         }
2682     }
2683     else
2684 0         for(i = 1;; i++) {
2685 0             *s++ = (char)(dig = quorem(b,S) + '0');
2686 0             if (i >= ilim)
2687 0                 break;
2688 0             b = multadd(b, 10, 0);
2689 0             if (!b)
2690 0                 goto nomem;
2691         }
2692
2693     /* Round off last digit */
2694
2695 0     b = lshift(b, 1);
2696 0     if (!b)
2697 0         goto nomem;
2698 0     j = cmp(b, S);
2699 0     if ((j > 0) || (j == 0 && (dig & 1 || biasUp))) {
2700     roundoff:
2701 0         while(*--s == '9')
2702 0             if (s == buf) {
2703 0                 k++;
2704 0                 *s++ = '1';
2705 0                 goto ret;
2706             }
2707 0         ++*s++;
2708     }
2709     else {
2710         /* Strip trailing zeros */
2711 0         while(*--s == '0') ;
2712 0         s++;
2713     }
2714   ret:
2715 0     Bfree(S);
2716 0     if (mhi) {
2717 0         if (mlo && mlo != mhi)
2718 0             Bfree(mlo);
2719 0         Bfree(mhi);
2720     }
2721   ret1:
2722 0     Bfree(b);
2723 0     JS_ASSERT(s < buf + bufsize);
2724 0     *s = '\0';
2725 0     if (rve)
2726 0         *rve = s;
2727 0     *decpt = k + 1;
2728 0     return JS_TRUE;
2729
2730 nomem:
2731 0     Bfree(S);
2732 0     if (mhi) {
2733 0         if (mlo && mlo != mhi)
2734 0             Bfree(mlo);
2735 0         Bfree(mhi);
2736     }
2737 0     Bfree(b);
2738 0     return JS_FALSE;
2739 }
2740
2741
2742 /* Mapping of JSDToStrMode -> js_dtoa mode */
2743 static const int dtoaModes[] = {
2744     0,   /* DTOSTR_STANDARD */
2745     0,   /* DTOSTR_STANDARD_EXPONENTIAL, */
2746     3,   /* DTOSTR_FIXED, */
2747     2,   /* DTOSTR_EXPONENTIAL, */
2748     2};  /* DTOSTR_PRECISION */
2749
2750 JS_FRIEND_API(char *)
2751 JS_dtostr(char *buffer, size_t bufferSize, JSDToStrMode mode, int precision, double d)
2752 111 {
2753 111     int decPt;                  /* Position of decimal point relative to first digit returned by js_dtoa */
2754 111     int sign;                   /* Nonzero if the sign bit was set in d */
2755 111     int nDigits;                /* Number of significand digits returned by js_dtoa */
2756 111     char *numBegin = buffer+2;  /* Pointer to the digits returned by js_dtoa; the +2 leaves space for */
2757                                 /* the sign and/or decimal point */
2758 111     char *numEnd;               /* Pointer past the digits returned by js_dtoa */
2759 111     JSBool dtoaRet;
2760
2761 111     JS_ASSERT(bufferSize >= (size_t)(mode <= DTOSTR_STANDARD_EXPONENTIAL ? DTOSTR_STANDARD_BUFFER_SIZE :
2762             DTOSTR_VARIABLE_BUFFER_SIZE(precision)));
2763
2764 111     if (mode == DTOSTR_FIXED && (d >= 1e21 || d <= -1e21))
2765 0         mode = DTOSTR_STANDARD; /* Change mode here rather than below because the buffer may not be large enough to hold a large integer. */
2766
2767     /* Locking for Balloc's shared buffers */
2768     ACQUIRE_DTOA_LOCK();
2769 111     dtoaRet = js_dtoa(d, dtoaModes[mode], mode >= DTOSTR_FIXED, precision, &decPt, &sign, &numEnd, numBegin, bufferSize-2);
2770     RELEASE_DTOA_LOCK();
2771 111     if (!dtoaRet)
2772 0         return 0;
2773
2774 111     nDigits = numEnd - numBegin;
2775
2776     /* If Infinity, -Infinity, or NaN, return the string regardless of the mode. */
2777 111     if (decPt != 9999) {
2778 0         JSBool exponentialNotation = JS_FALSE;
2779 0         int minNDigits = 0;         /* Minimum number of significand digits required by mode and precision */
2780 0         char *p;
2781 0         char *q;
2782
2783 0         switch (mode) {
2784             case DTOSTR_STANDARD:
2785 0                 if (decPt < -5 || decPt > 21)
2786 0                     exponentialNotation = JS_TRUE;
2787                 else
2788 0                     minNDigits = decPt;
2789 0                 break;
2790
2791             case DTOSTR_FIXED:
2792 0                 if (precision >= 0)
2793 0                     minNDigits = decPt + precision;
2794                 else
2795 0                     minNDigits = decPt;
2796 0                 break;
2797
2798             case DTOSTR_EXPONENTIAL:
2799 0                 JS_ASSERT(precision > 0);
2800 0                 minNDigits = precision;
2801                 /* Fall through */
2802             case DTOSTR_STANDARD_EXPONENTIAL:
2803 0                 exponentialNotation = JS_TRUE;
2804 0                 break;
2805
2806             case DTOSTR_PRECISION:
2807 0                 JS_ASSERT(precision > 0);
2808 0                 minNDigits = precision;
2809 0                 if (decPt < -5 || decPt > precision)
2810 0                     exponentialNotation = JS_TRUE;
2811                 break;
2812         }
2813
2814         /* If the number has fewer than minNDigits, pad it with zeros at the end */
2815 0         if (nDigits < minNDigits) {
2816 0             p = numBegin + minNDigits;
2817 0             nDigits = minNDigits;
2818 0             do {
2819 0                 *numEnd++ = '0';
2820 0             } while (numEnd != p);
2821 0             *numEnd = '\0';
2822         }
2823
2824 0         if (exponentialNotation) {
2825             /* Insert a decimal point if more than one significand digit */
2826 0             if (nDigits != 1) {
2827 0                 numBegin--;
2828 0                 numBegin[0] = numBegin[1];
2829 0                 numBegin[1] = '.';
2830             }
2831 0             JS_snprintf(numEnd, bufferSize - (numEnd - buffer), "e%+d", decPt-1);
2832 0         } else if (decPt != nDigits) {
2833             /* Some kind of a fraction in fixed notation */
2834 0             JS_ASSERT(decPt <= nDigits);
2835 0             if (decPt > 0) {
2836                 /* dd...dd . dd...dd */
2837 0                 p = --numBegin;
2838 0                 do {
2839 0                     *p = p[1];
2840 0                     p++;
2841 0                 } while (--decPt);
2842 0                 *p = '.';
2843             } else {
2844                 /* 0 . 00...00dd...dd */
2845 0                 p = numEnd;
2846 0                 numEnd += 1 - decPt;
2847 0                 q = numEnd;
2848 0                 JS_ASSERT(numEnd < buffer + bufferSize);
2849 0                 *numEnd = '\0';
2850 0                 while (p != numBegin)
2851 0                     *--q = *--p;
2852 0                 for (p = numBegin + 1; p != q; p++)
2853 0                     *p = '0';
2854 0                 *numBegin = '.';
2855 0                 *--numBegin = '0';
2856             }
2857         }
2858     }
2859
2860     /* If negative and neither -0.0 nor NaN, output a leading '-'. */
2861 111     if (sign &&
2862 0             !(word0(d) == Sign_bit && word1(d) == 0) &&
2863 0             !((word0(d) & Exp_mask) == Exp_mask &&
2864 0               (word1(d) || (word0(d) & Frac_mask)))) {
2865 0         *--numBegin = '-';
2866     }
2867 111     return numBegin;
2868 }
2869
2870
2871 /* Let b = floor(b / divisor), and return the remainder.  b must be nonnegative.
2872  * divisor must be between 1 and 65536.
2873  * This function cannot run out of memory. */
2874 static uint32
2875 divrem(Bigint *b, uint32 divisor)
2876 0 {
2877 0     int32 n = b->wds;
2878 0     uint32 remainder = 0;
2879 0     ULong *bx;
2880 0     ULong *bp;
2881
2882 0     JS_ASSERT(divisor > 0 && divisor <= 65536);
2883
2884 0     if (!n)
2885 0         return 0; /* b is zero */
2886 0     bx = b->x;
2887 0     bp = bx + n;
2888 0     do {
2889 0         ULong a = *--bp;
2890 0         ULong dividend = remainder << 16 | a >> 16;
2891 0         ULong quotientHi = dividend / divisor;
2892 0         ULong quotientLo;
2893
2894 0         remainder = dividend - quotientHi*divisor;
2895 0         JS_ASSERT(quotientHi <= 0xFFFF && remainder < divisor);
2896 0         dividend = remainder << 16 | (a & 0xFFFF);
2897 0         quotientLo = dividend / divisor;
2898 0         remainder = dividend - quotientLo*divisor;
2899 0         JS_ASSERT(quotientLo <= 0xFFFF && remainder < divisor);
2900 0         *bp = quotientHi << 16 | quotientLo;
2901 0     } while (bp != bx);
2902     /* Decrease the size of the number if its most significant word is now zero. */
2903 0     if (bx[n-1] == 0)
2904 0         b->wds--;
2905 0     return remainder;
2906 }
2907
2908
2909 /* "-0.0000...(1073 zeros after decimal point)...0001\0" is the longest string that we could produce,
2910  * which occurs when printing -5e-324 in binary.  We could compute a better estimate of the size of
2911  * the output string and malloc fewer bytes depending on d and base, but why bother? */
2912 #define DTOBASESTR_BUFFER_SIZE 1078
2913 #define BASEDIGIT(digit) ((char)(((digit) >= 10) ? 'a' - 10 + (digit) : '0' + (digit)))
2914
2915 JS_FRIEND_API(char *)
2916 JS_dtobasestr(int base, double d)
2917 0 {
2918 0     char *buffer;        /* The output string */
2919 0     char *p;             /* Pointer to current position in the buffer */
2920 0     char *pInt;          /* Pointer to the beginning of the integer part of the string */
2921 0     char *q;
2922 0     uint32 digit;
2923 0     double di;           /* d truncated to an integer */
2924 0     double df;           /* The fractional part of d */
2925
2926 0     JS_ASSERT(base >= 2 && base <= 36);
2927
2928 0     buffer = (char*) malloc(DTOBASESTR_BUFFER_SIZE);
2929 0     if (buffer) {
2930 0         p = buffer;
2931 0         if (d < 0.0
2932 #if defined(XP_WIN) || defined(XP_OS2)
2933             && !((word0(d) & Exp_mask) == Exp_mask && ((word0(d) & Frac_mask) || word1(d))) /* Visual C++ doesn't know how to compare against NaN */
2934 #endif
2935            ) {
2936 0             *p++ = '-';
2937 0             d = -d;
2938         }
2939
2940         /* Check for Infinity and NaN */
2941 0         if ((word0(d) & Exp_mask) == Exp_mask) {
2942 0             strcpy(p, !word1(d) && !(word0(d) & Frac_mask) ? "Infinity" : "NaN");
2943 0             return buffer;
2944         }
2945
2946         /* Locking for Balloc's shared buffers */
2947         ACQUIRE_DTOA_LOCK();
2948
2949         /* Output the integer part of d with the digits in reverse order. */
2950 0         pInt = p;
2951 0         di = fd_floor(d);
2952 0         if (di <= 4294967295.0) {
2953 0             uint32 n = (uint32)di;
2954 0             if (n)
2955 0                 do {
2956 0                     uint32 m = n / base;
2957 0                     digit = n - m*base;
2958 0                     n = m;
2959 0                     JS_ASSERT(digit < (uint32)base);
2960 0                     *p++ = BASEDIGIT(digit);
2961 0                 } while (n);
2962 0             else *p++ = '0';
2963         } else {
2964 0             int32 e;
2965 0             int32 bits;  /* Number of significant bits in di; not used. */
2966 0             Bigint *b = d2b(di, &e, &bits);
2967 0             if (!b)
2968 0                 goto nomem1;
2969 0             b = lshift(b, e);
2970 0             if (!b) {
2971               nomem1:
2972 0                 Bfree(b);
2973 0                 return NULL;
2974             }
2975 0             do {
2976 0                 digit = divrem(b, base);
2977 0                 JS_ASSERT(digit < (uint32)base);
2978 0                 *p++ = BASEDIGIT(digit);
2979 0             } while (b->wds);
2980 0             Bfree(b);
2981         }
2982         /* Reverse the digits of the integer part of d. */
2983 0         q = p-1;
2984 0         while (q > pInt) {
2985 0             char ch = *pInt;
2986 0             *pInt++ = *q;
2987 0             *q-- = ch;
2988         }
2989
2990 0         df = d - di;
2991 0         if (df != 0.0) {
2992             /* We have a fraction. */
2993 0             int32 e, bbits, s2, done;
2994 0             Bigint *b, *s, *mlo, *mhi;
2995
2996 0             b = s = mlo = mhi = NULL;
2997
2998 0             *p++ = '.';
2999 0             b = d2b(df, &e, &bbits);
3000 0             if (!b) {
3001               nomem2:
3002 0                 Bfree(b);
3003 0                 Bfree(s);
3004 0                 if (mlo != mhi)
3005 0                     Bfree(mlo);
3006 0                 Bfree(mhi);
3007 0                 return NULL;
3008             }
3009 0             JS_ASSERT(e < 0);
3010             /* At this point df = b * 2^e.  e must be less than zero because 0 < df < 1. */
3011
3012 0             s2 = -(int32)(word0(d) >> Exp_shift1 & Exp_mask>>Exp_shift1);
3013 #ifndef Sudden_Underflow
3014 0             if (!s2)
3015 0                 s2 = -1;
3016 #endif
3017 0             s2 += Bias + P;
3018             /* 1/2^s2 = (nextDouble(d) - d)/2 */
3019 0             JS_ASSERT(-s2 < e);
3020 0             mlo = i2b(1);
3021 0             if (!mlo)
3022 0                 goto nomem2;
3023 0             mhi = mlo;
3024 0             if (!word1(d) && !(word0(d) & Bndry_mask)
3025 #ifndef Sudden_Underflow
3026 0                 && word0(d) & (Exp_mask & Exp_mask << 1)
3027 #endif
3028                 ) {
3029                 /* The special case.  Here we want to be within a quarter of the last input
3030                    significant digit instead of one half of it when the output string's value is less than d.  */
3031 0                 s2 += Log2P;
3032 0                 mhi = i2b(1<<Log2P);
3033 0                 if (!mhi)
3034 0                     goto nomem2;
3035             }
3036 0             b = lshift(b, e + s2);
3037 0             if (!b)
3038 0                 goto nomem2;
3039 0             s = i2b(1);
3040 0             if (!s)
3041 0                 goto nomem2;
3042 0             s = lshift(s, s2);
3043 0             if (!s)
3044 0                 goto nomem2;
3045             /* At this point we have the following:
3046              *   s = 2^s2;
3047              *   1 > df = b/2^s2 > 0;
3048              *   (d - prevDouble(d))/2 = mlo/2^s2;
3049              *   (nextDouble(d) - d)/2 = mhi/2^s2. */
3050
3051 0             done = JS_FALSE;
3052 0             do {
3053 0                 int32 j, j1;
3054 0                 Bigint *delta;
3055
3056 0                 b = multadd(b, base, 0);
3057 0                 if (!b)
3058 0                     goto nomem2;
3059 0                 digit = quorem2(b, s2);
3060 0                 if (mlo == mhi) {
3061 0                     mlo = mhi = multadd(mlo, base, 0);
3062 0                     if (!mhi)
3063 0                         goto nomem2;
3064                 }
3065                 else {
3066 0                     mlo = multadd(mlo, base, 0);
3067 0                     if (!mlo)
3068 0                         goto nomem2;
3069 0                     mhi = multadd(mhi, base, 0);
3070 0                     if (!mhi)
3071 0                         goto nomem2;
3072                 }
3073
3074                 /* Do we yet have the shortest string that will round to d? */
3075 0                 j = cmp(b, mlo);
3076                 /* j is b/2^s2 compared with mlo/2^s2. */
3077 0                 delta = diff(s, mhi);
3078 0                 if (!delta)
3079 0                     goto nomem2;
3080 0                 j1 = delta->sign ? 1 : cmp(b, delta);
3081 0                 Bfree(delta);
3082                 /* j1 is b/2^s2 compared with 1 - mhi/2^s2. */
3083
3084 #ifndef ROUND_BIASED
3085 0                 if (j1 == 0 && !(word1(d) & 1)) {
3086 0                     if (j > 0)
3087 0                         digit++;
3088 0                     done = JS_TRUE;
3089                 } else
3090 #endif
3091 0                 if (j < 0 || (j == 0
3092 #ifndef ROUND_BIASED
3093 0                     && !(word1(d) & 1)
3094 #endif
3095                     )) {
3096 0                     if (j1 > 0) {
3097                         /* Either dig or dig+1 would work here as the least significant digit.
3098                            Use whichever would produce an output value closer to d. */
3099 0                         b = lshift(b, 1);
3100 0                         if (!b)
3101 0                             goto nomem2;
3102 0                         j1 = cmp(b, s);
3103 0                         if (j1 > 0) /* The even test (|| (j1 == 0 && (digit & 1))) is not here because it messes up odd base output
3104                                      * such as 3.5 in base 3.  */
3105 0                             digit++;
3106                     }
3107 0                     done = JS_TRUE;
3108 0                 } else if (j1 > 0) {
3109 0                     digit++;
3110 0                     done = JS_TRUE;
3111                 }
3112 0                 JS_ASSERT(digit < (uint32)base);
3113 0                 *p++ = BASEDIGIT(digit);
3114 0             } while (!done);
3115 0             Bfree(b);
3116 0             Bfree(s);
3117 0             if (mlo != mhi)
3118 0                 Bfree(mlo);
3119 0             Bfree(mhi);
3120         }
3121 0         JS_ASSERT(p < buffer + DTOBASESTR_BUFFER_SIZE);
3122 0         *p = '\0';
3123         RELEASE_DTOA_LOCK();
3124     }
3125 0     return buffer;