Back to index

lightning-sunbird  0.9+nobinonly
jsdtoa.c
Go to the documentation of this file.
00001 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
00002  *
00003  * ***** BEGIN LICENSE BLOCK *****
00004  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
00005  *
00006  * The contents of this file are subject to the Mozilla Public License Version
00007  * 1.1 (the "License"); you may not use this file except in compliance with
00008  * the License. You may obtain a copy of the License at
00009  * http://www.mozilla.org/MPL/
00010  *
00011  * Software distributed under the License is distributed on an "AS IS" basis,
00012  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
00013  * for the specific language governing rights and limitations under the
00014  * License.
00015  *
00016  * The Original Code is Mozilla Communicator client code, released
00017  * March 31, 1998.
00018  *
00019  * The Initial Developer of the Original Code is
00020  * Netscape Communications Corporation.
00021  * Portions created by the Initial Developer are Copyright (C) 1998
00022  * the Initial Developer. All Rights Reserved.
00023  *
00024  * Contributor(s):
00025  *
00026  * Alternatively, the contents of this file may be used under the terms of
00027  * either of the GNU General Public License Version 2 or later (the "GPL"),
00028  * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
00029  * in which case the provisions of the GPL or the LGPL are applicable instead
00030  * of those above. If you wish to allow use of your version of this file only
00031  * under the terms of either the GPL or the LGPL, and not to allow others to
00032  * use your version of this file under the terms of the MPL, indicate your
00033  * decision by deleting the provisions above and replace them with the notice
00034  * and other provisions required by the GPL or the LGPL. If you do not delete
00035  * the provisions above, a recipient may use your version of this file under
00036  * the terms of any one of the MPL, the GPL or the LGPL.
00037  *
00038  * ***** END LICENSE BLOCK ***** */
00039 
00040 /*
00041  * Portable double to alphanumeric string and back converters.
00042  */
00043 #include "jsstddef.h"
00044 #include "jslibmath.h"
00045 #include "jstypes.h"
00046 #include "jsdtoa.h"
00047 #include "jsprf.h"
00048 #include "jsutil.h" /* Added by JSIFY */
00049 #include "jspubtd.h"
00050 #include "jsnum.h"
00051 
00052 #ifdef JS_THREADSAFE
00053 #include "prlock.h"
00054 #endif
00055 
00056 /****************************************************************
00057  *
00058  * The author of this software is David M. Gay.
00059  *
00060  * Copyright (c) 1991 by Lucent Technologies.
00061  *
00062  * Permission to use, copy, modify, and distribute this software for any
00063  * purpose without fee is hereby granted, provided that this entire notice
00064  * is included in all copies of any software which is or includes a copy
00065  * or modification of this software and in all copies of the supporting
00066  * documentation for such software.
00067  *
00068  * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
00069  * WARRANTY.  IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
00070  * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
00071  * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
00072  *
00073  ***************************************************************/
00074 
00075 /* Please send bug reports to
00076     David M. Gay
00077     Bell Laboratories, Room 2C-463
00078     600 Mountain Avenue
00079     Murray Hill, NJ 07974-0636
00080     U.S.A.
00081     dmg@bell-labs.com
00082  */
00083 
00084 /* On a machine with IEEE extended-precision registers, it is
00085  * necessary to specify double-precision (53-bit) rounding precision
00086  * before invoking strtod or dtoa.  If the machine uses (the equivalent
00087  * of) Intel 80x87 arithmetic, the call
00088  *  _control87(PC_53, MCW_PC);
00089  * does this with many compilers.  Whether this or another call is
00090  * appropriate depends on the compiler; for this to work, it may be
00091  * necessary to #include "float.h" or another system-dependent header
00092  * file.
00093  */
00094 
00095 /* strtod for IEEE-arithmetic machines.
00096  *
00097  * This strtod returns a nearest machine number to the input decimal
00098  * string (or sets err to JS_DTOA_ERANGE or JS_DTOA_ENOMEM).  With IEEE
00099  * arithmetic, ties are broken by the IEEE round-even rule.  Otherwise
00100  * ties are broken by biased rounding (add half and chop).
00101  *
00102  * Inspired loosely by William D. Clinger's paper "How to Read Floating
00103  * Point Numbers Accurately" [Proc. ACM SIGPLAN '90, pp. 92-101].
00104  *
00105  * Modifications:
00106  *
00107  *  1. We only require IEEE double-precision
00108  *      arithmetic (not IEEE double-extended).
00109  *  2. We get by with floating-point arithmetic in a case that
00110  *      Clinger missed -- when we're computing d * 10^n
00111  *      for a small integer d and the integer n is not too
00112  *      much larger than 22 (the maximum integer k for which
00113  *      we can represent 10^k exactly), we may be able to
00114  *      compute (d*10^k) * 10^(e-k) with just one roundoff.
00115  *  3. Rather than a bit-at-a-time adjustment of the binary
00116  *      result in the hard case, we use floating-point
00117  *      arithmetic to determine the adjustment to within
00118  *      one bit; only in really hard cases do we need to
00119  *      compute a second residual.
00120  *  4. Because of 3., we don't need a large table of powers of 10
00121  *      for ten-to-e (just some small tables, e.g. of 10^k
00122  *      for 0 <= k <= 22).
00123  */
00124 
00125 /*
00126  * #define IEEE_8087 for IEEE-arithmetic machines where the least
00127  *  significant byte has the lowest address.
00128  * #define IEEE_MC68k for IEEE-arithmetic machines where the most
00129  *  significant byte has the lowest address.
00130  * #define Long int on machines with 32-bit ints and 64-bit longs.
00131  * #define Sudden_Underflow for IEEE-format machines without gradual
00132  *  underflow (i.e., that flush to zero on underflow).
00133  * #define No_leftright to omit left-right logic in fast floating-point
00134  *  computation of js_dtoa.
00135  * #define Check_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3.
00136  * #define RND_PRODQUOT to use rnd_prod and rnd_quot (assembly routines
00137  *  that use extended-precision instructions to compute rounded
00138  *  products and quotients) with IBM.
00139  * #define ROUND_BIASED for IEEE-format with biased rounding.
00140  * #define Inaccurate_Divide for IEEE-format with correctly rounded
00141  *  products but inaccurate quotients, e.g., for Intel i860.
00142  * #define JS_HAVE_LONG_LONG on machines that have a "long long"
00143  *  integer type (of >= 64 bits).  If long long is available and the name is
00144  *  something other than "long long", #define Llong to be the name,
00145  *  and if "unsigned Llong" does not work as an unsigned version of
00146  *  Llong, #define #ULLong to be the corresponding unsigned type.
00147  * #define Bad_float_h if your system lacks a float.h or if it does not
00148  *  define some or all of DBL_DIG, DBL_MAX_10_EXP, DBL_MAX_EXP,
00149  *  FLT_RADIX, FLT_ROUNDS, and DBL_MAX.
00150  * #define MALLOC your_malloc, where your_malloc(n) acts like malloc(n)
00151  *  if memory is available and otherwise does something you deem
00152  *  appropriate.  If MALLOC is undefined, malloc will be invoked
00153  *  directly -- and assumed always to succeed.
00154  * #define Omit_Private_Memory to omit logic (added Jan. 1998) for making
00155  *  memory allocations from a private pool of memory when possible.
00156  *  When used, the private pool is PRIVATE_MEM bytes long: 2000 bytes,
00157  *  unless #defined to be a different length.  This default length
00158  *  suffices to get rid of MALLOC calls except for unusual cases,
00159  *  such as decimal-to-binary conversion of a very long string of
00160  *  digits.
00161  * #define INFNAN_CHECK on IEEE systems to cause strtod to check for
00162  *  Infinity and NaN (case insensitively).  On some systems (e.g.,
00163  *  some HP systems), it may be necessary to #define NAN_WORD0
00164  *  appropriately -- to the most significant word of a quiet NaN.
00165  *  (On HP Series 700/800 machines, -DNAN_WORD0=0x7ff40000 works.)
00166  * #define MULTIPLE_THREADS if the system offers preemptively scheduled
00167  *  multiple threads.  In this case, you must provide (or suitably
00168  *  #define) two locks, acquired by ACQUIRE_DTOA_LOCK() and released
00169  *  by RELEASE_DTOA_LOCK().  (The second lock, accessed
00170  *  in pow5mult, ensures lazy evaluation of only one copy of high
00171  *  powers of 5; omitting this lock would introduce a small
00172  *  probability of wasting memory, but would otherwise be harmless.)
00173  *  You must also invoke freedtoa(s) to free the value s returned by
00174  *  dtoa.  You may do so whether or not MULTIPLE_THREADS is #defined.
00175  * #define NO_IEEE_Scale to disable new (Feb. 1997) logic in strtod that
00176  *  avoids underflows on inputs whose result does not underflow.
00177  */
00178 #ifdef IS_LITTLE_ENDIAN
00179 #define IEEE_8087
00180 #else
00181 #define IEEE_MC68k
00182 #endif
00183 
00184 #ifndef Long
00185 #define Long int32
00186 #endif
00187 
00188 #ifndef ULong
00189 #define ULong uint32
00190 #endif
00191 
00192 #define Bug(errorMessageString) JS_ASSERT(!errorMessageString)
00193 
00194 #include "stdlib.h"
00195 #include "string.h"
00196 
00197 #ifdef MALLOC
00198 extern void *MALLOC(size_t);
00199 #else
00200 #define MALLOC malloc
00201 #endif
00202 
00203 #define Omit_Private_Memory
00204 /* Private memory currently doesn't work with JS_THREADSAFE */
00205 #ifndef Omit_Private_Memory
00206 #ifndef PRIVATE_MEM
00207 #define PRIVATE_MEM 2000
00208 #endif
00209 #define PRIVATE_mem ((PRIVATE_MEM+sizeof(double)-1)/sizeof(double))
00210 static double private_mem[PRIVATE_mem], *pmem_next = private_mem;
00211 #endif
00212 
00213 #ifdef Bad_float_h
00214 #undef __STDC__
00215 
00216 #define DBL_DIG 15
00217 #define DBL_MAX_10_EXP 308
00218 #define DBL_MAX_EXP 1024
00219 #define FLT_RADIX 2
00220 #define FLT_ROUNDS 1
00221 #define DBL_MAX 1.7976931348623157e+308
00222 
00223 
00224 
00225 #ifndef LONG_MAX
00226 #define LONG_MAX 2147483647
00227 #endif
00228 
00229 #else /* ifndef Bad_float_h */
00230 #include "float.h"
00231 #endif /* Bad_float_h */
00232 
00233 #ifndef __MATH_H__
00234 #include "math.h"
00235 #endif
00236 
00237 #ifndef CONST
00238 #define CONST const
00239 #endif
00240 
00241 #if defined(IEEE_8087) + defined(IEEE_MC68k) != 1
00242 Exactly one of IEEE_8087 or IEEE_MC68k should be defined.
00243 #endif
00244 
00245 #define word0(x)        JSDOUBLE_HI32(x)
00246 #define set_word0(x, y) JSDOUBLE_SET_HI32(x, y)
00247 #define word1(x)        JSDOUBLE_LO32(x)
00248 #define set_word1(x, y) JSDOUBLE_SET_LO32(x, y)
00249 
00250 #define Storeinc(a,b,c) (*(a)++ = (b) << 16 | (c) & 0xffff)
00251 
00252 /* #define P DBL_MANT_DIG */
00253 /* Ten_pmax = floor(P*log(2)/log(5)) */
00254 /* Bletch = (highest power of 2 < DBL_MAX_10_EXP) / 16 */
00255 /* Quick_max = floor((P-1)*log(FLT_RADIX)/log(10) - 1) */
00256 /* Int_max = floor(P*log(FLT_RADIX)/log(10) - 1) */
00257 
00258 #define Exp_shift  20
00259 #define Exp_shift1 20
00260 #define Exp_msk1    0x100000
00261 #define Exp_msk11   0x100000
00262 #define Exp_mask  0x7ff00000
00263 #define P 53
00264 #define Bias 1023
00265 #define Emin (-1022)
00266 #define Exp_1  0x3ff00000
00267 #define Exp_11 0x3ff00000
00268 #define Ebits 11
00269 #define Frac_mask  0xfffff
00270 #define Frac_mask1 0xfffff
00271 #define Ten_pmax 22
00272 #define Bletch 0x10
00273 #define Bndry_mask  0xfffff
00274 #define Bndry_mask1 0xfffff
00275 #define LSB 1
00276 #define Sign_bit 0x80000000
00277 #define Log2P 1
00278 #define Tiny0 0
00279 #define Tiny1 1
00280 #define Quick_max 14
00281 #define Int_max 14
00282 #define Infinite(x) (word0(x) == 0x7ff00000) /* sufficient test for here */
00283 #ifndef NO_IEEE_Scale
00284 #define Avoid_Underflow
00285 #endif
00286 
00287 
00288 
00289 #ifdef RND_PRODQUOT
00290 #define rounded_product(a,b) a = rnd_prod(a, b)
00291 #define rounded_quotient(a,b) a = rnd_quot(a, b)
00292 extern double rnd_prod(double, double), rnd_quot(double, double);
00293 #else
00294 #define rounded_product(a,b) a *= b
00295 #define rounded_quotient(a,b) a /= b
00296 #endif
00297 
00298 #define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
00299 #define Big1 0xffffffff
00300 
00301 #ifndef JS_HAVE_LONG_LONG
00302 #undef ULLong
00303 #else   /* long long available */
00304 #ifndef Llong
00305 #define Llong JSInt64
00306 #endif
00307 #ifndef ULLong
00308 #define ULLong JSUint64
00309 #endif
00310 #endif /* JS_HAVE_LONG_LONG */
00311 
00312 #ifdef JS_THREADSAFE
00313 #define MULTIPLE_THREADS
00314 static PRLock *freelist_lock;
00315 #define ACQUIRE_DTOA_LOCK()                                                   \
00316     JS_BEGIN_MACRO                                                            \
00317         if (!initialized)                                                     \
00318             InitDtoa();                                                       \
00319         PR_Lock(freelist_lock);                                               \
00320     JS_END_MACRO
00321 #define RELEASE_DTOA_LOCK() PR_Unlock(freelist_lock)
00322 #else
00323 #undef MULTIPLE_THREADS
00324 #define ACQUIRE_DTOA_LOCK()   /*nothing*/
00325 #define RELEASE_DTOA_LOCK()   /*nothing*/
00326 #endif
00327 
00328 #define Kmax 15
00329 
00330 struct Bigint {
00331     struct Bigint *next;  /* Free list link */
00332     int32 k;              /* lg2(maxwds) */
00333     int32 maxwds;         /* Number of words allocated for x */
00334     int32 sign;           /* Zero if positive, 1 if negative.  Ignored by most Bigint routines! */
00335     int32 wds;            /* Actual number of words.  If value is nonzero, the most significant word must be nonzero. */
00336     ULong x[1];           /* wds words of number in little endian order */
00337 };
00338 
00339 #ifdef ENABLE_OOM_TESTING
00340 /* Out-of-memory testing.  Use a good testcase (over and over) and then use
00341  * these routines to cause a memory failure on every possible Balloc allocation,
00342  * to make sure that all out-of-memory paths can be followed.  See bug 14044.
00343  */
00344 
00345 static int allocationNum;               /* which allocation is next? */
00346 static int desiredFailure;              /* which allocation should fail? */
00347 
00354 JS_PUBLIC_API(void)
00355 js_BigintTestingReset(int newFailure)
00356 {
00357     allocationNum = 0;
00358     desiredFailure = newFailure;
00359 }
00360 
00367 JS_PUBLIC_API(int)
00368 js_BigintTestingWhere()
00369 {
00370     return allocationNum;
00371 }
00372 
00373 
00374 /*
00375  * So here's what you do: Set up a fantastic test case that exercises the
00376  * elements of the code you wish.  Set the failure point at 0 and run the test,
00377  * then get the allocation position.  This number is the number of allocations
00378  * your test makes.  Now loop from 1 to that number, setting the failure point
00379  * at each loop count, and run the test over and over, causing failures at each
00380  * step.  Any memory failure *should* cause a Out-Of-Memory exception; if it
00381  * doesn't, then there's still an error here.
00382  */
00383 #endif
00384 
00385 typedef struct Bigint Bigint;
00386 
00387 static Bigint *freelist[Kmax+1];
00388 
00389 /*
00390  * Allocate a Bigint with 2^k words.
00391  * This is not threadsafe. The caller must use thread locks
00392  */
00393 static Bigint *Balloc(int32 k)
00394 {
00395     int32 x;
00396     Bigint *rv;
00397 #ifndef Omit_Private_Memory
00398     uint32 len;
00399 #endif
00400 
00401 #ifdef ENABLE_OOM_TESTING
00402     if (++allocationNum == desiredFailure) {
00403         printf("Forced Failing Allocation number %d\n", allocationNum);
00404         return NULL;
00405     }
00406 #endif
00407 
00408     if ((rv = freelist[k]) != NULL)
00409         freelist[k] = rv->next;
00410     if (rv == NULL) {
00411         x = 1 << k;
00412 #ifdef Omit_Private_Memory
00413         rv = (Bigint *)MALLOC(sizeof(Bigint) + (x-1)*sizeof(ULong));
00414 #else
00415         len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)
00416             /sizeof(double);
00417         if (pmem_next - private_mem + len <= PRIVATE_mem) {
00418             rv = (Bigint*)pmem_next;
00419             pmem_next += len;
00420             }
00421         else
00422             rv = (Bigint*)MALLOC(len*sizeof(double));
00423 #endif
00424         if (!rv)
00425             return NULL;
00426         rv->k = k;
00427         rv->maxwds = x;
00428     }
00429     rv->sign = rv->wds = 0;
00430     return rv;
00431 }
00432 
00433 static void Bfree(Bigint *v)
00434 {
00435     if (v) {
00436         v->next = freelist[v->k];
00437         freelist[v->k] = v;
00438     }
00439 }
00440 
00441 #define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign, \
00442                           y->wds*sizeof(Long) + 2*sizeof(int32))
00443 
00444 /* Return b*m + a.  Deallocate the old b.  Both a and m must be between 0 and
00445  * 65535 inclusive.  NOTE: old b is deallocated on memory failure.
00446  */
00447 static Bigint *multadd(Bigint *b, int32 m, int32 a)
00448 {
00449     int32 i, wds;
00450 #ifdef ULLong
00451     ULong *x;
00452     ULLong carry, y;
00453 #else
00454     ULong carry, *x, y;
00455     ULong xi, z;
00456 #endif
00457     Bigint *b1;
00458 
00459 #ifdef ENABLE_OOM_TESTING
00460     if (++allocationNum == desiredFailure) {
00461         /* Faux allocation, because I'm not getting all of the failure paths
00462          * without it.
00463          */
00464         printf("Forced Failing Allocation number %d\n", allocationNum);
00465         Bfree(b);
00466         return NULL;
00467     }
00468 #endif
00469 
00470     wds = b->wds;
00471     x = b->x;
00472     i = 0;
00473     carry = a;
00474     do {
00475 #ifdef ULLong
00476         y = *x * (ULLong)m + carry;
00477         carry = y >> 32;
00478         *x++ = (ULong)(y & 0xffffffffUL);
00479 #else
00480         xi = *x;
00481         y = (xi & 0xffff) * m + carry;
00482         z = (xi >> 16) * m + (y >> 16);
00483         carry = z >> 16;
00484         *x++ = (z << 16) + (y & 0xffff);
00485 #endif
00486     }
00487     while(++i < wds);
00488     if (carry) {
00489         if (wds >= b->maxwds) {
00490             b1 = Balloc(b->k+1);
00491             if (!b1) {
00492                 Bfree(b);
00493                 return NULL;
00494             }
00495             Bcopy(b1, b);
00496             Bfree(b);
00497             b = b1;
00498         }
00499         b->x[wds++] = (ULong)carry;
00500         b->wds = wds;
00501     }
00502     return b;
00503 }
00504 
00505 static Bigint *s2b(CONST char *s, int32 nd0, int32 nd, ULong y9)
00506 {
00507     Bigint *b;
00508     int32 i, k;
00509     Long x, y;
00510 
00511     x = (nd + 8) / 9;
00512     for(k = 0, y = 1; x > y; y <<= 1, k++) ;
00513     b = Balloc(k);
00514     if (!b)
00515         return NULL;
00516     b->x[0] = y9;
00517     b->wds = 1;
00518 
00519     i = 9;
00520     if (9 < nd0) {
00521         s += 9;
00522         do {
00523             b = multadd(b, 10, *s++ - '0');
00524             if (!b)
00525                 return NULL;
00526         } while(++i < nd0);
00527         s++;
00528     }
00529     else
00530         s += 10;
00531     for(; i < nd; i++) {
00532         b = multadd(b, 10, *s++ - '0');
00533         if (!b)
00534             return NULL;
00535     }
00536     return b;
00537 }
00538 
00539 
00540 /* Return the number (0 through 32) of most significant zero bits in x. */
00541 static int32 hi0bits(register ULong x)
00542 {
00543     register int32 k = 0;
00544 
00545     if (!(x & 0xffff0000)) {
00546         k = 16;
00547         x <<= 16;
00548     }
00549     if (!(x & 0xff000000)) {
00550         k += 8;
00551         x <<= 8;
00552     }
00553     if (!(x & 0xf0000000)) {
00554         k += 4;
00555         x <<= 4;
00556     }
00557     if (!(x & 0xc0000000)) {
00558         k += 2;
00559         x <<= 2;
00560     }
00561     if (!(x & 0x80000000)) {
00562         k++;
00563         if (!(x & 0x40000000))
00564             return 32;
00565     }
00566     return k;
00567 }
00568 
00569 
00570 /* Return the number (0 through 32) of least significant zero bits in y.
00571  * Also shift y to the right past these 0 through 32 zeros so that y's
00572  * least significant bit will be set unless y was originally zero. */
00573 static int32 lo0bits(ULong *y)
00574 {
00575     register int32 k;
00576     register ULong x = *y;
00577 
00578     if (x & 7) {
00579         if (x & 1)
00580             return 0;
00581         if (x & 2) {
00582             *y = x >> 1;
00583             return 1;
00584         }
00585         *y = x >> 2;
00586         return 2;
00587     }
00588     k = 0;
00589     if (!(x & 0xffff)) {
00590         k = 16;
00591         x >>= 16;
00592     }
00593     if (!(x & 0xff)) {
00594         k += 8;
00595         x >>= 8;
00596     }
00597     if (!(x & 0xf)) {
00598         k += 4;
00599         x >>= 4;
00600     }
00601     if (!(x & 0x3)) {
00602         k += 2;
00603         x >>= 2;
00604     }
00605     if (!(x & 1)) {
00606         k++;
00607         x >>= 1;
00608         if (!x & 1)
00609             return 32;
00610     }
00611     *y = x;
00612     return k;
00613 }
00614 
00615 /* Return a new Bigint with the given integer value, which must be nonnegative. */
00616 static Bigint *i2b(int32 i)
00617 {
00618     Bigint *b;
00619 
00620     b = Balloc(1);
00621     if (!b)
00622         return NULL;
00623     b->x[0] = i;
00624     b->wds = 1;
00625     return b;
00626 }
00627 
00628 /* Return a newly allocated product of a and b. */
00629 static Bigint *mult(CONST Bigint *a, CONST Bigint *b)
00630 {
00631     CONST Bigint *t;
00632     Bigint *c;
00633     int32 k, wa, wb, wc;
00634     ULong y;
00635     ULong *xc, *xc0, *xce;
00636     CONST ULong *x, *xa, *xae, *xb, *xbe;
00637 #ifdef ULLong
00638     ULLong carry, z;
00639 #else
00640     ULong carry, z;
00641     ULong z2;
00642 #endif
00643 
00644     if (a->wds < b->wds) {
00645         t = a;
00646         a = b;
00647         b = t;
00648     }
00649     k = a->k;
00650     wa = a->wds;
00651     wb = b->wds;
00652     wc = wa + wb;
00653     if (wc > a->maxwds)
00654         k++;
00655     c = Balloc(k);
00656     if (!c)
00657         return NULL;
00658     for(xc = c->x, xce = xc + wc; xc < xce; xc++)
00659         *xc = 0;
00660     xa = a->x;
00661     xae = xa + wa;
00662     xb = b->x;
00663     xbe = xb + wb;
00664     xc0 = c->x;
00665 #ifdef ULLong
00666     for(; xb < xbe; xc0++) {
00667         if ((y = *xb++) != 0) {
00668             x = xa;
00669             xc = xc0;
00670             carry = 0;
00671             do {
00672                 z = *x++ * (ULLong)y + *xc + carry;
00673                 carry = z >> 32;
00674                 *xc++ = (ULong)(z & 0xffffffffUL);
00675                 }
00676                 while(x < xae);
00677             *xc = (ULong)carry;
00678             }
00679         }
00680 #else
00681     for(; xb < xbe; xb++, xc0++) {
00682         if ((y = *xb & 0xffff) != 0) {
00683             x = xa;
00684             xc = xc0;
00685             carry = 0;
00686             do {
00687                 z = (*x & 0xffff) * y + (*xc & 0xffff) + carry;
00688                 carry = z >> 16;
00689                 z2 = (*x++ >> 16) * y + (*xc >> 16) + carry;
00690                 carry = z2 >> 16;
00691                 Storeinc(xc, z2, z);
00692             }
00693             while(x < xae);
00694             *xc = carry;
00695         }
00696         if ((y = *xb >> 16) != 0) {
00697             x = xa;
00698             xc = xc0;
00699             carry = 0;
00700             z2 = *xc;
00701             do {
00702                 z = (*x & 0xffff) * y + (*xc >> 16) + carry;
00703                 carry = z >> 16;
00704                 Storeinc(xc, z, z2);
00705                 z2 = (*x++ >> 16) * y + (*xc & 0xffff) + carry;
00706                 carry = z2 >> 16;
00707             }
00708             while(x < xae);
00709             *xc = z2;
00710         }
00711     }
00712 #endif
00713     for(xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ;
00714     c->wds = wc;
00715     return c;
00716 }
00717 
00718 /*
00719  * 'p5s' points to a linked list of Bigints that are powers of 5.
00720  * This list grows on demand, and it can only grow: it won't change
00721  * in any other way.  So if we read 'p5s' or the 'next' field of
00722  * some Bigint on the list, and it is not NULL, we know it won't
00723  * change to NULL or some other value.  Only when the value of
00724  * 'p5s' or 'next' is NULL do we need to acquire the lock and add
00725  * a new Bigint to the list.
00726  */
00727 
00728 static Bigint *p5s;
00729 
00730 #ifdef JS_THREADSAFE
00731 static PRLock *p5s_lock;
00732 #endif
00733 
00734 /* Return b * 5^k.  Deallocate the old b.  k must be nonnegative. */
00735 /* NOTE: old b is deallocated on memory failure. */
00736 static Bigint *pow5mult(Bigint *b, int32 k)
00737 {
00738     Bigint *b1, *p5, *p51;
00739     int32 i;
00740     static CONST int32 p05[3] = { 5, 25, 125 };
00741 
00742     if ((i = k & 3) != 0) {
00743         b = multadd(b, p05[i-1], 0);
00744         if (!b)
00745             return NULL;
00746     }
00747 
00748     if (!(k >>= 2))
00749         return b;
00750     if (!(p5 = p5s)) {
00751 #ifdef JS_THREADSAFE
00752         /*
00753          * We take great care to not call i2b() and Bfree()
00754          * while holding the lock.
00755          */
00756         Bigint *wasted_effort = NULL;
00757         p5 = i2b(625);
00758         if (!p5) {
00759             Bfree(b);
00760             return NULL;
00761         }
00762         /* lock and check again */
00763         PR_Lock(p5s_lock);
00764         if (!p5s) {
00765             /* first time */
00766             p5s = p5;
00767             p5->next = 0;
00768         } else {
00769             /* some other thread just beat us */
00770             wasted_effort = p5;
00771             p5 = p5s;
00772         }
00773         PR_Unlock(p5s_lock);
00774         if (wasted_effort) {
00775             Bfree(wasted_effort);
00776         }
00777 #else
00778         /* first time */
00779         p5 = p5s = i2b(625);
00780         if (!p5) {
00781             Bfree(b);
00782             return NULL;
00783         }
00784         p5->next = 0;
00785 #endif
00786     }
00787     for(;;) {
00788         if (k & 1) {
00789             b1 = mult(b, p5);
00790             Bfree(b);
00791             if (!b1)
00792                 return NULL;
00793             b = b1;
00794         }
00795         if (!(k >>= 1))
00796             break;
00797         if (!(p51 = p5->next)) {
00798 #ifdef JS_THREADSAFE
00799             Bigint *wasted_effort = NULL;
00800             p51 = mult(p5, p5);
00801             if (!p51) {
00802                 Bfree(b);
00803                 return NULL;
00804             }
00805             PR_Lock(p5s_lock);
00806             if (!p5->next) {
00807                 p5->next = p51;
00808                 p51->next = 0;
00809             } else {
00810                 wasted_effort = p51;
00811                 p51 = p5->next;
00812             }
00813             PR_Unlock(p5s_lock);
00814             if (wasted_effort) {
00815                 Bfree(wasted_effort);
00816             }
00817 #else
00818             p51 = mult(p5,p5);
00819             if (!p51) {
00820                 Bfree(b);
00821                 return NULL;
00822             }
00823             p51->next = 0;
00824             p5->next = p51;
00825 #endif
00826         }
00827         p5 = p51;
00828     }
00829     return b;
00830 }
00831 
00832 /* Return b * 2^k.  Deallocate the old b.  k must be nonnegative.
00833  * NOTE: on memory failure, old b is deallocated. */
00834 static Bigint *lshift(Bigint *b, int32 k)
00835 {
00836     int32 i, k1, n, n1;
00837     Bigint *b1;
00838     ULong *x, *x1, *xe, z;
00839 
00840     n = k >> 5;
00841     k1 = b->k;
00842     n1 = n + b->wds + 1;
00843     for(i = b->maxwds; n1 > i; i <<= 1)
00844         k1++;
00845     b1 = Balloc(k1);
00846     if (!b1)
00847         goto done;
00848     x1 = b1->x;
00849     for(i = 0; i < n; i++)
00850         *x1++ = 0;
00851     x = b->x;
00852     xe = x + b->wds;
00853     if (k &= 0x1f) {
00854         k1 = 32 - k;
00855         z = 0;
00856         do {
00857             *x1++ = *x << k | z;
00858             z = *x++ >> k1;
00859         }
00860         while(x < xe);
00861         if ((*x1 = z) != 0)
00862             ++n1;
00863     }
00864     else do
00865         *x1++ = *x++;
00866          while(x < xe);
00867     b1->wds = n1 - 1;
00868 done:
00869     Bfree(b);
00870     return b1;
00871 }
00872 
00873 /* Return -1, 0, or 1 depending on whether a<b, a==b, or a>b, respectively. */
00874 static int32 cmp(Bigint *a, Bigint *b)
00875 {
00876     ULong *xa, *xa0, *xb, *xb0;
00877     int32 i, j;
00878 
00879     i = a->wds;
00880     j = b->wds;
00881 #ifdef DEBUG
00882     if (i > 1 && !a->x[i-1])
00883         Bug("cmp called with a->x[a->wds-1] == 0");
00884     if (j > 1 && !b->x[j-1])
00885         Bug("cmp called with b->x[b->wds-1] == 0");
00886 #endif
00887     if (i -= j)
00888         return i;
00889     xa0 = a->x;
00890     xa = xa0 + j;
00891     xb0 = b->x;
00892     xb = xb0 + j;
00893     for(;;) {
00894         if (*--xa != *--xb)
00895             return *xa < *xb ? -1 : 1;
00896         if (xa <= xa0)
00897             break;
00898     }
00899     return 0;
00900 }
00901 
00902 static Bigint *diff(Bigint *a, Bigint *b)
00903 {
00904     Bigint *c;
00905     int32 i, wa, wb;
00906     ULong *xa, *xae, *xb, *xbe, *xc;
00907 #ifdef ULLong
00908     ULLong borrow, y;
00909 #else
00910     ULong borrow, y;
00911     ULong z;
00912 #endif
00913 
00914     i = cmp(a,b);
00915     if (!i) {
00916         c = Balloc(0);
00917         if (!c)
00918             return NULL;
00919         c->wds = 1;
00920         c->x[0] = 0;
00921         return c;
00922     }
00923     if (i < 0) {
00924         c = a;
00925         a = b;
00926         b = c;
00927         i = 1;
00928     }
00929     else
00930         i = 0;
00931     c = Balloc(a->k);
00932     if (!c)
00933         return NULL;
00934     c->sign = i;
00935     wa = a->wds;
00936     xa = a->x;
00937     xae = xa + wa;
00938     wb = b->wds;
00939     xb = b->x;
00940     xbe = xb + wb;
00941     xc = c->x;
00942     borrow = 0;
00943 #ifdef ULLong
00944     do {
00945         y = (ULLong)*xa++ - *xb++ - borrow;
00946         borrow = y >> 32 & 1UL;
00947         *xc++ = (ULong)(y & 0xffffffffUL);
00948         }
00949         while(xb < xbe);
00950     while(xa < xae) {
00951         y = *xa++ - borrow;
00952         borrow = y >> 32 & 1UL;
00953         *xc++ = (ULong)(y & 0xffffffffUL);
00954         }
00955 #else
00956     do {
00957         y = (*xa & 0xffff) - (*xb & 0xffff) - borrow;
00958         borrow = (y & 0x10000) >> 16;
00959         z = (*xa++ >> 16) - (*xb++ >> 16) - borrow;
00960         borrow = (z & 0x10000) >> 16;
00961         Storeinc(xc, z, y);
00962         }
00963         while(xb < xbe);
00964     while(xa < xae) {
00965         y = (*xa & 0xffff) - borrow;
00966         borrow = (y & 0x10000) >> 16;
00967         z = (*xa++ >> 16) - borrow;
00968         borrow = (z & 0x10000) >> 16;
00969         Storeinc(xc, z, y);
00970         }
00971 #endif
00972     while(!*--xc)
00973         wa--;
00974     c->wds = wa;
00975     return c;
00976 }
00977 
00978 /* Return the absolute difference between x and the adjacent greater-magnitude double number (ignoring exponent overflows). */
00979 static double ulp(double x)
00980 {
00981     register Long L;
00982     double a = 0;
00983 
00984     L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1;
00985 #ifndef Sudden_Underflow
00986     if (L > 0) {
00987 #endif
00988         set_word0(a, L);
00989         set_word1(a, 0);
00990 #ifndef Sudden_Underflow
00991     }
00992     else {
00993         L = -L >> Exp_shift;
00994         if (L < Exp_shift) {
00995             set_word0(a, 0x80000 >> L);
00996             set_word1(a, 0);
00997         }
00998         else {
00999             set_word0(a, 0);
01000             L -= Exp_shift;
01001             set_word1(a, L >= 31 ? 1 : 1 << (31 - L));
01002         }
01003     }
01004 #endif
01005     return a;
01006 }
01007 
01008 
01009 static double b2d(Bigint *a, int32 *e)
01010 {
01011     ULong *xa, *xa0, w, y, z;
01012     int32 k;
01013     double d = 0;
01014 #define d0 word0(d)
01015 #define d1 word1(d)
01016 #define set_d0(x) set_word0(d, x)
01017 #define set_d1(x) set_word1(d, x)
01018 
01019     xa0 = a->x;
01020     xa = xa0 + a->wds;
01021     y = *--xa;
01022 #ifdef DEBUG
01023     if (!y) Bug("zero y in b2d");
01024 #endif
01025     k = hi0bits(y);
01026     *e = 32 - k;
01027     if (k < Ebits) {
01028         set_d0(Exp_1 | y >> (Ebits - k));
01029         w = xa > xa0 ? *--xa : 0;
01030         set_d1(y << (32-Ebits + k) | w >> (Ebits - k));
01031         goto ret_d;
01032     }
01033     z = xa > xa0 ? *--xa : 0;
01034     if (k -= Ebits) {
01035         set_d0(Exp_1 | y << k | z >> (32 - k));
01036         y = xa > xa0 ? *--xa : 0;
01037         set_d1(z << k | y >> (32 - k));
01038     }
01039     else {
01040         set_d0(Exp_1 | y);
01041         set_d1(z);
01042     }
01043   ret_d:
01044 #undef d0
01045 #undef d1
01046 #undef set_d0
01047 #undef set_d1
01048     return d;
01049 }
01050 
01051 
01052 /* Convert d into the form b*2^e, where b is an odd integer.  b is the returned
01053  * Bigint and e is the returned binary exponent.  Return the number of significant
01054  * bits in b in bits.  d must be finite and nonzero. */
01055 static Bigint *d2b(double d, int32 *e, int32 *bits)
01056 {
01057     Bigint *b;
01058     int32 de, i, k;
01059     ULong *x, y, z;
01060 #define d0 word0(d)
01061 #define d1 word1(d)
01062 #define set_d0(x) set_word0(d, x)
01063 #define set_d1(x) set_word1(d, x)
01064 
01065     b = Balloc(1);
01066     if (!b)
01067         return NULL;
01068     x = b->x;
01069 
01070     z = d0 & Frac_mask;
01071     set_d0(d0 & 0x7fffffff);  /* clear sign bit, which we ignore */
01072 #ifdef Sudden_Underflow
01073     de = (int32)(d0 >> Exp_shift);
01074     z |= Exp_msk11;
01075 #else
01076     if ((de = (int32)(d0 >> Exp_shift)) != 0)
01077         z |= Exp_msk1;
01078 #endif
01079     if ((y = d1) != 0) {
01080         if ((k = lo0bits(&y)) != 0) {
01081             x[0] = y | z << (32 - k);
01082             z >>= k;
01083         }
01084         else
01085             x[0] = y;
01086         i = b->wds = (x[1] = z) ? 2 : 1;
01087     }
01088     else {
01089         JS_ASSERT(z);
01090         k = lo0bits(&z);
01091         x[0] = z;
01092         i = b->wds = 1;
01093         k += 32;
01094     }
01095 #ifndef Sudden_Underflow
01096     if (de) {
01097 #endif
01098         *e = de - Bias - (P-1) + k;
01099         *bits = P - k;
01100 #ifndef Sudden_Underflow
01101     }
01102     else {
01103         *e = de - Bias - (P-1) + 1 + k;
01104         *bits = 32*i - hi0bits(x[i-1]);
01105     }
01106 #endif
01107     return b;
01108 }
01109 #undef d0
01110 #undef d1
01111 #undef set_d0
01112 #undef set_d1
01113 
01114 
01115 static double ratio(Bigint *a, Bigint *b)
01116 {
01117     double da, db;
01118     int32 k, ka, kb;
01119 
01120     da = b2d(a, &ka);
01121     db = b2d(b, &kb);
01122     k = ka - kb + 32*(a->wds - b->wds);
01123     if (k > 0)
01124         set_word0(da, word0(da) + k*Exp_msk1);
01125     else {
01126         k = -k;
01127         set_word0(db, word0(db) + k*Exp_msk1);
01128     }
01129     return da / db;
01130 }
01131 
01132 static CONST double
01133 tens[] = {
01134     1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
01135     1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
01136     1e20, 1e21, 1e22
01137 };
01138 
01139 static CONST double bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 };
01140 static CONST double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128,
01141 #ifdef Avoid_Underflow
01142         9007199254740992.e-256
01143 #else
01144         1e-256
01145 #endif
01146         };
01147 /* The factor of 2^53 in tinytens[4] helps us avoid setting the underflow */
01148 /* flag unnecessarily.  It leads to a song and dance at the end of strtod. */
01149 #define Scale_Bit 0x10
01150 #define n_bigtens 5
01151 
01152 
01153 #ifdef INFNAN_CHECK
01154 
01155 #ifndef NAN_WORD0
01156 #define NAN_WORD0 0x7ff80000
01157 #endif
01158 
01159 #ifndef NAN_WORD1
01160 #define NAN_WORD1 0
01161 #endif
01162 
01163 static int match(CONST char **sp, char *t)
01164 {
01165     int c, d;
01166     CONST char *s = *sp;
01167 
01168     while(d = *t++) {
01169         if ((c = *++s) >= 'A' && c <= 'Z')
01170             c += 'a' - 'A';
01171         if (c != d)
01172             return 0;
01173         }
01174     *sp = s + 1;
01175     return 1;
01176     }
01177 #endif /* INFNAN_CHECK */
01178 
01179 
01180 #ifdef JS_THREADSAFE
01181 static JSBool initialized = JS_FALSE;
01182 
01183 /* hacked replica of nspr _PR_InitDtoa */
01184 static void InitDtoa(void)
01185 {
01186     freelist_lock = PR_NewLock();
01187         p5s_lock = PR_NewLock();
01188     initialized = JS_TRUE;
01189 }
01190 #endif
01191 
01192 void js_FinishDtoa(void)
01193 {
01194     int count;
01195     Bigint *temp;
01196 
01197 #ifdef JS_THREADSAFE
01198     if (initialized == JS_TRUE) {
01199         PR_DestroyLock(freelist_lock);
01200         PR_DestroyLock(p5s_lock);
01201         initialized = JS_FALSE;
01202     }
01203 #endif
01204 
01205     /* clear down the freelist array and p5s */
01206 
01207     /* static Bigint *freelist[Kmax+1]; */
01208     for (count = 0; count <= Kmax; count++) {
01209         Bigint **listp = &freelist[count];
01210         while ((temp = *listp) != NULL) {
01211             *listp = temp->next;
01212             free(temp);
01213         }
01214         freelist[count] = NULL;
01215     }
01216 
01217     /* static Bigint *p5s; */
01218     while (p5s) {
01219         temp = p5s;
01220         p5s = p5s->next;
01221         free(temp);
01222     }
01223 }
01224 
01225 /* nspr2 watcom bug ifdef omitted */
01226 
01227 JS_FRIEND_API(double)
01228 JS_strtod(CONST char *s00, char **se, int *err)
01229 {
01230     int32 scale;
01231     int32 bb2, bb5, bbe, bd2, bd5, bbbits, bs2, c, dsign,
01232         e, e1, esign, i, j, k, nd, nd0, nf, nz, nz0, sign;
01233     CONST char *s, *s0, *s1;
01234     double aadj, aadj1, adj, rv, rv0;
01235     Long L;
01236     ULong y, z;
01237     Bigint *bb, *bb1, *bd, *bd0, *bs, *delta;
01238 
01239     *err = 0;
01240 
01241     bb = bd = bs = delta = NULL;
01242     sign = nz0 = nz = 0;
01243     rv = 0.;
01244 
01245     /* Locking for Balloc's shared buffers that will be used in this block */
01246     ACQUIRE_DTOA_LOCK();
01247 
01248     for(s = s00;;s++) switch(*s) {
01249     case '-':
01250         sign = 1;
01251         /* no break */
01252     case '+':
01253         if (*++s)
01254             goto break2;
01255         /* no break */
01256     case 0:
01257         s = s00;
01258         goto ret;
01259     case '\t':
01260     case '\n':
01261     case '\v':
01262     case '\f':
01263     case '\r':
01264     case ' ':
01265         continue;
01266     default:
01267         goto break2;
01268     }
01269 break2:
01270 
01271     if (*s == '0') {
01272         nz0 = 1;
01273         while(*++s == '0') ;
01274         if (!*s)
01275             goto ret;
01276     }
01277     s0 = s;
01278     y = z = 0;
01279     for(nd = nf = 0; (c = *s) >= '0' && c <= '9'; nd++, s++)
01280         if (nd < 9)
01281             y = 10*y + c - '0';
01282         else if (nd < 16)
01283             z = 10*z + c - '0';
01284     nd0 = nd;
01285     if (c == '.') {
01286         c = *++s;
01287         if (!nd) {
01288             for(; c == '0'; c = *++s)
01289                 nz++;
01290             if (c > '0' && c <= '9') {
01291                 s0 = s;
01292                 nf += nz;
01293                 nz = 0;
01294                 goto have_dig;
01295             }
01296             goto dig_done;
01297         }
01298         for(; c >= '0' && c <= '9'; c = *++s) {
01299         have_dig:
01300             nz++;
01301             if (c -= '0') {
01302                 nf += nz;
01303                 for(i = 1; i < nz; i++)
01304                     if (nd++ < 9)
01305                         y *= 10;
01306                     else if (nd <= DBL_DIG + 1)
01307                         z *= 10;
01308                 if (nd++ < 9)
01309                     y = 10*y + c;
01310                 else if (nd <= DBL_DIG + 1)
01311                     z = 10*z + c;
01312                 nz = 0;
01313             }
01314         }
01315     }
01316 dig_done:
01317     e = 0;
01318     if (c == 'e' || c == 'E') {
01319         if (!nd && !nz && !nz0) {
01320             s = s00;
01321             goto ret;
01322         }
01323         s00 = s;
01324         esign = 0;
01325         switch(c = *++s) {
01326         case '-':
01327             esign = 1;
01328         case '+':
01329             c = *++s;
01330         }
01331         if (c >= '0' && c <= '9') {
01332             while(c == '0')
01333                 c = *++s;
01334             if (c > '0' && c <= '9') {
01335                 L = c - '0';
01336                 s1 = s;
01337                 while((c = *++s) >= '0' && c <= '9')
01338                     L = 10*L + c - '0';
01339                 if (s - s1 > 8 || L > 19999)
01340                     /* Avoid confusion from exponents
01341                      * so large that e might overflow.
01342                      */
01343                     e = 19999; /* safe for 16 bit ints */
01344                 else
01345                     e = (int32)L;
01346                 if (esign)
01347                     e = -e;
01348             }
01349             else
01350                 e = 0;
01351         }
01352         else
01353             s = s00;
01354     }
01355     if (!nd) {
01356         if (!nz && !nz0) {
01357 #ifdef INFNAN_CHECK
01358             /* Check for Nan and Infinity */
01359             switch(c) {
01360               case 'i':
01361               case 'I':
01362                 if (match(&s,"nfinity")) {
01363                     set_word0(rv, 0x7ff00000);
01364                     set_word1(rv, 0);
01365                     goto ret;
01366                     }
01367                 break;
01368               case 'n':
01369               case 'N':
01370                 if (match(&s, "an")) {
01371                     set_word0(rv, NAN_WORD0);
01372                     set_word1(rv, NAN_WORD1);
01373                     goto ret;
01374                     }
01375               }
01376 #endif /* INFNAN_CHECK */
01377             s = s00;
01378             }
01379         goto ret;
01380     }
01381     e1 = e -= nf;
01382 
01383     /* Now we have nd0 digits, starting at s0, followed by a
01384      * decimal point, followed by nd-nd0 digits.  The number we're
01385      * after is the integer represented by those digits times
01386      * 10**e */
01387 
01388     if (!nd0)
01389         nd0 = nd;
01390     k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;
01391     rv = y;
01392     if (k > 9)
01393         rv = tens[k - 9] * rv + z;
01394     bd0 = 0;
01395     if (nd <= DBL_DIG
01396 #ifndef RND_PRODQUOT
01397         && FLT_ROUNDS == 1
01398 #endif
01399         ) {
01400         if (!e)
01401             goto ret;
01402         if (e > 0) {
01403             if (e <= Ten_pmax) {
01404                 /* rv = */ rounded_product(rv, tens[e]);
01405                 goto ret;
01406             }
01407             i = DBL_DIG - nd;
01408             if (e <= Ten_pmax + i) {
01409                 /* A fancier test would sometimes let us do
01410                  * this for larger i values.
01411                  */
01412                 e -= i;
01413                 rv *= tens[i];
01414                 /* rv = */ rounded_product(rv, tens[e]);
01415                 goto ret;
01416             }
01417         }
01418 #ifndef Inaccurate_Divide
01419         else if (e >= -Ten_pmax) {
01420             /* rv = */ rounded_quotient(rv, tens[-e]);
01421             goto ret;
01422         }
01423 #endif
01424     }
01425     e1 += nd - k;
01426 
01427     scale = 0;
01428 
01429     /* Get starting approximation = rv * 10**e1 */
01430 
01431     if (e1 > 0) {
01432         if ((i = e1 & 15) != 0)
01433             rv *= tens[i];
01434         if (e1 &= ~15) {
01435             if (e1 > DBL_MAX_10_EXP) {
01436             ovfl:
01437                 *err = JS_DTOA_ERANGE;
01438 #ifdef __STDC__
01439                 rv = HUGE_VAL;
01440 #else
01441                 /* Can't trust HUGE_VAL */
01442                 set_word0(rv, Exp_mask);
01443                 set_word1(rv, 0);
01444 #endif
01445                 if (bd0)
01446                     goto retfree;
01447                 goto ret;
01448             }
01449             e1 >>= 4;
01450             for(j = 0; e1 > 1; j++, e1 >>= 1)
01451                 if (e1 & 1)
01452                     rv *= bigtens[j];
01453             /* The last multiplication could overflow. */
01454             set_word0(rv, word0(rv) - P*Exp_msk1);
01455             rv *= bigtens[j];
01456             if ((z = word0(rv) & Exp_mask) > Exp_msk1*(DBL_MAX_EXP+Bias-P))
01457                 goto ovfl;
01458             if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) {
01459                 /* set to largest number */
01460                 /* (Can't trust DBL_MAX) */
01461                 set_word0(rv, Big0);
01462                 set_word1(rv, Big1);
01463                 }
01464             else
01465                 set_word0(rv, word0(rv) + P*Exp_msk1);
01466             }
01467     }
01468     else if (e1 < 0) {
01469         e1 = -e1;
01470         if ((i = e1 & 15) != 0)
01471             rv /= tens[i];
01472         if (e1 &= ~15) {
01473             e1 >>= 4;
01474             if (e1 >= 1 << n_bigtens)
01475                 goto undfl;
01476 #ifdef Avoid_Underflow
01477             if (e1 & Scale_Bit)
01478                 scale = P;
01479             for(j = 0; e1 > 0; j++, e1 >>= 1)
01480                 if (e1 & 1)
01481                     rv *= tinytens[j];
01482             if (scale && (j = P + 1 - ((word0(rv) & Exp_mask)
01483                         >> Exp_shift)) > 0) {
01484                 /* scaled rv is denormal; zap j low bits */
01485                 if (j >= 32) {
01486                     set_word1(rv, 0);
01487                     set_word0(rv, word0(rv) & (0xffffffff << (j-32)));
01488                     if (!word0(rv))
01489                         set_word0(rv, 1);
01490                     }
01491                 else
01492                     set_word1(rv, word1(rv) & (0xffffffff << j));
01493                 }
01494 #else
01495             for(j = 0; e1 > 1; j++, e1 >>= 1)
01496                 if (e1 & 1)
01497                     rv *= tinytens[j];
01498             /* The last multiplication could underflow. */
01499             rv0 = rv;
01500             rv *= tinytens[j];
01501             if (!rv) {
01502                 rv = 2.*rv0;
01503                 rv *= tinytens[j];
01504 #endif
01505                 if (!rv) {
01506                 undfl:
01507                     rv = 0.;
01508                     *err = JS_DTOA_ERANGE;
01509                     if (bd0)
01510                         goto retfree;
01511                     goto ret;
01512                 }
01513 #ifndef Avoid_Underflow
01514                 set_word0(rv, Tiny0);
01515                 set_word1(rv, Tiny1);
01516                 /* The refinement below will clean
01517                  * this approximation up.
01518                  */
01519             }
01520 #endif
01521         }
01522     }
01523 
01524     /* Now the hard part -- adjusting rv to the correct value.*/
01525 
01526     /* Put digits into bd: true value = bd * 10^e */
01527 
01528     bd0 = s2b(s0, nd0, nd, y);
01529     if (!bd0)
01530         goto nomem;
01531 
01532     for(;;) {
01533         bd = Balloc(bd0->k);
01534         if (!bd)
01535             goto nomem;
01536         Bcopy(bd, bd0);
01537         bb = d2b(rv, &bbe, &bbbits);    /* rv = bb * 2^bbe */
01538         if (!bb)
01539             goto nomem;
01540         bs = i2b(1);
01541         if (!bs)
01542             goto nomem;
01543 
01544         if (e >= 0) {
01545             bb2 = bb5 = 0;
01546             bd2 = bd5 = e;
01547         }
01548         else {
01549             bb2 = bb5 = -e;
01550             bd2 = bd5 = 0;
01551         }
01552         if (bbe >= 0)
01553             bb2 += bbe;
01554         else
01555             bd2 -= bbe;
01556         bs2 = bb2;
01557 #ifdef Sudden_Underflow
01558         j = P + 1 - bbbits;
01559 #else
01560 #ifdef Avoid_Underflow
01561         j = bbe - scale;
01562 #else
01563         j = bbe;
01564 #endif
01565         i = j + bbbits - 1; /* logb(rv) */
01566         if (i < Emin)   /* denormal */
01567             j += P - Emin;
01568         else
01569             j = P + 1 - bbbits;
01570 #endif
01571         bb2 += j;
01572         bd2 += j;
01573 #ifdef Avoid_Underflow
01574         bd2 += scale;
01575 #endif
01576         i = bb2 < bd2 ? bb2 : bd2;
01577         if (i > bs2)
01578             i = bs2;
01579         if (i > 0) {
01580             bb2 -= i;
01581             bd2 -= i;
01582             bs2 -= i;
01583         }
01584         if (bb5 > 0) {
01585             bs = pow5mult(bs, bb5);
01586             if (!bs)
01587                 goto nomem;
01588             bb1 = mult(bs, bb);
01589             if (!bb1)
01590                 goto nomem;
01591             Bfree(bb);
01592             bb = bb1;
01593         }
01594         if (bb2 > 0) {
01595             bb = lshift(bb, bb2);
01596             if (!bb)
01597                 goto nomem;
01598         }
01599         if (bd5 > 0) {
01600             bd = pow5mult(bd, bd5);
01601             if (!bd)
01602                 goto nomem;
01603         }
01604         if (bd2 > 0) {
01605             bd = lshift(bd, bd2);
01606             if (!bd)
01607                 goto nomem;
01608         }
01609         if (bs2 > 0) {
01610             bs = lshift(bs, bs2);
01611             if (!bs)
01612                 goto nomem;
01613         }
01614         delta = diff(bb, bd);
01615         if (!delta)
01616             goto nomem;
01617         dsign = delta->sign;
01618         delta->sign = 0;
01619         i = cmp(delta, bs);
01620         if (i < 0) {
01621             /* Error is less than half an ulp -- check for
01622              * special case of mantissa a power of two.
01623              */
01624             if (dsign || word1(rv) || word0(rv) & Bndry_mask
01625 #ifdef Avoid_Underflow
01626              || (word0(rv) & Exp_mask) <= Exp_msk1 + P*Exp_msk1
01627 #else
01628              || (word0(rv) & Exp_mask) <= Exp_msk1
01629 #endif
01630                 ) {
01631 #ifdef Avoid_Underflow
01632                 if (!delta->x[0] && delta->wds == 1)
01633                     dsign = 2;
01634 #endif
01635                 break;
01636                 }
01637             delta = lshift(delta,Log2P);
01638             if (!delta)
01639                 goto nomem;
01640             if (cmp(delta, bs) > 0)
01641                 goto drop_down;
01642             break;
01643         }
01644         if (i == 0) {
01645             /* exactly half-way between */
01646             if (dsign) {
01647                 if ((word0(rv) & Bndry_mask1) == Bndry_mask1
01648                     &&  word1(rv) == 0xffffffff) {
01649                     /*boundary case -- increment exponent*/
01650                     set_word0(rv, (word0(rv) & Exp_mask) + Exp_msk1);
01651                     set_word1(rv, 0);
01652 #ifdef Avoid_Underflow
01653                     dsign = 0;
01654 #endif
01655                     break;
01656                 }
01657             }
01658             else if (!(word0(rv) & Bndry_mask) && !word1(rv)) {
01659 #ifdef Avoid_Underflow
01660                 dsign = 2;
01661 #endif
01662             drop_down:
01663                 /* boundary case -- decrement exponent */
01664 #ifdef Sudden_Underflow
01665                 L = word0(rv) & Exp_mask;
01666                 if (L <= Exp_msk1)
01667                     goto undfl;
01668                 L -= Exp_msk1;
01669 #else
01670                 L = (word0(rv) & Exp_mask) - Exp_msk1;
01671 #endif
01672                 set_word0(rv, L | Bndry_mask1);
01673                 set_word1(rv, 0xffffffff);
01674                 break;
01675             }
01676 #ifndef ROUND_BIASED
01677             if (!(word1(rv) & LSB))
01678                 break;
01679 #endif
01680             if (dsign)
01681                 rv += ulp(rv);
01682 #ifndef ROUND_BIASED
01683             else {
01684                 rv -= ulp(rv);
01685 #ifndef Sudden_Underflow
01686                 if (!rv)
01687                     goto undfl;
01688 #endif
01689             }
01690 #ifdef Avoid_Underflow
01691             dsign = 1 - dsign;
01692 #endif
01693 #endif
01694             break;
01695         }
01696         if ((aadj = ratio(delta, bs)) <= 2.) {
01697             if (dsign)
01698                 aadj = aadj1 = 1.;
01699             else if (word1(rv) || word0(rv) & Bndry_mask) {
01700 #ifndef Sudden_Underflow
01701                 if (word1(rv) == Tiny1 && !word0(rv))
01702                     goto undfl;
01703 #endif
01704                 aadj = 1.;
01705                 aadj1 = -1.;
01706             }
01707             else {
01708                 /* special case -- power of FLT_RADIX to be */
01709                 /* rounded down... */
01710 
01711                 if (aadj < 2./FLT_RADIX)
01712                     aadj = 1./FLT_RADIX;
01713                 else
01714                     aadj *= 0.5;
01715                 aadj1 = -aadj;
01716             }
01717         }
01718         else {
01719             aadj *= 0.5;
01720             aadj1 = dsign ? aadj : -aadj;
01721 #ifdef Check_FLT_ROUNDS
01722             switch(FLT_ROUNDS) {
01723             case 2: /* towards +infinity */
01724                 aadj1 -= 0.5;
01725                 break;
01726             case 0: /* towards 0 */
01727             case 3: /* towards -infinity */
01728                 aadj1 += 0.5;
01729             }
01730 #else
01731             if (FLT_ROUNDS == 0)
01732                 aadj1 += 0.5;
01733 #endif
01734         }
01735         y = word0(rv) & Exp_mask;
01736 
01737         /* Check for overflow */
01738 
01739         if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) {
01740             rv0 = rv;
01741             set_word0(rv, word0(rv) - P*Exp_msk1);
01742             adj = aadj1 * ulp(rv);
01743             rv += adj;
01744             if ((word0(rv) & Exp_mask) >=
01745                 Exp_msk1*(DBL_MAX_EXP+Bias-P)) {
01746                 if (word0(rv0) == Big0 && word1(rv0) == Big1)
01747                     goto ovfl;
01748                 set_word0(rv, Big0);
01749                 set_word1(rv, Big1);
01750                 goto cont;
01751             }
01752             else
01753                 set_word0(rv, word0(rv) + P*Exp_msk1);
01754         }
01755         else {
01756 #ifdef Sudden_Underflow
01757             if ((word0(rv) & Exp_mask) <= P*Exp_msk1) {
01758                 rv0 = rv;
01759                 set_word0(rv, word0(rv) + P*Exp_msk1);
01760                 adj = aadj1 * ulp(rv);
01761                 rv += adj;
01762                     if ((word0(rv) & Exp_mask) <= P*Exp_msk1)
01763                         {
01764                             if (word0(rv0) == Tiny0
01765                                 && word1(rv0) == Tiny1)
01766                                 goto undfl;
01767                             set_word0(rv, Tiny0);
01768                             set_word1(rv, Tiny1);
01769                             goto cont;
01770                         }
01771                     else
01772                         set_word0(rv, word0(rv) - P*Exp_msk1);
01773             }
01774             else {
01775                 adj = aadj1 * ulp(rv);
01776                 rv += adj;
01777             }
01778 #else
01779             /* Compute adj so that the IEEE rounding rules will
01780              * correctly round rv + adj in some half-way cases.
01781              * If rv * ulp(rv) is denormalized (i.e.,
01782              * y <= (P-1)*Exp_msk1), we must adjust aadj to avoid
01783              * trouble from bits lost to denormalization;
01784              * example: 1.2e-307 .
01785              */
01786 #ifdef Avoid_Underflow
01787             if (y <= P*Exp_msk1 && aadj > 1.)
01788 #else
01789             if (y <= (P-1)*Exp_msk1 && aadj > 1.)
01790 #endif
01791                 {
01792                 aadj1 = (double)(int32)(aadj + 0.5);
01793                 if (!dsign)
01794                     aadj1 = -aadj1;
01795             }
01796 #ifdef Avoid_Underflow
01797             if (scale && y <= P*Exp_msk1)
01798                 set_word0(aadj1, word0(aadj1) + (P+1)*Exp_msk1 - y);
01799 #endif
01800             adj = aadj1 * ulp(rv);
01801             rv += adj;
01802 #endif
01803         }
01804         z = word0(rv) & Exp_mask;
01805 #ifdef Avoid_Underflow
01806         if (!scale)
01807 #endif
01808         if (y == z) {
01809             /* Can we stop now? */
01810             L = (Long)aadj;
01811             aadj -= L;
01812             /* The tolerances below are conservative. */
01813             if (dsign || word1(rv) || word0(rv) & Bndry_mask) {
01814                 if (aadj < .4999999 || aadj > .5000001)
01815                     break;
01816             }
01817             else if (aadj < .4999999/FLT_RADIX)
01818                 break;
01819         }
01820     cont:
01821         Bfree(bb);
01822         Bfree(bd);
01823         Bfree(bs);
01824         Bfree(delta);
01825         bb = bd = bs = delta = NULL;
01826     }
01827 #ifdef Avoid_Underflow
01828     if (scale) {
01829         rv0 = 0.;
01830         set_word0(rv0, Exp_1 - P*Exp_msk1);
01831         set_word1(rv0, 0);
01832         if ((word0(rv) & Exp_mask) <= P*Exp_msk1
01833               && word1(rv) & 1
01834               && dsign != 2) {
01835             if (dsign) {
01836 #ifdef Sudden_Underflow
01837                 /* rv will be 0, but this would give the  */
01838                 /* right result if only rv *= rv0 worked. */
01839                 set_word0(rv, word0(rv) + P*Exp_msk1);
01840                 set_word0(rv0, Exp_1 - 2*P*Exp_msk1);
01841 #endif
01842                 rv += ulp(rv);
01843                 }
01844             else
01845                 set_word1(rv, word1(rv) & ~1);
01846         }
01847         rv *= rv0;
01848     }
01849 #endif /* Avoid_Underflow */
01850 retfree:
01851     Bfree(bb);
01852     Bfree(bd);
01853     Bfree(bs);
01854     Bfree(bd0);
01855     Bfree(delta);
01856 ret:
01857     RELEASE_DTOA_LOCK();
01858     if (se)
01859         *se = (char *)s;
01860     return sign ? -rv : rv;
01861 
01862 nomem:
01863     Bfree(bb);
01864     Bfree(bd);
01865     Bfree(bs);
01866     Bfree(bd0);
01867     Bfree(delta);
01868     RELEASE_DTOA_LOCK();
01869     *err = JS_DTOA_ENOMEM;
01870     return 0;
01871 }
01872 
01873 
01874 /* Return floor(b/2^k) and set b to be the remainder.  The returned quotient must be less than 2^32. */
01875 static uint32 quorem2(Bigint *b, int32 k)
01876 {
01877     ULong mask;
01878     ULong result;
01879     ULong *bx, *bxe;
01880     int32 w;
01881     int32 n = k >> 5;
01882     k &= 0x1F;
01883     mask = (1<<k) - 1;
01884 
01885     w = b->wds - n;
01886     if (w <= 0)
01887         return 0;
01888     JS_ASSERT(w <= 2);
01889     bx = b->x;
01890     bxe = bx + n;
01891     result = *bxe >> k;
01892     *bxe &= mask;
01893     if (w == 2) {
01894         JS_ASSERT(!(bxe[1] & ~mask));
01895         if (k)
01896             result |= bxe[1] << (32 - k);
01897     }
01898     n++;
01899     while (!*bxe && bxe != bx) {
01900         n--;
01901         bxe--;
01902     }
01903     b->wds = n;
01904     return result;
01905 }
01906 
01907 /* Return floor(b/S) and set b to be the remainder.  As added restrictions, b must not have
01908  * more words than S, the most significant word of S must not start with a 1 bit, and the
01909  * returned quotient must be less than 36. */
01910 static int32 quorem(Bigint *b, Bigint *S)
01911 {
01912     int32 n;
01913     ULong *bx, *bxe, q, *sx, *sxe;
01914 #ifdef ULLong
01915     ULLong borrow, carry, y, ys;
01916 #else
01917     ULong borrow, carry, y, ys;
01918     ULong si, z, zs;
01919 #endif
01920 
01921     n = S->wds;
01922     JS_ASSERT(b->wds <= n);
01923     if (b->wds < n)
01924         return 0;
01925     sx = S->x;
01926     sxe = sx + --n;
01927     bx = b->x;
01928     bxe = bx + n;
01929     JS_ASSERT(*sxe <= 0x7FFFFFFF);
01930     q = *bxe / (*sxe + 1);  /* ensure q <= true quotient */
01931     JS_ASSERT(q < 36);
01932     if (q) {
01933         borrow = 0;
01934         carry = 0;
01935         do {
01936 #ifdef ULLong
01937             ys = *sx++ * (ULLong)q + carry;
01938             carry = ys >> 32;
01939             y = *bx - (ys & 0xffffffffUL) - borrow;
01940             borrow = y >> 32 & 1UL;
01941             *bx++ = (ULong)(y & 0xffffffffUL);
01942 #else
01943             si = *sx++;
01944             ys = (si & 0xffff) * q + carry;
01945             zs = (si >> 16) * q + (ys >> 16);
01946             carry = zs >> 16;
01947             y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
01948             borrow = (y & 0x10000) >> 16;
01949             z = (*bx >> 16) - (zs & 0xffff) - borrow;
01950             borrow = (z & 0x10000) >> 16;
01951             Storeinc(bx, z, y);
01952 #endif
01953         }
01954         while(sx <= sxe);
01955         if (!*bxe) {
01956             bx = b->x;
01957             while(--bxe > bx && !*bxe)
01958                 --n;
01959             b->wds = n;
01960         }
01961     }
01962     if (cmp(b, S) >= 0) {
01963         q++;
01964         borrow = 0;
01965         carry = 0;
01966         bx = b->x;
01967         sx = S->x;
01968         do {
01969 #ifdef ULLong
01970             ys = *sx++ + carry;
01971             carry = ys >> 32;
01972             y = *bx - (ys & 0xffffffffUL) - borrow;
01973             borrow = y >> 32 & 1UL;
01974             *bx++ = (ULong)(y & 0xffffffffUL);
01975 #else
01976             si = *sx++;
01977             ys = (si & 0xffff) + carry;
01978             zs = (si >> 16) + (ys >> 16);
01979             carry = zs >> 16;
01980             y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
01981             borrow = (y & 0x10000) >> 16;
01982             z = (*bx >> 16) - (zs & 0xffff) - borrow;
01983             borrow = (z & 0x10000) >> 16;
01984             Storeinc(bx, z, y);
01985 #endif
01986         } while(sx <= sxe);
01987         bx = b->x;
01988         bxe = bx + n;
01989         if (!*bxe) {
01990             while(--bxe > bx && !*bxe)
01991                 --n;
01992             b->wds = n;
01993         }
01994     }
01995     return (int32)q;
01996 }
01997 
01998 /* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
01999  *
02000  * Inspired by "How to Print Floating-Point Numbers Accurately" by
02001  * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 92-101].
02002  *
02003  * Modifications:
02004  *  1. Rather than iterating, we use a simple numeric overestimate
02005  *     to determine k = floor(log10(d)).  We scale relevant
02006  *     quantities using O(log2(k)) rather than O(k) multiplications.
02007  *  2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
02008  *     try to generate digits strictly left to right.  Instead, we
02009  *     compute with fewer bits and propagate the carry if necessary
02010  *     when rounding the final digit up.  This is often faster.
02011  *  3. Under the assumption that input will be rounded nearest,
02012  *     mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
02013  *     That is, we allow equality in stopping tests when the
02014  *     round-nearest rule will give the same floating-point value
02015  *     as would satisfaction of the stopping test with strict
02016  *     inequality.
02017  *  4. We remove common factors of powers of 2 from relevant
02018  *     quantities.
02019  *  5. When converting floating-point integers less than 1e16,
02020  *     we use floating-point arithmetic rather than resorting
02021  *     to multiple-precision integers.
02022  *  6. When asked to produce fewer than 15 digits, we first try
02023  *     to get by with floating-point arithmetic; we resort to
02024  *     multiple-precision integer arithmetic only if we cannot
02025  *     guarantee that the floating-point calculation has given
02026  *     the correctly rounded result.  For k requested digits and
02027  *     "uniformly" distributed input, the probability is
02028  *     something like 10^(k-15) that we must resort to the Long
02029  *     calculation.
02030  */
02031 
02032 /* Always emits at least one digit. */
02033 /* If biasUp is set, then rounding in modes 2 and 3 will round away from zero
02034  * when the number is exactly halfway between two representable values.  For example,
02035  * rounding 2.5 to zero digits after the decimal point will return 3 and not 2.
02036  * 2.49 will still round to 2, and 2.51 will still round to 3. */
02037 /* bufsize should be at least 20 for modes 0 and 1.  For the other modes,
02038  * bufsize should be two greater than the maximum number of output characters expected. */
02039 static JSBool
02040 js_dtoa(double d, int mode, JSBool biasUp, int ndigits,
02041     int *decpt, int *sign, char **rve, char *buf, size_t bufsize)
02042 {
02043     /*  Arguments ndigits, decpt, sign are similar to those
02044         of ecvt and fcvt; trailing zeros are suppressed from
02045         the returned string.  If not null, *rve is set to point
02046         to the end of the return value.  If d is +-Infinity or NaN,
02047         then *decpt is set to 9999.
02048 
02049         mode:
02050         0 ==> shortest string that yields d when read in
02051         and rounded to nearest.
02052         1 ==> like 0, but with Steele & White stopping rule;
02053         e.g. with IEEE P754 arithmetic , mode 0 gives
02054         1e23 whereas mode 1 gives 9.999999999999999e22.
02055         2 ==> max(1,ndigits) significant digits.  This gives a
02056         return value similar to that of ecvt, except
02057         that trailing zeros are suppressed.
02058         3 ==> through ndigits past the decimal point.  This
02059         gives a return value similar to that from fcvt,
02060         except that trailing zeros are suppressed, and
02061         ndigits can be negative.
02062         4-9 should give the same return values as 2-3, i.e.,
02063         4 <= mode <= 9 ==> same return as mode
02064         2 + (mode & 1).  These modes are mainly for
02065         debugging; often they run slower but sometimes
02066         faster than modes 2-3.
02067         4,5,8,9 ==> left-to-right digit generation.
02068         6-9 ==> don't try fast floating-point estimate
02069         (if applicable).
02070 
02071         Values of mode other than 0-9 are treated as mode 0.
02072 
02073         Sufficient space is allocated to the return value
02074         to hold the suppressed trailing zeros.
02075     */
02076 
02077     int32 bbits, b2, b5, be, dig, i, ieps, ilim, ilim0, ilim1,
02078         j, j1, k, k0, k_check, leftright, m2, m5, s2, s5,
02079         spec_case, try_quick;
02080     Long L;
02081 #ifndef Sudden_Underflow
02082     int32 denorm;
02083     ULong x;
02084 #endif
02085     Bigint *b, *b1, *delta, *mlo, *mhi, *S;
02086     double d2, ds, eps;
02087     char *s;
02088 
02089     if (word0(d) & Sign_bit) {
02090         /* set sign for everything, including 0's and NaNs */
02091         *sign = 1;
02092         set_word0(d, word0(d) & ~Sign_bit);  /* clear sign bit */
02093     }
02094     else
02095         *sign = 0;
02096 
02097     if ((word0(d) & Exp_mask) == Exp_mask) {
02098         /* Infinity or NaN */
02099         *decpt = 9999;
02100         s = !word1(d) && !(word0(d) & Frac_mask) ? "Infinity" : "NaN";
02101         if ((s[0] == 'I' && bufsize < 9) || (s[0] == 'N' && bufsize < 4)) {
02102             JS_ASSERT(JS_FALSE);
02103 /*          JS_SetError(JS_BUFFER_OVERFLOW_ERROR, 0); */
02104             return JS_FALSE;
02105         }
02106         strcpy(buf, s);
02107         if (rve) {
02108             *rve = buf[3] ? buf + 8 : buf + 3;
02109             JS_ASSERT(**rve == '\0');
02110         }
02111         return JS_TRUE;
02112     }
02113 
02114     b = NULL;                           /* initialize for abort protection */
02115     S = NULL;
02116     mlo = mhi = NULL;
02117 
02118     if (!d) {
02119       no_digits:
02120         *decpt = 1;
02121         if (bufsize < 2) {
02122             JS_ASSERT(JS_FALSE);
02123 /*          JS_SetError(JS_BUFFER_OVERFLOW_ERROR, 0); */
02124             return JS_FALSE;
02125         }
02126         buf[0] = '0'; buf[1] = '\0';  /* copy "0" to buffer */
02127         if (rve)
02128             *rve = buf + 1;
02129         /* We might have jumped to "no_digits" from below, so we need
02130          * to be sure to free the potentially allocated Bigints to avoid
02131          * memory leaks. */
02132         Bfree(b);
02133         Bfree(S);
02134         if (mlo != mhi)
02135             Bfree(mlo);
02136         Bfree(mhi);
02137         return JS_TRUE;
02138     }
02139 
02140     b = d2b(d, &be, &bbits);
02141     if (!b)
02142         goto nomem;
02143 #ifdef Sudden_Underflow
02144     i = (int32)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1));
02145 #else
02146     if ((i = (int32)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1))) != 0) {
02147 #endif
02148         d2 = d;
02149         set_word0(d2, word0(d2) & Frac_mask1);
02150         set_word0(d2, word0(d2) | Exp_11);
02151 
02152         /* log(x)   ~=~ log(1.5) + (x-1.5)/1.5
02153          * log10(x)  =  log(x) / log(10)
02154          *      ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
02155          * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2)
02156          *
02157          * This suggests computing an approximation k to log10(d) by
02158          *
02159          * k = (i - Bias)*0.301029995663981
02160          *  + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
02161          *
02162          * We want k to be too large rather than too small.
02163          * The error in the first-order Taylor series approximation
02164          * is in our favor, so we just round up the constant enough
02165          * to compensate for any error in the multiplication of
02166          * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
02167          * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
02168          * adding 1e-13 to the constant term more than suffices.
02169          * Hence we adjust the constant term to 0.1760912590558.
02170          * (We could get a more accurate k by invoking log10,
02171          *  but this is probably not worthwhile.)
02172          */
02173 
02174         i -= Bias;
02175 #ifndef Sudden_Underflow
02176         denorm = 0;
02177     }
02178     else {
02179         /* d is denormalized */
02180 
02181         i = bbits + be + (Bias + (P-1) - 1);
02182         x = i > 32 ? word0(d) << (64 - i) | word1(d) >> (i - 32) : word1(d) << (32 - i);
02183         d2 = x;
02184         set_word0(d2, word0(d2) - 31*Exp_msk1); /* adjust exponent */
02185         i -= (Bias + (P-1) - 1) + 1;
02186         denorm = 1;
02187     }
02188 #endif
02189     /* At this point d = f*2^i, where 1 <= f < 2.  d2 is an approximation of f. */
02190     ds = (d2-1.5)*0.289529654602168 + 0.1760912590558 + i*0.301029995663981;
02191     k = (int32)ds;
02192     if (ds < 0. && ds != k)
02193         k--;    /* want k = floor(ds) */
02194     k_check = 1;
02195     if (k >= 0 && k <= Ten_pmax) {
02196         if (d < tens[k])
02197             k--;
02198         k_check = 0;
02199     }
02200     /* At this point floor(log10(d)) <= k <= floor(log10(d))+1.
02201        If k_check is zero, we're guaranteed that k = floor(log10(d)). */
02202     j = bbits - i - 1;
02203     /* At this point d = b/2^j, where b is an odd integer. */
02204     if (j >= 0) {
02205         b2 = 0;
02206         s2 = j;
02207     }
02208     else {
02209         b2 = -j;
02210         s2 = 0;
02211     }
02212     if (k >= 0) {
02213         b5 = 0;
02214         s5 = k;
02215         s2 += k;
02216     }
02217     else {
02218         b2 -= k;
02219         b5 = -k;
02220         s5 = 0;
02221     }
02222     /* At this point d/10^k = (b * 2^b2 * 5^b5) / (2^s2 * 5^s5), where b is an odd integer,
02223        b2 >= 0, b5 >= 0, s2 >= 0, and s5 >= 0. */
02224     if (mode < 0 || mode > 9)
02225         mode = 0;
02226     try_quick = 1;
02227     if (mode > 5) {
02228         mode -= 4;
02229         try_quick = 0;
02230     }
02231     leftright = 1;
02232     ilim = ilim1 = 0;
02233     switch(mode) {
02234     case 0:
02235     case 1:
02236         ilim = ilim1 = -1;
02237         i = 18;
02238         ndigits = 0;
02239         break;
02240     case 2:
02241         leftright = 0;
02242         /* no break */
02243     case 4:
02244         if (ndigits <= 0)
02245             ndigits = 1;
02246         ilim = ilim1 = i = ndigits;
02247         break;
02248     case 3:
02249         leftright = 0;
02250         /* no break */
02251     case 5:
02252         i = ndigits + k + 1;
02253         ilim = i;
02254         ilim1 = i - 1;
02255         if (i <= 0)
02256             i = 1;
02257     }
02258     /* ilim is the maximum number of significant digits we want, based on k and ndigits. */
02259     /* ilim1 is the maximum number of significant digits we want, based on k and ndigits,
02260        when it turns out that k was computed too high by one. */
02261 
02262     /* Ensure space for at least i+1 characters, including trailing null. */
02263     if (bufsize <= (size_t)i) {
02264         Bfree(b);
02265         JS_ASSERT(JS_FALSE);
02266         return JS_FALSE;
02267     }
02268     s = buf;
02269 
02270     if (ilim >= 0 && ilim <= Quick_max && try_quick) {
02271 
02272         /* Try to get by with floating-point arithmetic. */
02273 
02274         i = 0;
02275         d2 = d;
02276         k0 = k;
02277         ilim0 = ilim;
02278         ieps = 2; /* conservative */
02279         /* Divide d by 10^k, keeping track of the roundoff error and avoiding overflows. */
02280         if (k > 0) {
02281             ds = tens[k&0xf];
02282             j = k >> 4;
02283             if (j & Bletch) {
02284                 /* prevent overflows */
02285                 j &= Bletch - 1;
02286                 d /= bigtens[n_bigtens-1];
02287                 ieps++;
02288             }
02289             for(; j; j >>= 1, i++)
02290                 if (j & 1) {
02291                     ieps++;
02292                     ds *= bigtens[i];
02293                 }
02294             d /= ds;
02295         }
02296         else if ((j1 = -k) != 0) {
02297             d *= tens[j1 & 0xf];
02298             for(j = j1 >> 4; j; j >>= 1, i++)
02299                 if (j & 1) {
02300                     ieps++;
02301                     d *= bigtens[i];
02302                 }
02303         }
02304         /* Check that k was computed correctly. */
02305         if (k_check && d < 1. && ilim > 0) {
02306             if (ilim1 <= 0)
02307                 goto fast_failed;
02308             ilim = ilim1;
02309             k--;
02310             d *= 10.;
02311             ieps++;
02312         }
02313         /* eps bounds the cumulative error. */
02314         eps = ieps*d + 7.;
02315         set_word0(eps, word0(eps) - (P-1)*Exp_msk1);
02316         if (ilim == 0) {
02317             S = mhi = 0;
02318             d -= 5.;
02319             if (d > eps)
02320                 goto one_digit;
02321             if (d < -eps)
02322                 goto no_digits;
02323             goto fast_failed;
02324         }
02325 #ifndef No_leftright
02326         if (leftright) {
02327             /* Use Steele & White method of only
02328              * generating digits needed.
02329              */
02330             eps = 0.5/tens[ilim-1] - eps;
02331             for(i = 0;;) {
02332                 L = (Long)d;
02333                 d -= L;
02334                 *s++ = '0' + (char)L;
02335                 if (d < eps)
02336                     goto ret1;
02337                 if (1. - d < eps)
02338                     goto bump_up;
02339                 if (++i >= ilim)
02340                     break;
02341                 eps *= 10.;
02342                 d *= 10.;
02343             }
02344         }
02345         else {
02346 #endif
02347             /* Generate ilim digits, then fix them up. */
02348             eps *= tens[ilim-1];
02349             for(i = 1;; i++, d *= 10.) {
02350                 L = (Long)d;
02351                 d -= L;
02352                 *s++ = '0' + (char)L;
02353                 if (i == ilim) {
02354                     if (d > 0.5 + eps)
02355                         goto bump_up;
02356                     else if (d < 0.5 - eps) {
02357                         while(*--s == '0') ;
02358                         s++;
02359                         goto ret1;
02360                     }
02361                     break;
02362                 }
02363             }
02364 #ifndef No_leftright
02365         }
02366 #endif
02367     fast_failed:
02368         s = buf;
02369         d = d2;
02370         k = k0;
02371         ilim = ilim0;
02372     }
02373 
02374     /* Do we have a "small" integer? */
02375 
02376     if (be >= 0 && k <= Int_max) {
02377         /* Yes. */
02378         ds = tens[k];
02379         if (ndigits < 0 && ilim <= 0) {
02380             S = mhi = 0;
02381             if (ilim < 0 || d < 5*ds || (!biasUp && d == 5*ds))
02382                 goto no_digits;
02383             goto one_digit;
02384         }
02385 
02386         /* Use true number of digits to limit looping. */
02387         for(i = 1; i<=k+1; i++) {
02388             L = (Long) (d / ds);
02389             d -= L*ds;
02390 #ifdef Check_FLT_ROUNDS
02391             /* If FLT_ROUNDS == 2, L will usually be high by 1 */
02392             if (d < 0) {
02393                 L--;
02394                 d += ds;
02395             }
02396 #endif
02397             *s++ = '0' + (char)L;
02398             if (i == ilim) {
02399                 d += d;
02400                 if ((d > ds) || (d == ds && (L & 1 || biasUp))) {
02401                 bump_up:
02402                     while(*--s == '9')
02403                         if (s == buf) {
02404                             k++;
02405                             *s = '0';
02406                             break;
02407                         }
02408                     ++*s++;
02409                 }
02410                 break;
02411             }
02412             d *= 10.;
02413         }
02414         goto ret1;
02415     }
02416 
02417     m2 = b2;
02418     m5 = b5;
02419     if (leftright) {
02420         if (mode < 2) {
02421             i =
02422 #ifndef Sudden_Underflow
02423                 denorm ? be + (Bias + (P-1) - 1 + 1) :
02424 #endif
02425             1 + P - bbits;
02426             /* i is 1 plus the number of trailing zero bits in d's significand. Thus,
02427                (2^m2 * 5^m5) / (2^(s2+i) * 5^s5) = (1/2 lsb of d)/10^k. */
02428         }
02429         else {
02430             j = ilim - 1;
02431             if (m5 >= j)
02432                 m5 -= j;
02433             else {
02434                 s5 += j -= m5;
02435                 b5 += j;
02436                 m5 = 0;
02437             }
02438             if ((i = ilim) < 0) {
02439                 m2 -= i;
02440                 i = 0;
02441             }
02442             /* (2^m2 * 5^m5) / (2^(s2+i) * 5^s5) = (1/2 * 10^(1-ilim))/10^k. */
02443         }
02444         b2 += i;
02445         s2 += i;
02446         mhi = i2b(1);
02447         if (!mhi)
02448             goto nomem;
02449         /* (mhi * 2^m2 * 5^m5) / (2^s2 * 5^s5) = one-half of last printed (when mode >= 2) or
02450            input (when mode < 2) significant digit, divided by 10^k. */
02451     }
02452     /* We still have d/10^k = (b * 2^b2 * 5^b5) / (2^s2 * 5^s5).  Reduce common factors in
02453        b2, m2, and s2 without changing the equalities. */
02454     if (m2 > 0 && s2 > 0) {
02455         i = m2 < s2 ? m2 : s2;
02456         b2 -= i;
02457         m2 -= i;
02458         s2 -= i;
02459     }
02460 
02461     /* Fold b5 into b and m5 into mhi. */
02462     if (b5 > 0) {
02463         if (leftright) {
02464             if (m5 > 0) {
02465                 mhi = pow5mult(mhi, m5);
02466                 if (!mhi)
02467                     goto nomem;
02468                 b1 = mult(mhi, b);
02469                 if (!b1)
02470                     goto nomem;
02471                 Bfree(b);
02472                 b = b1;
02473             }
02474             if ((j = b5 - m5) != 0) {
02475                 b = pow5mult(b, j);
02476                 if (!b)
02477                     goto nomem;
02478             }
02479         }
02480         else {
02481             b = pow5mult(b, b5);
02482             if (!b)
02483                 goto nomem;
02484         }
02485     }
02486     /* Now we have d/10^k = (b * 2^b2) / (2^s2 * 5^s5) and
02487        (mhi * 2^m2) / (2^s2 * 5^s5) = one-half of last printed or input significant digit, divided by 10^k. */
02488 
02489     S = i2b(1);
02490     if (!S)
02491         goto nomem;
02492     if (s5 > 0) {
02493         S = pow5mult(S, s5);
02494         if (!S)
02495             goto nomem;
02496     }
02497     /* Now we have d/10^k = (b * 2^b2) / (S * 2^s2) and
02498        (mhi * 2^m2) / (S * 2^s2) = one-half of last printed or input significant digit, divided by 10^k. */
02499 
02500     /* Check for special case that d is a normalized power of 2. */
02501     spec_case = 0;
02502     if (mode < 2) {
02503         if (!word1(d) && !(word0(d) & Bndry_mask)
02504 #ifndef Sudden_Underflow
02505             && word0(d) & (Exp_mask & Exp_mask << 1)
02506 #endif
02507             ) {
02508             /* The special case.  Here we want to be within a quarter of the last input
02509                significant digit instead of one half of it when the decimal output string's value is less than d.  */
02510             b2 += Log2P;
02511             s2 += Log2P;
02512             spec_case = 1;
02513         }
02514     }
02515 
02516     /* Arrange for convenient computation of quotients:
02517      * shift left if necessary so divisor has 4 leading 0 bits.
02518      *
02519      * Perhaps we should just compute leading 28 bits of S once
02520      * and for all and pass them and a shift to quorem, so it
02521      * can do shifts and ors to compute the numerator for q.
02522      */
02523     if ((i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0x1f) != 0)
02524         i = 32 - i;
02525     /* i is the number of leading zero bits in the most significant word of S*2^s2. */
02526     if (i > 4) {
02527         i -= 4;
02528         b2 += i;
02529         m2 += i;
02530         s2 += i;
02531     }
02532     else if (i < 4) {
02533         i += 28;
02534         b2 += i;
02535         m2 += i;
02536         s2 += i;
02537     }
02538     /* Now S*2^s2 has exactly four leading zero bits in its most significant word. */
02539     if (b2 > 0) {
02540         b = lshift(b, b2);
02541         if (!b)
02542             goto nomem;
02543     }
02544     if (s2 > 0) {
02545         S = lshift(S, s2);
02546         if (!S)
02547             goto nomem;
02548     }
02549     /* Now we have d/10^k = b/S and
02550        (mhi * 2^m2) / S = maximum acceptable error, divided by 10^k. */
02551     if (k_check) {
02552         if (cmp(b,S) < 0) {
02553             k--;
02554             b = multadd(b, 10, 0);  /* we botched the k estimate */
02555             if (!b)
02556                 goto nomem;
02557             if (leftright) {
02558                 mhi = multadd(mhi, 10, 0);
02559                 if (!mhi)
02560                     goto nomem;
02561             }
02562             ilim = ilim1;
02563         }
02564     }
02565     /* At this point 1 <= d/10^k = b/S < 10. */
02566 
02567     if (ilim <= 0 && mode > 2) {
02568         /* We're doing fixed-mode output and d is less than the minimum nonzero output in this mode.
02569            Output either zero or the minimum nonzero output depending on which is closer to d. */
02570         if (ilim < 0)
02571             goto no_digits;
02572         S = multadd(S,5,0);
02573         if (!S)
02574             goto nomem;
02575         i = cmp(b,S);
02576         if (i < 0 || (i == 0 && !biasUp)) {
02577         /* Always emit at least one digit.  If the number appears to be zero
02578            using the current mode, then emit one '0' digit and set decpt to 1. */
02579         /*no_digits:
02580             k = -1 - ndigits;
02581             goto ret; */
02582             goto no_digits;
02583         }
02584     one_digit:
02585         *s++ = '1';
02586         k++;
02587         goto ret;
02588     }
02589     if (leftright) {
02590         if (m2 > 0) {
02591             mhi = lshift(mhi, m2);
02592             if (!mhi)
02593                 goto nomem;
02594         }
02595 
02596         /* Compute mlo -- check for special case
02597          * that d is a normalized power of 2.
02598          */
02599 
02600         mlo = mhi;
02601         if (spec_case) {
02602             mhi = Balloc(mhi->k);
02603             if (!mhi)
02604                 goto nomem;
02605             Bcopy(mhi, mlo);
02606             mhi = lshift(mhi, Log2P);
02607             if (!mhi)
02608                 goto nomem;
02609         }
02610         /* mlo/S = maximum acceptable error, divided by 10^k, if the output is less than d. */
02611         /* mhi/S = maximum acceptable error, divided by 10^k, if the output is greater than d. */
02612 
02613         for(i = 1;;i++) {
02614             dig = quorem(b,S) + '0';
02615             /* Do we yet have the shortest decimal string
02616              * that will round to d?
02617              */
02618             j = cmp(b, mlo);
02619             /* j is b/S compared with mlo/S. */
02620             delta = diff(S, mhi);
02621             if (!delta)
02622                 goto nomem;
02623             j1 = delta->sign ? 1 : cmp(b, delta);
02624             Bfree(delta);
02625             /* j1 is b/S compared with 1 - mhi/S. */
02626 #ifndef ROUND_BIASED
02627             if (j1 == 0 && !mode && !(word1(d) & 1)) {
02628                 if (dig == '9')
02629                     goto round_9_up;
02630                 if (j > 0)
02631                     dig++;
02632                 *s++ = (char)dig;
02633                 goto ret;
02634             }
02635 #endif
02636             if ((j < 0) || (j == 0 && !mode
02637 #ifndef ROUND_BIASED
02638                 && !(word1(d) & 1)
02639 #endif
02640                 )) {
02641                 if (j1 > 0) {
02642                     /* Either dig or dig+1 would work here as the least significant decimal digit.
02643                        Use whichever would produce a decimal value closer to d. */
02644                     b = lshift(b, 1);
02645                     if (!b)
02646                         goto nomem;
02647                     j1 = cmp(b, S);
02648                     if (((j1 > 0) || (j1 == 0 && (dig & 1 || biasUp)))
02649                         && (dig++ == '9'))
02650                         goto round_9_up;
02651                 }
02652                 *s++ = (char)dig;
02653                 goto ret;
02654             }
02655             if (j1 > 0) {
02656                 if (dig == '9') { /* possible if i == 1 */
02657                 round_9_up:
02658                     *s++ = '9';
02659                     goto roundoff;
02660                 }
02661                 *s++ = (char)dig + 1;
02662                 goto ret;
02663             }
02664             *s++ = (char)dig;
02665             if (i == ilim)
02666                 break;
02667             b = multadd(b, 10, 0);
02668             if (!b)
02669                 goto nomem;
02670             if (mlo == mhi) {
02671                 mlo = mhi = multadd(mhi, 10, 0);
02672                 if (!mhi)
02673                     goto nomem;
02674             }
02675             else {
02676                 mlo = multadd(mlo, 10, 0);
02677                 if (!mlo)
02678                     goto nomem;
02679                 mhi = multadd(mhi, 10, 0);
02680                 if (!mhi)
02681                     goto nomem;
02682             }
02683         }
02684     }
02685     else
02686         for(i = 1;; i++) {
02687             *s++ = (char)(dig = quorem(b,S) + '0');
02688             if (i >= ilim)
02689                 break;
02690             b = multadd(b, 10, 0);
02691             if (!b)
02692                 goto nomem;
02693         }
02694 
02695     /* Round off last digit */
02696 
02697     b = lshift(b, 1);
02698     if (!b)
02699         goto nomem;
02700     j = cmp(b, S);
02701     if ((j > 0) || (j == 0 && (dig & 1 || biasUp))) {
02702     roundoff:
02703         while(*--s == '9')
02704             if (s == buf) {
02705                 k++;
02706                 *s++ = '1';
02707                 goto ret;
02708             }
02709         ++*s++;
02710     }
02711     else {
02712         /* Strip trailing zeros */
02713         while(*--s == '0') ;
02714         s++;
02715     }
02716   ret:
02717     Bfree(S);
02718     if (mhi) {
02719         if (mlo && mlo != mhi)
02720             Bfree(mlo);
02721         Bfree(mhi);
02722     }
02723   ret1:
02724     Bfree(b);
02725     JS_ASSERT(s < buf + bufsize);
02726     *s = '\0';
02727     if (rve)
02728         *rve = s;
02729     *decpt = k + 1;
02730     return JS_TRUE;
02731 
02732 nomem:
02733     Bfree(S);
02734     if (mhi) {
02735         if (mlo && mlo != mhi)
02736             Bfree(mlo);
02737         Bfree(mhi);
02738     }
02739     Bfree(b);
02740     return JS_FALSE;
02741 }
02742 
02743 
02744 /* Mapping of JSDToStrMode -> js_dtoa mode */
02745 static const int dtoaModes[] = {
02746     0,   /* DTOSTR_STANDARD */
02747     0,   /* DTOSTR_STANDARD_EXPONENTIAL, */
02748     3,   /* DTOSTR_FIXED, */
02749     2,   /* DTOSTR_EXPONENTIAL, */
02750     2};  /* DTOSTR_PRECISION */
02751 
02752 JS_FRIEND_API(char *)
02753 JS_dtostr(char *buffer, size_t bufferSize, JSDToStrMode mode, int precision, double d)
02754 {
02755     int decPt;                  /* Position of decimal point relative to first digit returned by js_dtoa */
02756     int sign;                   /* Nonzero if the sign bit was set in d */
02757     int nDigits;                /* Number of significand digits returned by js_dtoa */
02758     char *numBegin = buffer+2;  /* Pointer to the digits returned by js_dtoa; the +2 leaves space for */
02759                                 /* the sign and/or decimal point */
02760     char *numEnd;               /* Pointer past the digits returned by js_dtoa */
02761     JSBool dtoaRet;
02762 
02763     JS_ASSERT(bufferSize >= (size_t)(mode <= DTOSTR_STANDARD_EXPONENTIAL ? DTOSTR_STANDARD_BUFFER_SIZE :
02764             DTOSTR_VARIABLE_BUFFER_SIZE(precision)));
02765 
02766     if (mode == DTOSTR_FIXED && (d >= 1e21 || d <= -1e21))
02767         mode = DTOSTR_STANDARD; /* Change mode here rather than below because the buffer may not be large enough to hold a large integer. */
02768 
02769     /* Locking for Balloc's shared buffers */
02770     ACQUIRE_DTOA_LOCK();
02771     dtoaRet = js_dtoa(d, dtoaModes[mode], mode >= DTOSTR_FIXED, precision, &decPt, &sign, &numEnd, numBegin, bufferSize-2);
02772     RELEASE_DTOA_LOCK();
02773     if (!dtoaRet)
02774         return 0;
02775 
02776     nDigits = numEnd - numBegin;
02777 
02778     /* If Infinity, -Infinity, or NaN, return the string regardless of the mode. */
02779     if (decPt != 9999) {
02780         JSBool exponentialNotation = JS_FALSE;
02781         int minNDigits = 0;         /* Minimum number of significand digits required by mode and precision */
02782         char *p;
02783         char *q;
02784 
02785         switch (mode) {
02786             case DTOSTR_STANDARD:
02787                 if (decPt < -5 || decPt > 21)
02788                     exponentialNotation = JS_TRUE;
02789                 else
02790                     minNDigits = decPt;
02791                 break;
02792 
02793             case DTOSTR_FIXED:
02794                 if (precision >= 0)
02795                     minNDigits = decPt + precision;
02796                 else
02797                     minNDigits = decPt;
02798                 break;
02799 
02800             case DTOSTR_EXPONENTIAL:
02801                 JS_ASSERT(precision > 0);
02802                 minNDigits = precision;
02803                 /* Fall through */
02804             case DTOSTR_STANDARD_EXPONENTIAL:
02805                 exponentialNotation = JS_TRUE;
02806                 break;
02807 
02808             case DTOSTR_PRECISION:
02809                 JS_ASSERT(precision > 0);
02810                 minNDigits = precision;
02811                 if (decPt < -5 || decPt > precision)
02812                     exponentialNotation = JS_TRUE;
02813                 break;
02814         }
02815 
02816         /* If the number has fewer than minNDigits, pad it with zeros at the end */
02817         if (nDigits < minNDigits) {
02818             p = numBegin + minNDigits;
02819             nDigits = minNDigits;
02820             do {
02821                 *numEnd++ = '0';
02822             } while (numEnd != p);
02823             *numEnd = '\0';
02824         }
02825 
02826         if (exponentialNotation) {
02827             /* Insert a decimal point if more than one significand digit */
02828             if (nDigits != 1) {
02829                 numBegin--;
02830                 numBegin[0] = numBegin[1];
02831                 numBegin[1] = '.';
02832             }
02833             JS_snprintf(numEnd, bufferSize - (numEnd - buffer), "e%+d", decPt-1);
02834         } else if (decPt != nDigits) {
02835             /* Some kind of a fraction in fixed notation */
02836             JS_ASSERT(decPt <= nDigits);
02837             if (decPt > 0) {
02838                 /* dd...dd . dd...dd */
02839                 p = --numBegin;
02840                 do {
02841                     *p = p[1];
02842                     p++;
02843                 } while (--decPt);
02844                 *p = '.';
02845             } else {
02846                 /* 0 . 00...00dd...dd */
02847                 p = numEnd;
02848                 numEnd += 1 - decPt;
02849                 q = numEnd;
02850                 JS_ASSERT(numEnd < buffer + bufferSize);
02851                 *numEnd = '\0';
02852                 while (p != numBegin)
02853                     *--q = *--p;
02854                 for (p = numBegin + 1; p != q; p++)
02855                     *p = '0';
02856                 *numBegin = '.';
02857                 *--numBegin = '0';
02858             }
02859         }
02860     }
02861 
02862     /* If negative and neither -0.0 nor NaN, output a leading '-'. */
02863     if (sign &&
02864             !(word0(d) == Sign_bit && word1(d) == 0) &&
02865             !((word0(d) & Exp_mask) == Exp_mask &&
02866               (word1(d) || (word0(d) & Frac_mask)))) {
02867         *--numBegin = '-';
02868     }
02869     return numBegin;
02870 }
02871 
02872 
02873 /* Let b = floor(b / divisor), and return the remainder.  b must be nonnegative.
02874  * divisor must be between 1 and 65536.
02875  * This function cannot run out of memory. */
02876 static uint32
02877 divrem(Bigint *b, uint32 divisor)
02878 {
02879     int32 n = b->wds;
02880     uint32 remainder = 0;
02881     ULong *bx;
02882     ULong *bp;
02883 
02884     JS_ASSERT(divisor > 0 && divisor <= 65536);
02885 
02886     if (!n)
02887         return 0; /* b is zero */
02888     bx = b->x;
02889     bp = bx + n;
02890     do {
02891         ULong a = *--bp;
02892         ULong dividend = remainder << 16 | a >> 16;
02893         ULong quotientHi = dividend / divisor;
02894         ULong quotientLo;
02895 
02896         remainder = dividend - quotientHi*divisor;
02897         JS_ASSERT(quotientHi <= 0xFFFF && remainder < divisor);
02898         dividend = remainder << 16 | (a & 0xFFFF);
02899         quotientLo = dividend / divisor;
02900         remainder = dividend - quotientLo*divisor;
02901         JS_ASSERT(quotientLo <= 0xFFFF && remainder < divisor);
02902         *bp = quotientHi << 16 | quotientLo;
02903     } while (bp != bx);
02904     /* Decrease the size of the number if its most significant word is now zero. */
02905     if (bx[n-1] == 0)
02906         b->wds--;
02907     return remainder;
02908 }
02909 
02910 
02911 /* "-0.0000...(1073 zeros after decimal point)...0001\0" is the longest string that we could produce,
02912  * which occurs when printing -5e-324 in binary.  We could compute a better estimate of the size of
02913  * the output string and malloc fewer bytes depending on d and base, but why bother? */
02914 #define DTOBASESTR_BUFFER_SIZE 1078
02915 #define BASEDIGIT(digit) ((char)(((digit) >= 10) ? 'a' - 10 + (digit) : '0' + (digit)))
02916 
02917 JS_FRIEND_API(char *)
02918 JS_dtobasestr(int base, double d)
02919 {
02920     char *buffer;        /* The output string */
02921     char *p;             /* Pointer to current position in the buffer */
02922     char *pInt;          /* Pointer to the beginning of the integer part of the string */
02923     char *q;
02924     uint32 digit;
02925     double di;           /* d truncated to an integer */
02926     double df;           /* The fractional part of d */
02927 
02928     JS_ASSERT(base >= 2 && base <= 36);
02929 
02930     buffer = (char*) malloc(DTOBASESTR_BUFFER_SIZE);
02931     if (buffer) {
02932         p = buffer;
02933         if (d < 0.0
02934 #if defined(XP_WIN) || defined(XP_OS2)
02935             && !((word0(d) & Exp_mask) == Exp_mask && ((word0(d) & Frac_mask) || word1(d))) /* Visual C++ doesn't know how to compare against NaN */
02936 #endif
02937            ) {
02938             *p++ = '-';
02939             d = -d;
02940         }
02941 
02942         /* Check for Infinity and NaN */
02943         if ((word0(d) & Exp_mask) == Exp_mask) {
02944             strcpy(p, !word1(d) && !(word0(d) & Frac_mask) ? "Infinity" : "NaN");
02945             return buffer;
02946         }
02947 
02948         /* Locking for Balloc's shared buffers */
02949         ACQUIRE_DTOA_LOCK();
02950 
02951         /* Output the integer part of d with the digits in reverse order. */
02952         pInt = p;
02953         di = fd_floor(d);
02954         if (di <= 4294967295.0) {
02955             uint32 n = (uint32)di;
02956             if (n)
02957                 do {
02958                     uint32 m = n / base;
02959                     digit = n - m*base;
02960                     n = m;
02961                     JS_ASSERT(digit < (uint32)base);
02962                     *p++ = BASEDIGIT(digit);
02963                 } while (n);
02964             else *p++ = '0';
02965         } else {
02966             int32 e;
02967             int32 bits;  /* Number of significant bits in di; not used. */
02968             Bigint *b = d2b(di, &e, &bits);
02969             if (!b)
02970                 goto nomem1;
02971             b = lshift(b, e);
02972             if (!b) {
02973               nomem1:
02974                 Bfree(b);
02975                 RELEASE_DTOA_LOCK();
02976                 free(buffer);
02977                 return NULL;
02978             }
02979             do {
02980                 digit = divrem(b, base);
02981                 JS_ASSERT(digit < (uint32)base);
02982                 *p++ = BASEDIGIT(digit);
02983             } while (b->wds);
02984             Bfree(b);
02985         }
02986         /* Reverse the digits of the integer part of d. */
02987         q = p-1;
02988         while (q > pInt) {
02989             char ch = *pInt;
02990             *pInt++ = *q;
02991             *q-- = ch;
02992         }
02993 
02994         df = d - di;
02995         if (df != 0.0) {
02996             /* We have a fraction. */
02997             int32 e, bbits, s2, done;
02998             Bigint *b, *s, *mlo, *mhi;
02999 
03000             b = s = mlo = mhi = NULL;
03001 
03002             *p++ = '.';
03003             b = d2b(df, &e, &bbits);
03004             if (!b) {
03005               nomem2:
03006                 Bfree(b);
03007                 Bfree(s);
03008                 if (mlo != mhi)
03009                     Bfree(mlo);
03010                 Bfree(mhi);
03011                 RELEASE_DTOA_LOCK();
03012                 free(buffer);
03013                 return NULL;
03014             }
03015             JS_ASSERT(e < 0);
03016             /* At this point df = b * 2^e.  e must be less than zero because 0 < df < 1. */
03017 
03018             s2 = -(int32)(word0(d) >> Exp_shift1 & Exp_mask>>Exp_shift1);
03019 #ifndef Sudden_Underflow
03020             if (!s2)
03021                 s2 = -1;
03022 #endif
03023             s2 += Bias + P;
03024             /* 1/2^s2 = (nextDouble(d) - d)/2 */
03025             JS_ASSERT(-s2 < e);
03026             mlo = i2b(1);
03027             if (!mlo)
03028                 goto nomem2;
03029             mhi = mlo;
03030             if (!word1(d) && !(word0(d) & Bndry_mask)
03031 #ifndef Sudden_Underflow
03032                 && word0(d) & (Exp_mask & Exp_mask << 1)
03033 #endif
03034                 ) {
03035                 /* The special case.  Here we want to be within a quarter of the last input
03036                    significant digit instead of one half of it when the output string's value is less than d.  */
03037                 s2 += Log2P;
03038                 mhi = i2b(1<<Log2P);
03039                 if (!mhi)
03040                     goto nomem2;
03041             }
03042             b = lshift(b, e + s2);
03043             if (!b)
03044                 goto nomem2;
03045             s = i2b(1);
03046             if (!s)
03047                 goto nomem2;
03048             s = lshift(s, s2);
03049             if (!s)
03050                 goto nomem2;
03051             /* At this point we have the following:
03052              *   s = 2^s2;
03053              *   1 > df = b/2^s2 > 0;
03054              *   (d - prevDouble(d))/2 = mlo/2^s2;
03055              *   (nextDouble(d) - d)/2 = mhi/2^s2. */
03056 
03057             done = JS_FALSE;
03058             do {
03059                 int32 j, j1;
03060                 Bigint *delta;
03061 
03062                 b = multadd(b, base, 0);
03063                 if (!b)
03064                     goto nomem2;
03065                 digit = quorem2(b, s2);
03066                 if (mlo == mhi) {
03067                     mlo = mhi = multadd(mlo, base, 0);
03068                     if (!mhi)
03069                         goto nomem2;
03070                 }
03071                 else {
03072                     mlo = multadd(mlo, base, 0);
03073                     if (!mlo)
03074                         goto nomem2;
03075                     mhi = multadd(mhi, base, 0);
03076                     if (!mhi)
03077                         goto nomem2;
03078                 }
03079 
03080                 /* Do we yet have the shortest string that will round to d? */
03081                 j = cmp(b, mlo);
03082                 /* j is b/2^s2 compared with mlo/2^s2. */
03083                 delta = diff(s, mhi);
03084                 if (!delta)
03085                     goto nomem2;
03086                 j1 = delta->sign ? 1 : cmp(b, delta);
03087                 Bfree(delta);
03088                 /* j1 is b/2^s2 compared with 1 - mhi/2^s2. */
03089 
03090 #ifndef ROUND_BIASED
03091                 if (j1 == 0 && !(word1(d) & 1)) {
03092                     if (j > 0)
03093                         digit++;
03094                     done = JS_TRUE;
03095                 } else
03096 #endif
03097                 if (j < 0 || (j == 0
03098 #ifndef ROUND_BIASED
03099                     && !(word1(d) & 1)
03100 #endif
03101                     )) {
03102                     if (j1 > 0) {
03103                         /* Either dig or dig+1 would work here as the least significant digit.
03104                            Use whichever would produce an output value closer to d. */
03105                         b = lshift(b, 1);
03106                         if (!b)
03107                             goto nomem2;
03108                         j1 = cmp(b, s);
03109                         if (j1 > 0) /* The even test (|| (j1 == 0 && (digit & 1))) is not here because it messes up odd base output
03110                                      * such as 3.5 in base 3.  */
03111                             digit++;
03112                     }
03113                     done = JS_TRUE;
03114                 } else if (j1 > 0) {
03115                     digit++;
03116                     done = JS_TRUE;
03117                 }
03118                 JS_ASSERT(digit < (uint32)base);
03119                 *p++ = BASEDIGIT(digit);
03120             } while (!done);
03121             Bfree(b);
03122             Bfree(s);
03123             if (mlo != mhi)
03124                 Bfree(mlo);
03125             Bfree(mhi);
03126         }
03127         JS_ASSERT(p < buffer + DTOBASESTR_BUFFER_SIZE);
03128         *p = '\0';
03129         RELEASE_DTOA_LOCK();
03130     }
03131     return buffer;
03132 }