Debian Codegraph @

rhino/src/org/mozilla/javascript/DToA.java

raw symbols SCIP
1 /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 /****************************************************************
8 *
9 * The author of this software is David M. Gay.
10 *
11 * Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
12 *
13 * Permission to use, copy, modify, and distribute this software for any
14 * purpose without fee is hereby granted, provided that this entire notice
15 * is included in all copies of any software which is or includes a copy
16 * or modification of this software and in all copies of the supporting
17 * documentation for such software.
18 *
19 * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
20 * WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
21 * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
22 * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
23 *
24 ***************************************************************/
25
26 package org.mozilla.javascript;
27
28 import java.math.BigInteger;
29
30 class DToA {
31
32
33 private static char BASEDIGIT(int digit) {
34 return (char)((digit >= 10) ? 'a' - 10 + digit : '0' + digit);
35 }
36
37 static final int
38 DTOSTR_STANDARD = 0, /* Either fixed or exponential format; round-trip */
39 DTOSTR_STANDARD_EXPONENTIAL = 1, /* Always exponential format; round-trip */
40 DTOSTR_FIXED = 2, /* Round to <precision> digits after the decimal point; exponential if number is large */
41 DTOSTR_EXPONENTIAL = 3, /* Always exponential format; <precision> significant digits */
42 DTOSTR_PRECISION = 4; /* Either fixed or exponential format; <precision> significant digits */
43
44
45 private static final int Frac_mask = 0xfffff;
46 private static final int Exp_shift = 20;
47 private static final int Exp_msk1 = 0x100000;
48
49 private static final long Frac_maskL = 0xfffffffffffffL;
50 private static final int Exp_shiftL = 52;
51 private static final long Exp_msk1L = 0x10000000000000L;
52
53 private static final int Bias = 1023;
54 private static final int P = 53;
55
56 private static final int Exp_shift1 = 20;
57 private static final int Exp_mask = 0x7ff00000;
58 private static final int Exp_mask_shifted = 0x7ff;
59 private static final int Bndry_mask = 0xfffff;
60 private static final int Log2P = 1;
61
62 private static final int Sign_bit = 0x80000000;
63 private static final int Exp_11 = 0x3ff00000;
64 private static final int Ten_pmax = 22;
65 private static final int Quick_max = 14;
66 private static final int Bletch = 0x10;
67 private static final int Frac_mask1 = 0xfffff;
68 private static final int Int_max = 14;
69 private static final int n_bigtens = 5;
70
71
72 private static final double tens[] = {
73 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
74 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
75 1e20, 1e21, 1e22
76 };
77
78 private static final double bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 };
79
80 private static int lo0bits(int y)
81 {
82 int k;
83 int x = y;
84
85 if ((x & 7) != 0) {
86 if ((x & 1) != 0)
87 return 0;
88 if ((x & 2) != 0) {
89 return 1;
90 }
91 return 2;
92 }
93 k = 0;
94 if ((x & 0xffff) == 0) {
95 k = 16;
96 x >>>= 16;
97 }
98 if ((x & 0xff) == 0) {
99 k += 8;
100 x >>>= 8;
101 }
102 if ((x & 0xf) == 0) {
103 k += 4;
104 x >>>= 4;
105 }
106 if ((x & 0x3) == 0) {
107 k += 2;
108 x >>>= 2;
109 }
110 if ((x & 1) == 0) {
111 k++;
112 x >>>= 1;
113 if ((x & 1) == 0)
114 return 32;
115 }
116 return k;
117 }
118
119 /* Return the number (0 through 32) of most significant zero bits in x. */
120 private static int hi0bits(int x)
121 {
122 int k = 0;
123
124 if ((x & 0xffff0000) == 0) {
125 k = 16;
126 x <<= 16;
127 }
128 if ((x & 0xff000000) == 0) {
129 k += 8;
130 x <<= 8;
131 }
132 if ((x & 0xf0000000) == 0) {
133 k += 4;
134 x <<= 4;
135 }
136 if ((x & 0xc0000000) == 0) {
137 k += 2;
138 x <<= 2;
139 }
140 if ((x & 0x80000000) == 0) {
141 k++;
142 if ((x & 0x40000000) == 0)
143 return 32;
144 }
145 return k;
146 }
147
148 private static void stuffBits(byte bits[], int offset, int val)
149 {
150 bits[offset] = (byte)(val >> 24);
151 bits[offset + 1] = (byte)(val >> 16);
152 bits[offset + 2] = (byte)(val >> 8);
153 bits[offset + 3] = (byte)(val);
154 }
155
156 /* Convert d into the form b*2^e, where b is an odd integer. b is the returned
157 * Bigint and e is the returned binary exponent. Return the number of significant
158 * bits in b in bits. d must be finite and nonzero. */
159 private static BigInteger d2b(double d, int[] e, int[] bits)
160 {
161 byte dbl_bits[];
162 int i, k, y, z, de;
163 long dBits = Double.doubleToLongBits(d);
164 int d0 = (int)(dBits >>> 32);
165 int d1 = (int)(dBits);
166
167 z = d0 & Frac_mask;
168 d0 &= 0x7fffffff; /* clear sign bit, which we ignore */
169
170 if ((de = (d0 >>> Exp_shift)) != 0)
171 z |= Exp_msk1;
172
173 if ((y = d1) != 0) {
174 dbl_bits = new byte[8];
175 k = lo0bits(y);
176 y >>>= k;
177 if (k != 0) {
178 stuffBits(dbl_bits, 4, y | z << (32 - k));
179 z >>= k;
180 }
181 else
182 stuffBits(dbl_bits, 4, y);
183 stuffBits(dbl_bits, 0, z);
184 i = (z != 0) ? 2 : 1;
185 }
186 else {
187 // JS_ASSERT(z);
188 dbl_bits = new byte[4];
189 k = lo0bits(z);
190 z >>>= k;
191 stuffBits(dbl_bits, 0, z);
192 k += 32;
193 i = 1;
194 }
195 if (de != 0) {
196 e[0] = de - Bias - (P-1) + k;
197 bits[0] = P - k;
198 }
199 else {
200 e[0] = de - Bias - (P-1) + 1 + k;
201 bits[0] = 32*i - hi0bits(z);
202 }
203 return new BigInteger(dbl_bits);
204 }
205
206 static String JS_dtobasestr(int base, double d)
207 {
208 if (!(2 <= base && base <= 36))
209 throw new IllegalArgumentException("Bad base: "+base);
210
211 /* Check for Infinity and NaN */
212 if (Double.isNaN(d)) {
213 return "NaN";
214 } else if (Double.isInfinite(d)) {
215 return (d > 0.0) ? "Infinity" : "-Infinity";
216 } else if (d == 0) {
217 // ALERT: should it distinguish -0.0 from +0.0 ?
218 return "0";
219 }
220
221 boolean negative;
222 if (d >= 0.0) {
223 negative = false;
224 } else {
225 negative = true;
226 d = -d;
227 }
228
229 /* Get the integer part of d including '-' sign. */
230 String intDigits;
231
232 double dfloor = Math.floor(d);
233 long lfloor = (long)dfloor;
234 if (lfloor == dfloor) {
235 // int part fits long
236 intDigits = Long.toString((negative) ? -lfloor : lfloor, base);
237 } else {
238 // BigInteger should be used
239 long floorBits = Double.doubleToLongBits(dfloor);
240 int exp = (int)(floorBits >> Exp_shiftL) & Exp_mask_shifted;
241 long mantissa;
242 if (exp == 0) {
243 mantissa = (floorBits & Frac_maskL) << 1;
244 } else {
245 mantissa = (floorBits & Frac_maskL) | Exp_msk1L;
246 }
247 if (negative) {
248 mantissa = -mantissa;
249 }
250 exp -= 1075;
251 BigInteger x = BigInteger.valueOf(mantissa);
252 if (exp > 0) {
253 x = x.shiftLeft(exp);
254 } else if (exp < 0) {
255 x = x.shiftRight(-exp);
256 }
257 intDigits = x.toString(base);
258 }
259
260 if (d == dfloor) {
261 // No fraction part
262 return intDigits;
263 } else {
264 /* We have a fraction. */
265
266 StringBuilder buffer; /* The output string */
267 int digit;
268 double df; /* The fractional part of d */
269 BigInteger b;
270
271 buffer = new StringBuilder();
272 buffer.append(intDigits).append('.');
273 df = d - dfloor;
274
275 long dBits = Double.doubleToLongBits(d);
276 int word0 = (int)(dBits >> 32);
277 int word1 = (int)(dBits);
278
279 int[] e = new int[1];
280 int[] bbits = new int[1];
281
282 b = d2b(df, e, bbits);
283 // JS_ASSERT(e < 0);
284 /* At this point df = b * 2^e. e must be less than zero because 0 < df < 1. */
285
286 int s2 = -(word0 >>> Exp_shift1 & Exp_mask >> Exp_shift1);
287 if (s2 == 0)
288 s2 = -1;
289 s2 += Bias + P;
290 /* 1/2^s2 = (nextDouble(d) - d)/2 */
291 // JS_ASSERT(-s2 < e);
292 BigInteger mlo = BigInteger.valueOf(1);
293 BigInteger mhi = mlo;
294 if ((word1 == 0) && ((word0 & Bndry_mask) == 0)
295 && ((word0 & (Exp_mask & Exp_mask << 1)) != 0)) {
296 /* The special case. Here we want to be within a quarter of the last input
297 significant digit instead of one half of it when the output string's value is less than d. */
298 s2 += Log2P;
299 mhi = BigInteger.valueOf(1<<Log2P);
300 }
301
302 b = b.shiftLeft(e[0] + s2);
303 BigInteger s = BigInteger.valueOf(1);
304 s = s.shiftLeft(s2);
305 /* At this point we have the following:
306 * s = 2^s2;
307 * 1 > df = b/2^s2 > 0;
308 * (d - prevDouble(d))/2 = mlo/2^s2;
309 * (nextDouble(d) - d)/2 = mhi/2^s2. */
310 BigInteger bigBase = BigInteger.valueOf(base);
311
312 boolean done = false;
313 do {
314 b = b.multiply(bigBase);
315 BigInteger[] divResult = b.divideAndRemainder(s);
316 b = divResult[1];
317 digit = (char)(divResult[0].intValue());
318 if (mlo == mhi)
319 mlo = mhi = mlo.multiply(bigBase);
320 else {
321 mlo = mlo.multiply(bigBase);
322 mhi = mhi.multiply(bigBase);
323 }
324
325 /* Do we yet have the shortest string that will round to d? */
326 int j = b.compareTo(mlo);
327 /* j is b/2^s2 compared with mlo/2^s2. */
328 BigInteger delta = s.subtract(mhi);
329 int j1 = (delta.signum() <= 0) ? 1 : b.compareTo(delta);
330 /* j1 is b/2^s2 compared with 1 - mhi/2^s2. */
331 if (j1 == 0 && ((word1 & 1) == 0)) {
332 if (j > 0)
333 digit++;
334 done = true;
335 } else
336 if (j < 0 || (j == 0 && ((word1 & 1) == 0))) {
337 if (j1 > 0) {
338 /* Either dig or dig+1 would work here as the least significant digit.
339 Use whichever would produce an output value closer to d. */
340 b = b.shiftLeft(1);
341 j1 = b.compareTo(s);
342 if (j1 > 0) /* The even test (|| (j1 == 0 && (digit & 1))) is not here because it messes up odd base output
343 * such as 3.5 in base 3. */
344 digit++;
345 }
346 done = true;
347 } else if (j1 > 0) {
348 digit++;
349 done = true;
350 }
351 // JS_ASSERT(digit < (uint32)base);
352 buffer.append(BASEDIGIT(digit));
353 } while (!done);
354
355 return buffer.toString();
356 }
357
358 }
359
360 /* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
361 *
362 * Inspired by "How to Print Floating-Point Numbers Accurately" by
363 * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 92-101].
364 *
365 * Modifications:
366 * 1. Rather than iterating, we use a simple numeric overestimate
367 * to determine k = floor(log10(d)). We scale relevant
368 * quantities using O(log2(k)) rather than O(k) multiplications.
369 * 2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
370 * try to generate digits strictly left to right. Instead, we
371 * compute with fewer bits and propagate the carry if necessary
372 * when rounding the final digit up. This is often faster.
373 * 3. Under the assumption that input will be rounded nearest,
374 * mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
375 * That is, we allow equality in stopping tests when the
376 * round-nearest rule will give the same floating-point value
377 * as would satisfaction of the stopping test with strict
378 * inequality.
379 * 4. We remove common factors of powers of 2 from relevant
380 * quantities.
381 * 5. When converting floating-point integers less than 1e16,
382 * we use floating-point arithmetic rather than resorting
383 * to multiple-precision integers.
384 * 6. When asked to produce fewer than 15 digits, we first try
385 * to get by with floating-point arithmetic; we resort to
386 * multiple-precision integer arithmetic only if we cannot
387 * guarantee that the floating-point calculation has given
388 * the correctly rounded result. For k requested digits and
389 * "uniformly" distributed input, the probability is
390 * something like 10^(k-15) that we must resort to the Long
391 * calculation.
392 */
393
394 static int word0(double d)
395 {
396 long dBits = Double.doubleToLongBits(d);
397 return (int)(dBits >> 32);
398 }
399
400 static double setWord0(double d, int i)
401 {
402 long dBits = Double.doubleToLongBits(d);
403 dBits = ((long)i << 32) | (dBits & 0x0FFFFFFFFL);
404 return Double.longBitsToDouble(dBits);
405 }
406
407 static int word1(double d)
408 {
409 long dBits = Double.doubleToLongBits(d);
410 return (int)(dBits);
411 }
412
413 /* Return b * 5^k. k must be nonnegative. */
414 // XXXX the C version built a cache of these
415 static BigInteger pow5mult(BigInteger b, int k)
416 {
417 return b.multiply(BigInteger.valueOf(5).pow(k));
418 }
419
420 static boolean roundOff(StringBuilder buf)
421 {
422 int i = buf.length();
423 while (i != 0) {
424 --i;
425 char c = buf.charAt(i);
426 if (c != '9') {
427 buf.setCharAt(i, (char)(c + 1));
428 buf.setLength(i + 1);
429 return false;
430 }
431 }
432 buf.setLength(0);
433 return true;
434 }
435
436 /* Always emits at least one digit. */
437 /* If biasUp is set, then rounding in modes 2 and 3 will round away from zero
438 * when the number is exactly halfway between two representable values. For example,
439 * rounding 2.5 to zero digits after the decimal point will return 3 and not 2.
440 * 2.49 will still round to 2, and 2.51 will still round to 3. */
441 /* bufsize should be at least 20 for modes 0 and 1. For the other modes,
442 * bufsize should be two greater than the maximum number of output characters expected. */
443 static int
444 JS_dtoa(double d, int mode, boolean biasUp, int ndigits,
445 boolean[] sign, StringBuilder buf)
446 {
447 /* Arguments ndigits, decpt, sign are similar to those
448 of ecvt and fcvt; trailing zeros are suppressed from
449 the returned string. If not null, *rve is set to point
450 to the end of the return value. If d is +-Infinity or NaN,
451 then *decpt is set to 9999.
452
453 mode:
454 0 ==> shortest string that yields d when read in
455 and rounded to nearest.
456 1 ==> like 0, but with Steele & White stopping rule;
457 e.g. with IEEE P754 arithmetic , mode 0 gives
458 1e23 whereas mode 1 gives 9.999999999999999e22.
459 2 ==> max(1,ndigits) significant digits. This gives a
460 return value similar to that of ecvt, except
461 that trailing zeros are suppressed.
462 3 ==> through ndigits past the decimal point. This
463 gives a return value similar to that from fcvt,
464 except that trailing zeros are suppressed, and
465 ndigits can be negative.
466 4-9 should give the same return values as 2-3, i.e.,
467 4 <= mode <= 9 ==> same return as mode
468 2 + (mode & 1). These modes are mainly for
469 debugging; often they run slower but sometimes
470 faster than modes 2-3.
471 4,5,8,9 ==> left-to-right digit generation.
472 6-9 ==> don't try fast floating-point estimate
473 (if applicable).
474
475 Values of mode other than 0-9 are treated as mode 0.
476
477 Sufficient space is allocated to the return value
478 to hold the suppressed trailing zeros.
479 */
480
481 int b2, b5, i, ieps, ilim, ilim0, ilim1,
482 j, j1, k, k0, m2, m5, s2, s5;
483 char dig;
484 long L;
485 long x;
486 BigInteger b, b1, delta, mlo, mhi, S;
487 int[] be = new int[1];
488 int[] bbits = new int[1];
489 double d2, ds, eps;
490 boolean spec_case, denorm, k_check, try_quick, leftright;
491
492 if ((word0(d) & Sign_bit) != 0) {
493 /* set sign for everything, including 0's and NaNs */
494 sign[0] = true;
495 // word0(d) &= ~Sign_bit; /* clear sign bit */
496 d = setWord0(d, word0(d) & ~Sign_bit);
497 }
498 else
499 sign[0] = false;
500
501 if ((word0(d) & Exp_mask) == Exp_mask) {
502 /* Infinity or NaN */
503 buf.append(((word1(d) == 0) && ((word0(d) & Frac_mask) == 0)) ? "Infinity" : "NaN");
504 return 9999;
505 }
506 if (d == 0) {
507 // no_digits:
508 buf.setLength(0);
509 buf.append('0'); /* copy "0" to buffer */
510 return 1;
511 }
512
513 b = d2b(d, be, bbits);
514 if ((i = (word0(d) >>> Exp_shift1 & (Exp_mask>>Exp_shift1))) != 0) {
515 d2 = setWord0(d, (word0(d) & Frac_mask1) | Exp_11);
516 /* log(x) ~=~ log(1.5) + (x-1.5)/1.5
517 * log10(x) = log(x) / log(10)
518 * ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
519 * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2)
520 *
521 * This suggests computing an approximation k to log10(d) by
522 *
523 * k = (i - Bias)*0.301029995663981
524 * + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
525 *
526 * We want k to be too large rather than too small.
527 * The error in the first-order Taylor series approximation
528 * is in our favor, so we just round up the constant enough
529 * to compensate for any error in the multiplication of
530 * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
531 * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
532 * adding 1e-13 to the constant term more than suffices.
533 * Hence we adjust the constant term to 0.1760912590558.
534 * (We could get a more accurate k by invoking log10,
535 * but this is probably not worthwhile.)
536 */
537 i -= Bias;
538 denorm = false;
539 }
540 else {
541 /* d is denormalized */
542 i = bbits[0] + be[0] + (Bias + (P-1) - 1);
543 x = (i > 32)
544 ? ((long) word0(d)) << (64 - i) | word1(d) >>> (i - 32)
545 : ((long) word1(d)) << (32 - i);
546 // d2 = x;
547 // word0(d2) -= 31*Exp_msk1; /* adjust exponent */
548 d2 = setWord0(x, word0(x) - 31*Exp_msk1);
549 i -= (Bias + (P-1) - 1) + 1;
550 denorm = true;
551 }
552 /* At this point d = f*2^i, where 1 <= f < 2. d2 is an approximation of f. */
553 ds = (d2-1.5)*0.289529654602168 + 0.1760912590558 + i*0.301029995663981;
554 k = (int)ds;
555 if (ds < 0.0 && ds != k)
556 k--; /* want k = floor(ds) */
557 k_check = true;
558 if (k >= 0 && k <= Ten_pmax) {
559 if (d < tens[k])
560 k--;
561 k_check = false;
562 }
563 /* At this point floor(log10(d)) <= k <= floor(log10(d))+1.
564 If k_check is zero, we're guaranteed that k = floor(log10(d)). */
565 j = bbits[0] - i - 1;
566 /* At this point d = b/2^j, where b is an odd integer. */
567 if (j >= 0) {
568 b2 = 0;
569 s2 = j;
570 }
571 else {
572 b2 = -j;
573 s2 = 0;
574 }
575 if (k >= 0) {
576 b5 = 0;
577 s5 = k;
578 s2 += k;
579 }
580 else {
581 b2 -= k;
582 b5 = -k;
583 s5 = 0;
584 }
585 /* At this point d/10^k = (b * 2^b2 * 5^b5) / (2^s2 * 5^s5), where b is an odd integer,
586 b2 >= 0, b5 >= 0, s2 >= 0, and s5 >= 0. */
587 if (mode < 0 || mode > 9)
588 mode = 0;
589 try_quick = true;
590 if (mode > 5) {
591 mode -= 4;
592 try_quick = false;
593 }
594 leftright = true;
595 ilim = ilim1 = 0;
596 switch(mode) {
597 case 0:
598 case 1:
599 ilim = ilim1 = -1;
600 i = 18;
601 ndigits = 0;
602 break;
603 case 2:
604 leftright = false;
605 /* fallthru */
606 case 4:
607 if (ndigits <= 0)
608 ndigits = 1;
609 ilim = ilim1 = i = ndigits;
610 break;
611 case 3:
612 leftright = false;
613 /* fallthru */
614 case 5:
615 i = ndigits + k + 1;
616 ilim = i;
617 ilim1 = i - 1;
618 if (i <= 0)
619 i = 1;
620 }
621 /* ilim is the maximum number of significant digits we want, based on k and ndigits. */
622 /* ilim1 is the maximum number of significant digits we want, based on k and ndigits,
623 when it turns out that k was computed too high by one. */
624
625 boolean fast_failed = false;
626 if (ilim >= 0 && ilim <= Quick_max && try_quick) {
627
628 /* Try to get by with floating-point arithmetic. */
629
630 i = 0;
631 d2 = d;
632 k0 = k;
633 ilim0 = ilim;
634 ieps = 2; /* conservative */
635 /* Divide d by 10^k, keeping track of the roundoff error and avoiding overflows. */
636 if (k > 0) {
637 ds = tens[k&0xf];
638 j = k >> 4;
639 if ((j & Bletch) != 0) {
640 /* prevent overflows */
641 j &= Bletch - 1;
642 d /= bigtens[n_bigtens-1];
643 ieps++;
644 }
645 for(; (j != 0); j >>= 1, i++)
646 if ((j & 1) != 0) {
647 ieps++;
648 ds *= bigtens[i];
649 }
650 d /= ds;
651 }
652 else if ((j1 = -k) != 0) {
653 d *= tens[j1 & 0xf];
654 for(j = j1 >> 4; (j != 0); j >>= 1, i++)
655 if ((j & 1) != 0) {
656 ieps++;
657 d *= bigtens[i];
658 }
659 }
660 /* Check that k was computed correctly. */
661 if (k_check && d < 1.0 && ilim > 0) {
662 if (ilim1 <= 0)
663 fast_failed = true;
664 else {
665 ilim = ilim1;
666 k--;
667 d *= 10.;
668 ieps++;
669 }
670 }
671 /* eps bounds the cumulative error. */
672 // eps = ieps*d + 7.0;
673 // word0(eps) -= (P-1)*Exp_msk1;
674 eps = ieps*d + 7.0;
675 eps = setWord0(eps, word0(eps) - (P-1)*Exp_msk1);
676 if (ilim == 0) {
677 S = mhi = null;
678 d -= 5.0;
679 if (d > eps) {
680 buf.append('1');
681 k++;
682 return k + 1;
683 }
684 if (d < -eps) {
685 buf.setLength(0);
686 buf.append('0'); /* copy "0" to buffer */
687 return 1;
688 }
689 fast_failed = true;
690 }
691 if (!fast_failed) {
692 fast_failed = true;
693 if (leftright) {
694 /* Use Steele & White method of only
695 * generating digits needed.
696 */
697 eps = 0.5/tens[ilim-1] - eps;
698 for(i = 0;;) {
699 L = (long)d;
700 d -= L;
701 buf.append((char)('0' + L));
702 if (d < eps) {
703 return k + 1;
704 }
705 if (1.0 - d < eps) {
706 // goto bump_up;
707 char lastCh;
708 while (true) {
709 lastCh = buf.charAt(buf.length() - 1);
710 buf.setLength(buf.length() - 1);
711 if (lastCh != '9') break;
712 if (buf.length() == 0) {
713 k++;
714 lastCh = '0';
715 break;
716 }
717 }
718 buf.append((char)(lastCh + 1));
719 return k + 1;
720 }
721 if (++i >= ilim)
722 break;
723 eps *= 10.0;
724 d *= 10.0;
725 }
726 }
727 else {
728 /* Generate ilim digits, then fix them up. */
729 eps *= tens[ilim-1];
730 for(i = 1;; i++, d *= 10.0) {
731 L = (long)d;
732 d -= L;
733 buf.append((char)('0' + L));
734 if (i == ilim) {
735 if (d > 0.5 + eps) {
736 // goto bump_up;
737 char lastCh;
738 while (true) {
739 lastCh = buf.charAt(buf.length() - 1);
740 buf.setLength(buf.length() - 1);
741 if (lastCh != '9') break;
742 if (buf.length() == 0) {
743 k++;
744 lastCh = '0';
745 break;
746 }
747 }
748 buf.append((char)(lastCh + 1));
749 return k + 1;
750 }
751 else
752 if (d < 0.5 - eps) {
753 stripTrailingZeroes(buf);
754 // while(*--s == '0') ;
755 // s++;
756 return k + 1;
757 }
758 break;
759 }
760 }
761 }
762 }
763 if (fast_failed) {
764 buf.setLength(0);
765 d = d2;
766 k = k0;
767 ilim = ilim0;
768 }
769 }
770
771 /* Do we have a "small" integer? */
772
773 if (be[0] >= 0 && k <= Int_max) {
774 /* Yes. */
775 ds = tens[k];
776 if (ndigits < 0 && ilim <= 0) {
777 S = mhi = null;
778 if (ilim < 0 || d < 5*ds || (!biasUp && d == 5*ds)) {
779 buf.setLength(0);
780 buf.append('0'); /* copy "0" to buffer */
781 return 1;
782 }
783 buf.append('1');
784 k++;
785 return k + 1;
786 }
787 for(i = 1;; i++) {
788 L = (long) (d / ds);
789 d -= L*ds;
790 buf.append((char)('0' + L));
791 if (i == ilim) {
792 d += d;
793 if ((d > ds) || (d == ds && (((L & 1) != 0) || biasUp))) {
794 // bump_up:
795 // while(*--s == '9')
796 // if (s == buf) {
797 // k++;
798 // *s = '0';
799 // break;
800 // }
801 // ++*s++;
802 char lastCh;
803 while (true) {
804 lastCh = buf.charAt(buf.length() - 1);
805 buf.setLength(buf.length() - 1);
806 if (lastCh != '9') break;
807 if (buf.length() == 0) {
808 k++;
809 lastCh = '0';
810 break;
811 }
812 }
813 buf.append((char)(lastCh + 1));
814 }
815 break;
816 }
817 d *= 10.0;
818 if (d == 0)
819 break;
820 }
821 return k + 1;
822 }
823
824 m2 = b2;
825 m5 = b5;
826 mhi = mlo = null;
827 if (leftright) {
828 if (mode < 2) {
829 i = (denorm) ? be[0] + (Bias + (P-1) - 1 + 1) : 1 + P - bbits[0];
830 /* i is 1 plus the number of trailing zero bits in d's significand. Thus,
831 (2^m2 * 5^m5) / (2^(s2+i) * 5^s5) = (1/2 lsb of d)/10^k. */
832 }
833 else {
834 j = ilim - 1;
835 if (m5 >= j)
836 m5 -= j;
837 else {
838 s5 += j -= m5;
839 b5 += j;
840 m5 = 0;
841 }
842 if ((i = ilim) < 0) {
843 m2 -= i;
844 i = 0;
845 }
846 /* (2^m2 * 5^m5) / (2^(s2+i) * 5^s5) = (1/2 * 10^(1-ilim))/10^k. */
847 }
848 b2 += i;
849 s2 += i;
850 mhi = BigInteger.valueOf(1);
851 /* (mhi * 2^m2 * 5^m5) / (2^s2 * 5^s5) = one-half of last printed (when mode >= 2) or
852 input (when mode < 2) significant digit, divided by 10^k. */
853 }
854 /* We still have d/10^k = (b * 2^b2 * 5^b5) / (2^s2 * 5^s5). Reduce common factors in
855 b2, m2, and s2 without changing the equalities. */
856 if (m2 > 0 && s2 > 0) {
857 i = (m2 < s2) ? m2 : s2;
858 b2 -= i;
859 m2 -= i;
860 s2 -= i;
861 }
862
863 /* Fold b5 into b and m5 into mhi. */
864 if (b5 > 0) {
865 if (leftright) {
866 if (m5 > 0) {
867 mhi = pow5mult(mhi, m5);
868 b1 = mhi.multiply(b);
869 b = b1;
870 }
871 if ((j = b5 - m5) != 0)
872 b = pow5mult(b, j);
873 }
874 else
875 b = pow5mult(b, b5);
876 }
877 /* Now we have d/10^k = (b * 2^b2) / (2^s2 * 5^s5) and
878 (mhi * 2^m2) / (2^s2 * 5^s5) = one-half of last printed or input significant digit, divided by 10^k. */
879
880 S = BigInteger.valueOf(1);
881 if (s5 > 0)
882 S = pow5mult(S, s5);
883 /* Now we have d/10^k = (b * 2^b2) / (S * 2^s2) and
884 (mhi * 2^m2) / (S * 2^s2) = one-half of last printed or input significant digit, divided by 10^k. */
885
886 /* Check for special case that d is a normalized power of 2. */
887 spec_case = false;
888 if (mode < 2) {
889 if ( (word1(d) == 0) && ((word0(d) & Bndry_mask) == 0)
890 && ((word0(d) & (Exp_mask & Exp_mask << 1)) != 0)
891 ) {
892 /* The special case. Here we want to be within a quarter of the last input
893 significant digit instead of one half of it when the decimal output string's value is less than d. */
894 b2 += Log2P;
895 s2 += Log2P;
896 spec_case = true;
897 }
898 }
899
900 /* Arrange for convenient computation of quotients:
901 * shift left if necessary so divisor has 4 leading 0 bits.
902 *
903 * Perhaps we should just compute leading 28 bits of S once
904 * and for all and pass them and a shift to quorem, so it
905 * can do shifts and ors to compute the numerator for q.
906 */
907 byte [] S_bytes = S.toByteArray();
908 int S_hiWord = 0;
909 for (int idx = 0; idx < 4; idx++) {
910 S_hiWord = (S_hiWord << 8);
911 if (idx < S_bytes.length)
912 S_hiWord |= (S_bytes[idx] & 0xFF);
913 }
914 if ((i = (((s5 != 0) ? 32 - hi0bits(S_hiWord) : 1) + s2) & 0x1f) != 0)
915 i = 32 - i;
916 /* i is the number of leading zero bits in the most significant word of S*2^s2. */
917 if (i > 4) {
918 i -= 4;
919 b2 += i;
920 m2 += i;
921 s2 += i;
922 }
923 else if (i < 4) {
924 i += 28;
925 b2 += i;
926 m2 += i;
927 s2 += i;
928 }
929 /* Now S*2^s2 has exactly four leading zero bits in its most significant word. */
930 if (b2 > 0)
931 b = b.shiftLeft(b2);
932 if (s2 > 0)
933 S = S.shiftLeft(s2);
934 /* Now we have d/10^k = b/S and
935 (mhi * 2^m2) / S = maximum acceptable error, divided by 10^k. */
936 if (k_check) {
937 if (b.compareTo(S) < 0) {
938 k--;
939 b = b.multiply(BigInteger.valueOf(10)); /* we botched the k estimate */
940 if (leftright)
941 mhi = mhi.multiply(BigInteger.valueOf(10));
942 ilim = ilim1;
943 }
944 }
945 /* At this point 1 <= d/10^k = b/S < 10. */
946
947 if (ilim <= 0 && mode > 2) {
948 /* We're doing fixed-mode output and d is less than the minimum nonzero output in this mode.
949 Output either zero or the minimum nonzero output depending on which is closer to d. */
950 if ((ilim < 0 )
951 || ((i = b.compareTo(S = S.multiply(BigInteger.valueOf(5)))) < 0)
952 || ((i == 0 && !biasUp))) {
953 /* Always emit at least one digit. If the number appears to be zero
954 using the current mode, then emit one '0' digit and set decpt to 1. */
955 /*no_digits:
956 k = -1 - ndigits;
957 goto ret; */
958 buf.setLength(0);
959 buf.append('0'); /* copy "0" to buffer */
960 return 1;
961 // goto no_digits;
962 }
963 // one_digit:
964 buf.append('1');
965 k++;
966 return k + 1;
967 }
968 if (leftright) {
969 if (m2 > 0)
970 mhi = mhi.shiftLeft(m2);
971
972 /* Compute mlo -- check for special case
973 * that d is a normalized power of 2.
974 */
975
976 mlo = mhi;
977 if (spec_case) {
978 mhi = mlo;
979 mhi = mhi.shiftLeft(Log2P);
980 }
981 /* mlo/S = maximum acceptable error, divided by 10^k, if the output is less than d. */
982 /* mhi/S = maximum acceptable error, divided by 10^k, if the output is greater than d. */
983
984 for(i = 1;;i++) {
985 BigInteger[] divResult = b.divideAndRemainder(S);
986 b = divResult[1];
987 dig = (char)(divResult[0].intValue() + '0');
988 /* Do we yet have the shortest decimal string
989 * that will round to d?
990 */
991 j = b.compareTo(mlo);
992 /* j is b/S compared with mlo/S. */
993 delta = S.subtract(mhi);
994 j1 = (delta.signum() <= 0) ? 1 : b.compareTo(delta);
995 /* j1 is b/S compared with 1 - mhi/S. */
996 if ((j1 == 0) && (mode == 0) && ((word1(d) & 1) == 0)) {
997 if (dig == '9') {
998 buf.append('9');
999 if (roundOff(buf)) {
1000 k++;
1001 buf.append('1');
1002 }
1003 return k + 1;
1004 // goto round_9_up;
1005 }
1006 if (j > 0)
1007 dig++;
1008 buf.append(dig);
1009 return k + 1;
1010 }
1011 if ((j < 0)
1012 || ((j == 0)
1013 && (mode == 0)
1014 && ((word1(d) & 1) == 0)
1015 )) {
1016 if (j1 > 0) {
1017 /* Either dig or dig+1 would work here as the least significant decimal digit.
1018 Use whichever would produce a decimal value closer to d. */
1019 b = b.shiftLeft(1);
1020 j1 = b.compareTo(S);
1021 if (((j1 > 0) || (j1 == 0 && (((dig & 1) == 1) || biasUp)))
1022 && (dig++ == '9')) {
1023 buf.append('9');
1024 if (roundOff(buf)) {
1025 k++;
1026 buf.append('1');
1027 }
1028 return k + 1;
1029 // goto round_9_up;
1030 }
1031 }
1032 buf.append(dig);
1033 return k + 1;
1034 }
1035 if (j1 > 0) {
1036 if (dig == '9') { /* possible if i == 1 */
1037 // round_9_up:
1038 // *s++ = '9';
1039 // goto roundoff;
1040 buf.append('9');
1041 if (roundOff(buf)) {
1042 k++;
1043 buf.append('1');
1044 }
1045 return k + 1;
1046 }
1047 buf.append((char)(dig + 1));
1048 return k + 1;
1049 }
1050 buf.append(dig);
1051 if (i == ilim)
1052 break;
1053 b = b.multiply(BigInteger.valueOf(10));
1054 if (mlo == mhi)
1055 mlo = mhi = mhi.multiply(BigInteger.valueOf(10));
1056 else {
1057 mlo = mlo.multiply(BigInteger.valueOf(10));
1058 mhi = mhi.multiply(BigInteger.valueOf(10));
1059 }
1060 }
1061 }
1062 else
1063 for(i = 1;; i++) {
1064 // (char)(dig = quorem(b,S) + '0');
1065 BigInteger[] divResult = b.divideAndRemainder(S);
1066 b = divResult[1];
1067 dig = (char)(divResult[0].intValue() + '0');
1068 buf.append(dig);
1069 if (i >= ilim)
1070 break;
1071 b = b.multiply(BigInteger.valueOf(10));
1072 }
1073
1074 /* Round off last digit */
1075
1076 b = b.shiftLeft(1);
1077 j = b.compareTo(S);
1078 if ((j > 0) || (j == 0 && (((dig & 1) == 1) || biasUp))) {
1079 // roundoff:
1080 // while(*--s == '9')
1081 // if (s == buf) {
1082 // k++;
1083 // *s++ = '1';
1084 // goto ret;
1085 // }
1086 // ++*s++;
1087 if (roundOff(buf)) {
1088 k++;
1089 buf.append('1');
1090 return k + 1;
1091 }
1092 }
1093 else {
1094 stripTrailingZeroes(buf);
1095 // while(*--s == '0') ;
1096 // s++;
1097 }
1098 // ret:
1099 // Bfree(S);
1100 // if (mhi) {
1101 // if (mlo && mlo != mhi)
1102 // Bfree(mlo);
1103 // Bfree(mhi);
1104 // }
1105 // ret1:
1106 // Bfree(b);
1107 // JS_ASSERT(s < buf + bufsize);
1108 return k + 1;
1109 }
1110
1111 private static void
1112 stripTrailingZeroes(StringBuilder buf)
1113 {
1114 // while(*--s == '0') ;
1115 // s++;
1116 int bl = buf.length();
1117 while(bl-->0 && buf.charAt(bl) == '0') {
1118 // empty
1119 }
1120 buf.setLength(bl + 1);
1121 }
1122
1123 /* Mapping of JSDToStrMode -> JS_dtoa mode */
1124 private static final int dtoaModes[] = {
1125 0, /* DTOSTR_STANDARD */
1126 0, /* DTOSTR_STANDARD_EXPONENTIAL, */
1127 3, /* DTOSTR_FIXED, */
1128 2, /* DTOSTR_EXPONENTIAL, */
1129 2}; /* DTOSTR_PRECISION */
1130
1131 static void
1132 JS_dtostr(StringBuilder buffer, int mode, int precision, double d)
1133 {
1134 int decPt; /* Position of decimal point relative to first digit returned by JS_dtoa */
1135 boolean[] sign = new boolean[1]; /* true if the sign bit was set in d */
1136 int nDigits; /* Number of significand digits returned by JS_dtoa */
1137
1138 // JS_ASSERT(bufferSize >= (size_t)(mode <= DTOSTR_STANDARD_EXPONENTIAL ? DTOSTR_STANDARD_BUFFER_SIZE :
1139 // DTOSTR_VARIABLE_BUFFER_SIZE(precision)));
1140
1141 if (mode == DTOSTR_FIXED && (d >= 1e21 || d <= -1e21))
1142 mode = DTOSTR_STANDARD; /* Change mode here rather than below because the buffer may not be large enough to hold a large integer. */
1143
1144 decPt = JS_dtoa(d, dtoaModes[mode], mode >= DTOSTR_FIXED, precision, sign, buffer);
1145 nDigits = buffer.length();
1146
1147 /* If Infinity, -Infinity, or NaN, return the string regardless of the mode. */
1148 if (decPt != 9999) {
1149 boolean exponentialNotation = false;
1150 int minNDigits = 0; /* Minimum number of significand digits required by mode and precision */
1151 int p;
1152
1153 switch (mode) {
1154 case DTOSTR_STANDARD:
1155 if (decPt < -5 || decPt > 21)
1156 exponentialNotation = true;
1157 else
1158 minNDigits = decPt;
1159 break;
1160
1161 case DTOSTR_FIXED:
1162 if (precision >= 0)
1163 minNDigits = decPt + precision;
1164 else
1165 minNDigits = decPt;
1166 break;
1167
1168 case DTOSTR_EXPONENTIAL:
1169 // JS_ASSERT(precision > 0);
1170 minNDigits = precision;
1171 /* fallthru */
1172 case DTOSTR_STANDARD_EXPONENTIAL:
1173 exponentialNotation = true;
1174 break;
1175
1176 case DTOSTR_PRECISION:
1177 // JS_ASSERT(precision > 0);
1178 minNDigits = precision;
1179 if (decPt < -5 || decPt > precision)
1180 exponentialNotation = true;
1181 break;
1182 }
1183
1184 /* If the number has fewer than minNDigits, pad it with zeros at the end */
1185 if (nDigits < minNDigits) {
1186 p = minNDigits;
1187 nDigits = minNDigits;
1188 do {
1189 buffer.append('0');
1190 } while (buffer.length() != p);
1191 }
1192
1193 if (exponentialNotation) {
1194 /* Insert a decimal point if more than one significand digit */
1195 if (nDigits != 1) {
1196 buffer.insert(1, '.');
1197 }
1198 buffer.append('e');
1199 if ((decPt - 1) >= 0)
1200 buffer.append('+');
1201 buffer.append(decPt - 1);
1202 // JS_snprintf(numEnd, bufferSize - (numEnd - buffer), "e%+d", decPt-1);
1203 } else if (decPt != nDigits) {
1204 /* Some kind of a fraction in fixed notation */
1205 // JS_ASSERT(decPt <= nDigits);
1206 if (decPt > 0) {
1207 /* dd...dd . dd...dd */
1208 buffer.insert(decPt, '.');
1209 } else {
1210 /* 0 . 00...00dd...dd */
1211 for (int i = 0; i < 1 - decPt; i++)
1212 buffer.insert(0, '0');
1213 buffer.insert(1, '.');
1214 }
1215 }
1216 }
1217
1218 /* If negative and neither -0.0 nor NaN, output a leading '-'. */
1219 if (sign[0] &&
1220 !(word0(d) == Sign_bit && word1(d) == 0) &&
1221 !((word0(d) & Exp_mask) == Exp_mask &&
1222 ((word1(d) != 0) || ((word0(d) & Frac_mask) != 0)))) {
1223 buffer.insert(0, '-');
1224 }
1225 }
1226
1227 }
1228