Merge from vendor branch TNFTP:
[dragonfly.git] / lib / libc / stdlib / strtod.c
1 /*-
2  * Copyright (c) 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * $FreeBSD: src/lib/libc/stdlib/strtod.c,v 1.3.8.4 2002/08/31 22:26:35 dwmalone Exp $
34  * $DragonFly: src/lib/libc/stdlib/strtod.c,v 1.6 2006/09/10 21:22:32 swildner Exp $
35  *
36  * @(#)strtod.c 8.1 (Berkeley) 6/4/93
37  */
38
39 /****************************************************************
40  *
41  * The author of this software is David M. Gay.
42  *
43  * Copyright (c) 1991 by AT&T.
44  *
45  * Permission to use, copy, modify, and distribute this software for any
46  * purpose without fee is hereby granted, provided that this entire notice
47  * is included in all copies of any software which is or includes a copy
48  * or modification of this software and in all copies of the supporting
49  * documentation for such software.
50  *
51  * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
52  * WARRANTY.  IN PARTICULAR, NEITHER THE AUTHOR NOR AT&T MAKES ANY
53  * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
54  * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
55  *
56  ***************************************************************/
57
58 /* Please send bug reports to
59         David M. Gay
60         AT&T Bell Laboratories, Room 2C-463
61         600 Mountain Avenue
62         Murray Hill, NJ 07974-2070
63         U.S.A.
64         dmg@research.att.com or research!dmg
65  */
66
67 /* strtod for IEEE--arithmetic machines.
68  *
69  * This strtod returns a nearest machine number to the input decimal
70  * string (or sets errno to ERANGE).  With IEEE arithmetic, ties are
71  * broken by the IEEE round-even rule.  Otherwise ties are broken by
72  * biased rounding (add half and chop).
73  *
74  * Inspired loosely by William D. Clinger's paper "How to Read Floating
75  * Point Numbers Accurately" [Proc. ACM SIGPLAN '90, pp. 92-101].
76  *
77  * Modifications:
78  *
79  *      1. We only require IEEE double-precision arithmetic
80  *              (not IEEE double-extended).
81  *      2. We get by with floating-point arithmetic in a case that
82  *              Clinger missed -- when we're computing d * 10^n
83  *              for a small integer d and the integer n is not too
84  *              much larger than 22 (the maximum integer k for which
85  *              we can represent 10^k exactly), we may be able to
86  *              compute (d*10^k) * 10^(e-k) with just one roundoff.
87  *      3. Rather than a bit-at-a-time adjustment of the binary
88  *              result in the hard case, we use floating-point
89  *              arithmetic to determine the adjustment to within
90  *              one bit; only in really hard cases do we need to
91  *              compute a second residual.
92  *      4. Because of 3., we don't need a large table of powers of 10
93  *              for ten-to-e (just some small tables, e.g. of 10^k
94  *              for 0 <= k <= 22).
95  */
96
97 /*
98  * #define IEEE_8087 for IEEE-arithmetic machines where the least
99  *      significant byte has the lowest address.
100  * #define IEEE_MC68k for IEEE-arithmetic machines where the most
101  *      significant byte has the lowest address.
102  * #define Sudden_Underflow for IEEE-format machines without gradual
103  *      underflow (i.e., that flush to zero on underflow).
104  * #define Unsigned_Shifts if >> does treats its left operand as unsigned.
105  * #define No_leftright to omit left-right logic in fast floating-point
106  *      computation of dtoa.
107  * #define Check_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3.
108  * #define ROUND_BIASED for IEEE-format with biased rounding.
109  * #define Inaccurate_Divide for IEEE-format with correctly rounded
110  *      products but inaccurate quotients, e.g., for Intel i860.
111  * #define Just_16 to store 16 bits per 32-bit long when doing high-precision
112  *      integer arithmetic.  Whether this speeds things up or slows things
113  *      down depends on the machine and the number being converted.
114  */
115
116 #if defined(i386) || defined(mips) && defined(MIPSEL)
117 #define IEEE_8087
118 #else
119 #define IEEE_MC68k
120 #endif
121
122 #ifdef DEBUG
123 #include "stdio.h"
124 #define Bug(x) {fprintf(stderr, "%s\n", x); exit(1);}
125 #endif
126
127 #include <locale.h>
128 #ifdef __cplusplus
129 #include "malloc.h"
130 #include "memory.h"
131 #else
132 #include "stdlib.h"
133 #include "string.h"
134 #endif
135
136 #include "errno.h"
137 #include <ctype.h>
138 #include "float.h"
139
140 #ifndef __MATH_H__
141 #include "math.h"
142 #endif
143
144 #ifdef __cplusplus
145 extern "C" {
146 #endif
147
148 #ifndef CONST
149 #define CONST const
150 #endif
151
152 #ifdef Unsigned_Shifts
153 #define Sign_Extend(a,b) if (b < 0) a |= 0xffff0000;
154 #else
155 #define Sign_Extend(a,b) /*no-op*/
156 #endif
157
158 #if defined(IEEE_8087) + defined(IEEE_MC68k) != 1
159 Exactly one of IEEE_8087 or IEEE_MC68k should be defined.
160 #endif
161
162 union doubleasulongs {
163         double x;
164         unsigned long w[2];
165 };
166 #ifdef IEEE_8087
167 #define word0(x) (((union doubleasulongs *)&x)->w)[1]
168 #define word1(x) (((union doubleasulongs *)&x)->w)[0]
169 #else
170 #define word0(x) (((union doubleasulongs *)&x)->w)[0]
171 #define word1(x) (((union doubleasulongs *)&x)->w)[1]
172 #endif
173
174 /* The following definition of Storeinc is appropriate for MIPS processors.
175  * An alternative that might be better on some machines is
176  * #define Storeinc(a,b,c) (*a++ = b << 16 | c & 0xffff)
177  */
178 #if defined(IEEE_8087)
179 #define Storeinc(a,b,c) (((unsigned short *)a)[1] = (unsigned short)b, \
180 ((unsigned short *)a)[0] = (unsigned short)c, a++)
181 #else
182 #define Storeinc(a,b,c) (((unsigned short *)a)[0] = (unsigned short)b, \
183 ((unsigned short *)a)[1] = (unsigned short)c, a++)
184 #endif
185
186 /* #define P DBL_MANT_DIG */
187 /* Ten_pmax = floor(P*log(2)/log(5)) */
188 /* Bletch = (highest power of 2 < DBL_MAX_10_EXP) / 16 */
189 /* Quick_max = floor((P-1)*log(FLT_RADIX)/log(10) - 1) */
190 /* Int_max = floor(P*log(FLT_RADIX)/log(10) - 1) */
191
192 #if defined(IEEE_8087) + defined(IEEE_MC68k)
193 #define Exp_shift  20
194 #define Exp_shift1 20
195 #define Exp_msk1    0x100000
196 #define Exp_msk11   0x100000
197 #define Exp_mask  0x7ff00000
198 #define P 53
199 #define Bias 1023
200 #define IEEE_Arith
201 #define Emin (-1022)
202 #define Exp_1  0x3ff00000
203 #define Exp_11 0x3ff00000
204 #define Ebits 11
205 #define Frac_mask  0xfffff
206 #define Frac_mask1 0xfffff
207 #define Ten_pmax 22
208 #define Bletch 0x10
209 #define Bndry_mask  0xfffff
210 #define Bndry_mask1 0xfffff
211 #define LSB 1
212 #define Sign_bit 0x80000000
213 #define Log2P 1
214 #define Tiny0 0
215 #define Tiny1 1
216 #define Quick_max 14
217 #define Int_max 14
218 #define Infinite(x) (word0(x) == 0x7ff00000) /* sufficient test for here */
219 #endif
220
221 #ifndef IEEE_Arith
222 #define ROUND_BIASED
223 #endif
224
225 #define rounded_product(a,b) a *= b
226 #define rounded_quotient(a,b) a /= b
227
228 #define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
229 #define Big1 0xffffffff
230
231 #ifndef Just_16
232 /* When Pack_32 is not defined, we store 16 bits per 32-bit long.
233  * This makes some inner loops simpler and sometimes saves work
234  * during multiplications, but it often seems to make things slightly
235  * slower.  Hence the default is now to store 32 bits per long.
236  */
237 #ifndef Pack_32
238 #define Pack_32
239 #endif
240 #endif
241
242 #define Kmax 15
243
244 #ifdef __cplusplus
245 extern "C" double strtod(const char *s00, char **se);
246 extern "C" char *__dtoa(double d, int mode, int ndigits,
247                         int *decpt, int *sign, char **rve, char **resultp);
248 #endif
249
250 struct
251 Bigint {
252         struct Bigint *next;
253         int k, maxwds, sign, wds;
254         unsigned long x[1];
255 };
256
257 typedef struct Bigint Bigint;
258
259 static Bigint *
260 Balloc(int k)
261 {
262         int x;
263         Bigint *rv;
264
265         x = 1 << k;
266         rv = (Bigint *)malloc(sizeof(Bigint) + (x-1)*sizeof(long));
267         rv->k = k;
268         rv->maxwds = x;
269         rv->sign = rv->wds = 0;
270         return rv;
271 }
272
273 static void
274 Bfree(Bigint *v)
275 {
276         free(v);
277 }
278
279 #define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign, \
280 y->wds*sizeof(long) + 2*sizeof(int))
281
282 static Bigint *
283 multadd(Bigint *b, int m, int a)        /* multiply by m and add a */
284 {
285         int i, wds;
286         unsigned long *x, y;
287 #ifdef Pack_32
288         unsigned long xi, z;
289 #endif
290         Bigint *b1;
291
292         wds = b->wds;
293         x = b->x;
294         i = 0;
295         do {
296 #ifdef Pack_32
297                 xi = *x;
298                 y = (xi & 0xffff) * m + a;
299                 z = (xi >> 16) * m + (y >> 16);
300                 a = (int)(z >> 16);
301                 *x++ = (z << 16) + (y & 0xffff);
302 #else
303                 y = *x * m + a;
304                 a = (int)(y >> 16);
305                 *x++ = y & 0xffff;
306 #endif
307         } while (++i < wds);
308         if (a) {
309                 if (wds >= b->maxwds) {
310                         b1 = Balloc(b->k+1);
311                         Bcopy(b1, b);
312                         Bfree(b);
313                         b = b1;
314                         }
315                 b->x[wds++] = a;
316                 b->wds = wds;
317         }
318         return b;
319 }
320
321 static Bigint *
322 s2b(CONST char *s, int nd0, int nd, unsigned long y9)
323 {
324         Bigint *b;
325         int i, k;
326         long x, y;
327
328         x = (nd + 8) / 9;
329         for (k = 0, y = 1; x > y; y <<= 1, k++) ;
330 #ifdef Pack_32
331         b = Balloc(k);
332         b->x[0] = y9;
333         b->wds = 1;
334 #else
335         b = Balloc(k+1);
336         b->x[0] = y9 & 0xffff;
337         b->wds = (b->x[1] = y9 >> 16) ? 2 : 1;
338 #endif
339
340         i = 9;
341         if (9 < nd0) {
342                 s += 9;
343                 do
344                         b = multadd(b, 10, *s++ - '0');
345                 while (++i < nd0);
346                 s++;
347         } else
348                 s += 10;
349         for (; i < nd; i++)
350                 b = multadd(b, 10, *s++ - '0');
351         return b;
352 }
353
354 static int
355 hi0bits(unsigned long x)
356 {
357         int k = 0;
358
359         if (!(x & 0xffff0000)) {
360                 k = 16;
361                 x <<= 16;
362         }
363         if (!(x & 0xff000000)) {
364                 k += 8;
365                 x <<= 8;
366         }
367         if (!(x & 0xf0000000)) {
368                 k += 4;
369                 x <<= 4;
370         }
371         if (!(x & 0xc0000000)) {
372                 k += 2;
373                 x <<= 2;
374         }
375         if (!(x & 0x80000000)) {
376                 k++;
377                 if (!(x & 0x40000000))
378                         return 32;
379         }
380         return k;
381 }
382
383 static int
384 lo0bits(unsigned long *y)
385 {
386         int k;
387         unsigned long x = *y;
388
389         if (x & 7) {
390                 if (x & 1)
391                         return 0;
392                 if (x & 2) {
393                         *y = x >> 1;
394                         return 1;
395                 }
396                 *y = x >> 2;
397                 return 2;
398         }
399         k = 0;
400         if (!(x & 0xffff)) {
401                 k = 16;
402                 x >>= 16;
403         }
404         if (!(x & 0xff)) {
405                 k += 8;
406                 x >>= 8;
407         }
408         if (!(x & 0xf)) {
409                 k += 4;
410                 x >>= 4;
411         }
412         if (!(x & 0x3)) {
413                 k += 2;
414                 x >>= 2;
415         }
416         if (!(x & 1)) {
417                 k++;
418                 x >>= 1;
419                 if (!x & 1)
420                         return 32;
421         }
422         *y = x;
423         return k;
424 }
425
426 static Bigint *
427 i2b(int i)
428 {
429         Bigint *b;
430
431         b = Balloc(1);
432         b->x[0] = i;
433         b->wds = 1;
434         return b;
435         }
436
437 static Bigint *
438 mult(Bigint *a, Bigint *b)
439 {
440         Bigint *c;
441         int k, wa, wb, wc;
442         unsigned long carry, y, z;
443         unsigned long *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
444 #ifdef Pack_32
445         unsigned long z2;
446 #endif
447
448         if (a->wds < b->wds) {
449                 c = a;
450                 a = b;
451                 b = c;
452         }
453         k = a->k;
454         wa = a->wds;
455         wb = b->wds;
456         wc = wa + wb;
457         if (wc > a->maxwds)
458                 k++;
459         c = Balloc(k);
460         for (x = c->x, xa = x + wc; x < xa; x++)
461                 *x = 0;
462         xa = a->x;
463         xae = xa + wa;
464         xb = b->x;
465         xbe = xb + wb;
466         xc0 = c->x;
467 #ifdef Pack_32
468         for (; xb < xbe; xb++, xc0++) {
469                 if ( (y = *xb & 0xffff) ) {
470                         x = xa;
471                         xc = xc0;
472                         carry = 0;
473                         do {
474                                 z = (*x & 0xffff) * y + (*xc & 0xffff) + carry;
475                                 carry = z >> 16;
476                                 z2 = (*x++ >> 16) * y + (*xc >> 16) + carry;
477                                 carry = z2 >> 16;
478                                 Storeinc(xc, z2, z);
479                         } while (x < xae);
480                         *xc = carry;
481                 }
482                 if ( (y = *xb >> 16) ) {
483                         x = xa;
484                         xc = xc0;
485                         carry = 0;
486                         z2 = *xc;
487                         do {
488                                 z = (*x & 0xffff) * y + (*xc >> 16) + carry;
489                                 carry = z >> 16;
490                                 Storeinc(xc, z, z2);
491                                 z2 = (*x++ >> 16) * y + (*xc & 0xffff) + carry;
492                                 carry = z2 >> 16;
493                         } while (x < xae);
494                         *xc = z2;
495                 }
496         }
497 #else
498         for (; xb < xbe; xc0++) {
499                 if (y = *xb++) {
500                         x = xa;
501                         xc = xc0;
502                         carry = 0;
503                         do {
504                                 z = *x++ * y + *xc + carry;
505                                 carry = z >> 16;
506                                 *xc++ = z & 0xffff;
507                         } while (x < xae);
508                         *xc = carry;
509                 }
510         }
511 #endif
512         for (xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ;
513         c->wds = wc;
514         return c;
515 }
516
517 static Bigint *p5s;
518
519 static Bigint *
520 pow5mult(Bigint *b, int k)
521 {
522         Bigint *b1, *p5, *p51;
523         int i;
524         static int p05[3] = { 5, 25, 125 };
525
526         if ( (i = k & 3) )
527                 b = multadd(b, p05[i-1], 0);
528
529         if (!(k >>= 2))
530                 return b;
531         if (!(p5 = p5s)) {
532                 /* first time */
533                 p5 = p5s = i2b(625);
534                 p5->next = 0;
535         }
536         for (;;) {
537                 if (k & 1) {
538                         b1 = mult(b, p5);
539                         Bfree(b);
540                         b = b1;
541                 }
542                 if (!(k >>= 1))
543                         break;
544                 if (!(p51 = p5->next)) {
545                         p51 = p5->next = mult(p5,p5);
546                         p51->next = 0;
547                 }
548                 p5 = p51;
549         }
550         return b;
551 }
552
553 static Bigint *
554 lshift(Bigint *b, int k)
555 {
556         int i, k1, n, n1;
557         Bigint *b1;
558         unsigned long *x, *x1, *xe, z;
559
560 #ifdef Pack_32
561         n = k >> 5;
562 #else
563         n = k >> 4;
564 #endif
565         k1 = b->k;
566         n1 = n + b->wds + 1;
567         for (i = b->maxwds; n1 > i; i <<= 1)
568                 k1++;
569         b1 = Balloc(k1);
570         x1 = b1->x;
571         for (i = 0; i < n; i++)
572                 *x1++ = 0;
573         x = b->x;
574         xe = x + b->wds;
575 #ifdef Pack_32
576         if (k &= 0x1f) {
577                 k1 = 32 - k;
578                 z = 0;
579                 do {
580                         *x1++ = *x << k | z;
581                         z = *x++ >> k1;
582                 } while (x < xe);
583                 if ( (*x1 = z) )
584                         ++n1;
585         }
586 #else
587         if (k &= 0xf) {
588                 k1 = 16 - k;
589                 z = 0;
590                 do {
591                         *x1++ = *x << k  & 0xffff | z;
592                         z = *x++ >> k1;
593                 } while (x < xe);
594                 if (*x1 = z)
595                         ++n1;
596         }
597 #endif
598         else
599                 do
600                         *x1++ = *x++;
601                 while (x < xe);
602         b1->wds = n1 - 1;
603         Bfree(b);
604         return b1;
605 }
606
607 static int
608 cmp(Bigint *a, Bigint *b)
609 {
610         unsigned long *xa, *xa0, *xb, *xb0;
611         int i, j;
612
613         i = a->wds;
614         j = b->wds;
615 #ifdef DEBUG
616         if (i > 1 && !a->x[i-1])
617                 Bug("cmp called with a->x[a->wds-1] == 0");
618         if (j > 1 && !b->x[j-1])
619                 Bug("cmp called with b->x[b->wds-1] == 0");
620 #endif
621         if (i -= j)
622                 return i;
623         xa0 = a->x;
624         xa = xa0 + j;
625         xb0 = b->x;
626         xb = xb0 + j;
627         for (;;) {
628                 if (*--xa != *--xb)
629                         return *xa < *xb ? -1 : 1;
630                 if (xa <= xa0)
631                         break;
632         }
633         return 0;
634 }
635
636 static Bigint *
637 diff(Bigint *a, Bigint *b)
638 {
639         Bigint *c;
640         int i, wa, wb;
641         long borrow, y; /* We need signed shifts here. */
642         unsigned long *xa, *xae, *xb, *xbe, *xc;
643 #ifdef Pack_32
644         long z;
645 #endif
646
647         i = cmp(a,b);
648         if (!i) {
649                 c = Balloc(0);
650                 c->wds = 1;
651                 c->x[0] = 0;
652                 return c;
653         }
654         if (i < 0) {
655                 c = a;
656                 a = b;
657                 b = c;
658                 i = 1;
659         } else
660                 i = 0;
661         c = Balloc(a->k);
662         c->sign = i;
663         wa = a->wds;
664         xa = a->x;
665         xae = xa + wa;
666         wb = b->wds;
667         xb = b->x;
668         xbe = xb + wb;
669         xc = c->x;
670         borrow = 0;
671 #ifdef Pack_32
672         do {
673                 y = (*xa & 0xffff) - (*xb & 0xffff) + borrow;
674                 borrow = y >> 16;
675                 Sign_Extend(borrow, y);
676                 z = (*xa++ >> 16) - (*xb++ >> 16) + borrow;
677                 borrow = z >> 16;
678                 Sign_Extend(borrow, z);
679                 Storeinc(xc, z, y);
680         } while (xb < xbe);
681         while (xa < xae) {
682                 y = (*xa & 0xffff) + borrow;
683                 borrow = y >> 16;
684                 Sign_Extend(borrow, y);
685                 z = (*xa++ >> 16) + borrow;
686                 borrow = z >> 16;
687                 Sign_Extend(borrow, z);
688                 Storeinc(xc, z, y);
689         }
690 #else
691         do {
692                 y = *xa++ - *xb++ + borrow;
693                 borrow = y >> 16;
694                 Sign_Extend(borrow, y);
695                 *xc++ = y & 0xffff;
696         } while (xb < xbe);
697         while (xa < xae) {
698                 y = *xa++ + borrow;
699                 borrow = y >> 16;
700                 Sign_Extend(borrow, y);
701                 *xc++ = y & 0xffff;
702         }
703 #endif
704         while (!*--xc)
705                 wa--;
706         c->wds = wa;
707         return c;
708 }
709
710 static double
711 ulp(double x)
712 {
713         long L;
714         double a;
715
716         L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1;
717 #ifndef Sudden_Underflow
718         if (L > 0) {
719 #endif
720                 word0(a) = L;
721                 word1(a) = 0;
722 #ifndef Sudden_Underflow
723         } else {
724                 L = -L >> Exp_shift;
725                 if (L < Exp_shift) {
726                         word0(a) = 0x80000 >> L;
727                         word1(a) = 0;
728                 } else {
729                         word0(a) = 0;
730                         L -= Exp_shift;
731                         word1(a) = L >= 31 ? 1 : 1 << (31 - L);
732                 }
733         }
734 #endif
735         return a;
736 }
737
738 static double
739 b2d(Bigint *a, int *e)
740 {
741         unsigned long *xa, *xa0, w, y, z;
742         int k;
743         double d;
744 #define d0 word0(d)
745 #define d1 word1(d)
746
747         xa0 = a->x;
748         xa = xa0 + a->wds;
749         y = *--xa;
750 #ifdef DEBUG
751         if (!y) Bug("zero y in b2d");
752 #endif
753         k = hi0bits(y);
754         *e = 32 - k;
755 #ifdef Pack_32
756         if (k < Ebits) {
757                 d0 = Exp_1 | (y >> (Ebits - k));
758                 w = xa > xa0 ? *--xa : 0;
759                 d1 = (y << ((32-Ebits) + k)) | (w >> (Ebits - k));
760                 goto ret_d;
761                 }
762         z = xa > xa0 ? *--xa : 0;
763         if (k -= Ebits) {
764                 d0 = Exp_1 | (y << k) | (z >> (32 - k));
765                 y = xa > xa0 ? *--xa : 0;
766                 d1 = (z << k) | (y >> (32 - k));
767         } else {
768                 d0 = Exp_1 | y;
769                 d1 = z;
770         }
771 #else
772         if (k < Ebits + 16) {
773                 z = xa > xa0 ? *--xa : 0;
774                 d0 = Exp_1 | y << k - Ebits | z >> Ebits + 16 - k;
775                 w = xa > xa0 ? *--xa : 0;
776                 y = xa > xa0 ? *--xa : 0;
777                 d1 = z << k + 16 - Ebits | w << k - Ebits | y >> 16 + Ebits - k;
778                 goto ret_d;
779         }
780         z = xa > xa0 ? *--xa : 0;
781         w = xa > xa0 ? *--xa : 0;
782         k -= Ebits + 16;
783         d0 = Exp_1 | y << k + 16 | z << k | w >> 16 - k;
784         y = xa > xa0 ? *--xa : 0;
785         d1 = w << k + 16 | y << k;
786 #endif
787 ret_d:
788 #undef d0
789 #undef d1
790         return d;
791 }
792
793 static Bigint *
794 d2b(double d, int *e, int *bits)
795 {
796         Bigint *b;
797         int de, i, k;
798         unsigned long *x, y, z;
799 #define d0 word0(d)
800 #define d1 word1(d)
801
802 #ifdef Pack_32
803         b = Balloc(1);
804 #else
805         b = Balloc(2);
806 #endif
807         x = b->x;
808
809         z = d0 & Frac_mask;
810         d0 &= 0x7fffffff;       /* clear sign bit, which we ignore */
811 #ifdef Sudden_Underflow
812         de = (int)(d0 >> Exp_shift);
813         z |= Exp_msk11;
814 #else
815         if ( (de = (int)(d0 >> Exp_shift)) )
816                 z |= Exp_msk1;
817 #endif
818 #ifdef Pack_32
819         if ( (y = d1) ) {
820                 if ( (k = lo0bits(&y)) ) {
821                         x[0] = y | (z << (32 - k));
822                         z >>= k;
823                         }
824                 else
825                         x[0] = y;
826                 i = b->wds = (x[1] = z) ? 2 : 1;
827         } else {
828 #ifdef DEBUG
829                 if (!z)
830                         Bug("Zero passed to d2b");
831 #endif
832                 k = lo0bits(&z);
833                 x[0] = z;
834                 i = b->wds = 1;
835                 k += 32;
836         }
837 #else
838         if (y = d1) {
839                 if (k = lo0bits(&y))
840                         if (k >= 16) {
841                                 x[0] = y | z << 32 - k & 0xffff;
842                                 x[1] = z >> k - 16 & 0xffff;
843                                 x[2] = z >> k;
844                                 i = 2;
845                         } else {
846                                 x[0] = y & 0xffff;
847                                 x[1] = y >> 16 | z << 16 - k & 0xffff;
848                                 x[2] = z >> k & 0xffff;
849                                 x[3] = z >> k+16;
850                                 i = 3;
851                         }
852                 else {
853                         x[0] = y & 0xffff;
854                         x[1] = y >> 16;
855                         x[2] = z & 0xffff;
856                         x[3] = z >> 16;
857                         i = 3;
858                 }
859         } else {
860 #ifdef DEBUG
861                 if (!z)
862                         Bug("Zero passed to d2b");
863 #endif
864                 k = lo0bits(&z);
865                 if (k >= 16) {
866                         x[0] = z;
867                         i = 0;
868                 } else {
869                         x[0] = z & 0xffff;
870                         x[1] = z >> 16;
871                         i = 1;
872                 }
873                 k += 32;
874         }
875         while (!x[i])
876                 --i;
877         b->wds = i + 1;
878 #endif
879 #ifndef Sudden_Underflow
880         if (de) {
881 #endif
882                 *e = de - Bias - (P-1) + k;
883                 *bits = P - k;
884 #ifndef Sudden_Underflow
885         } else {
886                 *e = de - Bias - (P-1) + 1 + k;
887 #ifdef Pack_32
888                 *bits = 32*i - hi0bits(x[i-1]);
889 #else
890                 *bits = (i+2)*16 - hi0bits(x[i]);
891 #endif
892         }
893 #endif
894         return b;
895 }
896 #undef d0
897 #undef d1
898
899 static double
900 ratio(Bigint *a, Bigint *b)
901 {
902         double da, db;
903         int k, ka, kb;
904
905         da = b2d(a, &ka);
906         db = b2d(b, &kb);
907 #ifdef Pack_32
908         k = ka - kb + 32*(a->wds - b->wds);
909 #else
910         k = ka - kb + 16*(a->wds - b->wds);
911 #endif
912         if (k > 0)
913                 word0(da) += k*Exp_msk1;
914         else {
915                 k = -k;
916                 word0(db) += k*Exp_msk1;
917         }
918         return da / db;
919 }
920
921 static double
922 tens[] = {
923                 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
924                 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
925                 1e20, 1e21, 1e22
926                 };
927
928 static double
929 #ifdef IEEE_Arith
930 bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 };
931 static double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128, 1e-256 };
932 #define n_bigtens 5
933 #else
934 bigtens[] = { 1e16, 1e32 };
935 static double tinytens[] = { 1e-16, 1e-32 };
936 #define n_bigtens 2
937 #endif
938
939 double
940 strtod(CONST char *s00, char **se)
941 {
942         int bb2, bb5, bbe, bd2, bd5, bbbits, bs2, c, dsign,
943                  e, e1, esign, i, j, k, nd, nd0, nf, nz, nz0, sign;
944         CONST char *s, *s0, *s1;
945         double aadj, aadj1, adj, rv, rv0;
946         long L;
947         unsigned long y, z;
948         Bigint *bb, *bb1, *bd, *bd0, *bs, *delta;
949         char decimal_point = localeconv()->decimal_point[0];
950
951         sign = nz0 = nz = 0;
952         rv = 0.;
953         for (s = s00;;s++) switch(*s) {
954                 case '-':
955                         sign = 1;
956                         /* no break */
957                 case '+':
958                         if (*++s)
959                                 goto break2;
960                         /* no break */
961                 case 0:
962                         s = s00;
963                         goto ret;
964                 default:
965                         if (isspace((unsigned char)*s))
966                                 continue;
967                         goto break2;
968         }
969 break2:
970         if (*s == '0') {
971                 nz0 = 1;
972                 while (*++s == '0') ;
973                 if (!*s)
974                         goto ret;
975         }
976         s0 = s;
977         y = z = 0;
978         for (nd = nf = 0; (c = *s) >= '0' && c <= '9'; nd++, s++)
979                 if (nd < 9)
980                         y = 10*y + c - '0';
981                 else if (nd < 16)
982                         z = 10*z + c - '0';
983         nd0 = nd;
984         if ((char)c == decimal_point) {
985                 c = *++s;
986                 if (!nd) {
987                         for (; c == '0'; c = *++s)
988                                 nz++;
989                         if (c > '0' && c <= '9') {
990                                 s0 = s;
991                                 nf += nz;
992                                 nz = 0;
993                                 goto have_dig;
994                         }
995                         goto dig_done;
996                 }
997                 for (; c >= '0' && c <= '9'; c = *++s) {
998 have_dig:
999                         nz++;
1000                         if (c -= '0') {
1001                                 nf += nz;
1002                                 for (i = 1; i < nz; i++)
1003                                         if (nd++ < 9)
1004                                                 y *= 10;
1005                                         else if (nd <= DBL_DIG + 1)
1006                                                 z *= 10;
1007                                 if (nd++ < 9)
1008                                         y = 10*y + c;
1009                                 else if (nd <= DBL_DIG + 1)
1010                                         z = 10*z + c;
1011                                 nz = 0;
1012                         }
1013                 }
1014         }
1015 dig_done:
1016         e = 0;
1017         if (c == 'e' || c == 'E') {
1018                 if (!nd && !nz && !nz0) {
1019                         s = s00;
1020                         goto ret;
1021                 }
1022                 s00 = s;
1023                 esign = 0;
1024                 switch(c = *++s) {
1025                         case '-':
1026                                 esign = 1;
1027                         case '+':
1028                                 c = *++s;
1029                 }
1030                 if (c >= '0' && c <= '9') {
1031                         while (c == '0')
1032                                 c = *++s;
1033                         if (c > '0' && c <= '9') {
1034                                 L = c - '0';
1035                                 s1 = s;
1036                                 while ((c = *++s) >= '0' && c <= '9')
1037                                         L = 10*L + c - '0';
1038                                 if (s - s1 > 8 || L > 19999)
1039                                         /* Avoid confusion from exponents
1040                                          * so large that e might overflow.
1041                                          */
1042                                         e = 19999; /* safe for 16 bit ints */
1043                                 else
1044                                         e = (int)L;
1045                                 if (esign)
1046                                         e = -e;
1047                         } else
1048                                 e = 0;
1049                 } else
1050                         s = s00;
1051         }
1052         if (!nd) {
1053                 if (!nz && !nz0)
1054                         s = s00;
1055                 goto ret;
1056         }
1057         e1 = e -= nf;
1058
1059         /* Now we have nd0 digits, starting at s0, followed by a
1060          * decimal point, followed by nd-nd0 digits.  The number we're
1061          * after is the integer represented by those digits times
1062          * 10**e */
1063
1064         if (!nd0)
1065                 nd0 = nd;
1066         k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;
1067         rv = y;
1068         if (k > 9)
1069                 rv = tens[k - 9] * rv + z;
1070         if (nd <= DBL_DIG) {
1071                 if (!e)
1072                         goto ret;
1073                 if (e > 0) {
1074                         if (e <= Ten_pmax) {
1075                                 /* rv = */ rounded_product(rv, tens[e]);
1076                                 goto ret;
1077                                 }
1078                         i = DBL_DIG - nd;
1079                         if (e <= Ten_pmax + i) {
1080                                 /* A fancier test would sometimes let us do
1081                                  * this for larger i values.
1082                                  */
1083                                 e -= i;
1084                                 rv *= tens[i];
1085                                 /* rv = */ rounded_product(rv, tens[e]);
1086                                 goto ret;
1087                         }
1088                 }
1089 #ifndef Inaccurate_Divide
1090                 else if (e >= -Ten_pmax) {
1091                         /* rv = */ rounded_quotient(rv, tens[-e]);
1092                         goto ret;
1093                 }
1094 #endif
1095         }
1096         e1 += nd - k;
1097
1098         /* Get starting approximation = rv * 10**e1 */
1099
1100         if (e1 > 0) {
1101                 if ( (i = e1 & 15) )
1102                         rv *= tens[i];
1103                 if ( (e1 &= ~15) ) {
1104                         if (e1 > DBL_MAX_10_EXP) {
1105 ovfl:
1106                                 errno = ERANGE;
1107                                 rv = HUGE_VAL;
1108                                 goto ret;
1109                         }
1110                         if (e1 >>= 4) {
1111                                 for (j = 0; e1 > 1; j++, e1 >>= 1)
1112                                         if (e1 & 1)
1113                                                 rv *= bigtens[j];
1114                         /* The last multiplication could overflow. */
1115                                 word0(rv) -= P*Exp_msk1;
1116                                 rv *= bigtens[j];
1117                                 if ((z = word0(rv) & Exp_mask)
1118                                  > Exp_msk1*(DBL_MAX_EXP+Bias-P))
1119                                         goto ovfl;
1120                                 if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) {
1121                                         /* set to largest number */
1122                                         /* (Can't trust DBL_MAX) */
1123                                         word0(rv) = Big0;
1124                                         word1(rv) = Big1;
1125                                         }
1126                                 else
1127                                         word0(rv) += P*Exp_msk1;
1128                         }
1129                 }
1130         } else if (e1 < 0) {
1131                 e1 = -e1;
1132                 if ( (i = e1 & 15) )
1133                         rv /= tens[i];
1134                 if ( (e1 &= ~15) ) {
1135                         e1 >>= 4;
1136                         for (j = 0; e1 > 1; j++, e1 >>= 1)
1137                                 if (e1 & 1)
1138                                         rv *= tinytens[j];
1139                         /* The last multiplication could underflow. */
1140                         rv0 = rv;
1141                         rv *= tinytens[j];
1142                         if (!rv) {
1143                                 rv = 2.*rv0;
1144                                 rv *= tinytens[j];
1145                                 if (!rv) {
1146 undfl:
1147                                         rv = 0.;
1148                                         errno = ERANGE;
1149                                         goto ret;
1150                                         }
1151                                 word0(rv) = Tiny0;
1152                                 word1(rv) = Tiny1;
1153                                 /* The refinement below will clean
1154                                  * this approximation up.
1155                                  */
1156                         }
1157                 }
1158         }
1159
1160         /* Now the hard part -- adjusting rv to the correct value.*/
1161
1162         /* Put digits into bd: true value = bd * 10^e */
1163
1164         bd0 = s2b(s0, nd0, nd, y);
1165
1166         for (;;) {
1167                 bd = Balloc(bd0->k);
1168                 Bcopy(bd, bd0);
1169                 bb = d2b(rv, &bbe, &bbbits);    /* rv = bb * 2^bbe */
1170                 bs = i2b(1);
1171
1172                 if (e >= 0) {
1173                         bb2 = bb5 = 0;
1174                         bd2 = bd5 = e;
1175                 } else {
1176                         bb2 = bb5 = -e;
1177                         bd2 = bd5 = 0;
1178                 }
1179                 if (bbe >= 0)
1180                         bb2 += bbe;
1181                 else
1182                         bd2 -= bbe;
1183                 bs2 = bb2;
1184 #ifdef Sudden_Underflow
1185                 j = P + 1 - bbbits;
1186 #else
1187                 i = bbe + bbbits - 1;   /* logb(rv) */
1188                 if (i < Emin)   /* denormal */
1189                         j = bbe + (P-Emin);
1190                 else
1191                         j = P + 1 - bbbits;
1192 #endif
1193                 bb2 += j;
1194                 bd2 += j;
1195                 i = bb2 < bd2 ? bb2 : bd2;
1196                 if (i > bs2)
1197                         i = bs2;
1198                 if (i > 0) {
1199                         bb2 -= i;
1200                         bd2 -= i;
1201                         bs2 -= i;
1202                         }
1203                 if (bb5 > 0) {
1204                         bs = pow5mult(bs, bb5);
1205                         bb1 = mult(bs, bb);
1206                         Bfree(bb);
1207                         bb = bb1;
1208                         }
1209                 if (bb2 > 0)
1210                         bb = lshift(bb, bb2);
1211                 if (bd5 > 0)
1212                         bd = pow5mult(bd, bd5);
1213                 if (bd2 > 0)
1214                         bd = lshift(bd, bd2);
1215                 if (bs2 > 0)
1216                         bs = lshift(bs, bs2);
1217                 delta = diff(bb, bd);
1218                 dsign = delta->sign;
1219                 delta->sign = 0;
1220                 i = cmp(delta, bs);
1221                 if (i < 0) {
1222                         /* Error is less than half an ulp -- check for
1223                          * special case of mantissa a power of two.
1224                          */
1225                         if (dsign || word1(rv) || word0(rv) & Bndry_mask)
1226                                 break;
1227                         delta = lshift(delta,Log2P);
1228                         if (cmp(delta, bs) > 0)
1229                                 goto drop_down;
1230                         break;
1231                 }
1232                 if (i == 0) {
1233                         /* exactly half-way between */
1234                         if (dsign) {
1235                                 if ((word0(rv) & Bndry_mask1) == Bndry_mask1
1236                                  &&  word1(rv) == 0xffffffff) {
1237                                         /*boundary case -- increment exponent*/
1238                                         word0(rv) = (word0(rv) & Exp_mask)
1239                                                 + Exp_msk1;
1240                                         word1(rv) = 0;
1241                                         break;
1242                                 }
1243                         } else if (!(word0(rv) & Bndry_mask) && !word1(rv)) {
1244 drop_down:
1245                                 /* boundary case -- decrement exponent */
1246 #ifdef Sudden_Underflow
1247                                 L = word0(rv) & Exp_mask;
1248                                 if (L <= Exp_msk1)
1249                                         goto undfl;
1250                                 L -= Exp_msk1;
1251 #else
1252                                 L = (word0(rv) & Exp_mask) - Exp_msk1;
1253 #endif
1254                                 word0(rv) = L | Bndry_mask1;
1255                                 word1(rv) = 0xffffffff;
1256                                 break;
1257                         }
1258 #ifndef ROUND_BIASED
1259                         if (!(word1(rv) & LSB))
1260                                 break;
1261 #endif
1262                         if (dsign)
1263                                 rv += ulp(rv);
1264 #ifndef ROUND_BIASED
1265                         else {
1266                                 rv -= ulp(rv);
1267 #ifndef Sudden_Underflow
1268                                 if (!rv)
1269                                         goto undfl;
1270 #endif
1271                         }
1272 #endif
1273                         break;
1274                 }
1275                 if ((aadj = ratio(delta, bs)) <= 2.) {
1276                         if (dsign)
1277                                 aadj = aadj1 = 1.;
1278                         else if (word1(rv) || word0(rv) & Bndry_mask) {
1279 #ifndef Sudden_Underflow
1280                                 if (word1(rv) == Tiny1 && !word0(rv))
1281                                         goto undfl;
1282 #endif
1283                                 aadj = 1.;
1284                                 aadj1 = -1.;
1285                         } else {
1286                                 /* special case -- power of FLT_RADIX to be */
1287                                 /* rounded down... */
1288
1289                                 if (aadj < 2./FLT_RADIX)
1290                                         aadj = 1./FLT_RADIX;
1291                                 else
1292                                         aadj *= 0.5;
1293                                 aadj1 = -aadj;
1294                         }
1295                 } else {
1296                         aadj *= 0.5;
1297                         aadj1 = dsign ? aadj : -aadj;
1298 #ifdef Check_FLT_ROUNDS
1299                         switch(FLT_ROUNDS) {
1300                                 case 2: /* towards +infinity */
1301                                         aadj1 -= 0.5;
1302                                         break;
1303                                 case 0: /* towards 0 */
1304                                 case 3: /* towards -infinity */
1305                                         aadj1 += 0.5;
1306                         }
1307 #else
1308                         if (FLT_ROUNDS == 0)
1309                                 aadj1 += 0.5;
1310 #endif
1311                 }
1312                 y = word0(rv) & Exp_mask;
1313
1314                 /* Check for overflow */
1315
1316                 if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) {
1317                         rv0 = rv;
1318                         word0(rv) -= P*Exp_msk1;
1319                         adj = aadj1 * ulp(rv);
1320                         rv += adj;
1321                         if ((word0(rv) & Exp_mask) >=
1322                                         Exp_msk1*(DBL_MAX_EXP+Bias-P)) {
1323                                 if (word0(rv0) == Big0 && word1(rv0) == Big1)
1324                                         goto ovfl;
1325                                 word0(rv) = Big0;
1326                                 word1(rv) = Big1;
1327                                 goto cont;
1328                         } else
1329                                 word0(rv) += P*Exp_msk1;
1330                 } else {
1331 #ifdef Sudden_Underflow
1332                         if ((word0(rv) & Exp_mask) <= P*Exp_msk1) {
1333                                 rv0 = rv;
1334                                 word0(rv) += P*Exp_msk1;
1335                                 adj = aadj1 * ulp(rv);
1336                                 rv += adj;
1337                                 if ((word0(rv) & Exp_mask) <= P*Exp_msk1)
1338                                 {
1339                                         if (word0(rv0) == Tiny0
1340                                          && word1(rv0) == Tiny1)
1341                                                 goto undfl;
1342                                         word0(rv) = Tiny0;
1343                                         word1(rv) = Tiny1;
1344                                         goto cont;
1345                                 } else
1346                                         word0(rv) -= P*Exp_msk1;
1347                         } else {
1348                                 adj = aadj1 * ulp(rv);
1349                                 rv += adj;
1350                         }
1351 #else
1352                         /* Compute adj so that the IEEE rounding rules will
1353                          * correctly round rv + adj in some half-way cases.
1354                          * If rv * ulp(rv) is denormalized (i.e.,
1355                          * y <= (P-1)*Exp_msk1), we must adjust aadj to avoid
1356                          * trouble from bits lost to denormalization;
1357                          * example: 1.2e-307 .
1358                          */
1359                         if (y <= (P-1)*Exp_msk1 && aadj >= 1.) {
1360                                 aadj1 = (double)(int)(aadj + 0.5);
1361                                 if (!dsign)
1362                                         aadj1 = -aadj1;
1363                         }
1364                         adj = aadj1 * ulp(rv);
1365                         rv += adj;
1366 #endif
1367                 }
1368                 z = word0(rv) & Exp_mask;
1369                 if (y == z) {
1370                         /* Can we stop now? */
1371                         L = aadj;
1372                         aadj -= L;
1373                         /* The tolerances below are conservative. */
1374                         if (dsign || word1(rv) || word0(rv) & Bndry_mask) {
1375                                 if (aadj < .4999999 || aadj > .5000001)
1376                                         break;
1377                         } else if (aadj < .4999999/FLT_RADIX)
1378                                 break;
1379                 }
1380 cont:
1381                 Bfree(bb);
1382                 Bfree(bd);
1383                 Bfree(bs);
1384                 Bfree(delta);
1385         }
1386         Bfree(bb);
1387         Bfree(bd);
1388         Bfree(bs);
1389         Bfree(bd0);
1390         Bfree(delta);
1391 ret:
1392         if (se)
1393                 *se = (char *)s;
1394         return sign ? -rv : rv;
1395 }
1396
1397 static int
1398 quorem(Bigint *b, Bigint *S)
1399 {
1400         int n;
1401         long borrow, y;
1402         unsigned long carry, q, ys;
1403         unsigned long *bx, *bxe, *sx, *sxe;
1404 #ifdef Pack_32
1405         long z;
1406         unsigned long si, zs;
1407 #endif
1408
1409         n = S->wds;
1410 #ifdef DEBUG
1411         /*debug*/ if (b->wds > n)
1412         /*debug*/       Bug("oversize b in quorem");
1413 #endif
1414         if (b->wds < n)
1415                 return 0;
1416         sx = S->x;
1417         sxe = sx + --n;
1418         bx = b->x;
1419         bxe = bx + n;
1420         q = *bxe / (*sxe + 1);  /* ensure q <= true quotient */
1421 #ifdef DEBUG
1422         /*debug*/ if (q > 9)
1423         /*debug*/       Bug("oversized quotient in quorem");
1424 #endif
1425         if (q) {
1426                 borrow = 0;
1427                 carry = 0;
1428                 do {
1429 #ifdef Pack_32
1430                         si = *sx++;
1431                         ys = (si & 0xffff) * q + carry;
1432                         zs = (si >> 16) * q + (ys >> 16);
1433                         carry = zs >> 16;
1434                         y = (*bx & 0xffff) - (ys & 0xffff) + borrow;
1435                         borrow = y >> 16;
1436                         Sign_Extend(borrow, y);
1437                         z = (*bx >> 16) - (zs & 0xffff) + borrow;
1438                         borrow = z >> 16;
1439                         Sign_Extend(borrow, z);
1440                         Storeinc(bx, z, y);
1441 #else
1442                         ys = *sx++ * q + carry;
1443                         carry = ys >> 16;
1444                         y = *bx - (ys & 0xffff) + borrow;
1445                         borrow = y >> 16;
1446                         Sign_Extend(borrow, y);
1447                         *bx++ = y & 0xffff;
1448 #endif
1449                 } while (sx <= sxe);
1450                 if (!*bxe) {
1451                         bx = b->x;
1452                         while (--bxe > bx && !*bxe)
1453                                 --n;
1454                         b->wds = n;
1455                 }
1456         }
1457         if (cmp(b, S) >= 0) {
1458                 q++;
1459                 borrow = 0;
1460                 carry = 0;
1461                 bx = b->x;
1462                 sx = S->x;
1463                 do {
1464 #ifdef Pack_32
1465                         si = *sx++;
1466                         ys = (si & 0xffff) + carry;
1467                         zs = (si >> 16) + (ys >> 16);
1468                         carry = zs >> 16;
1469                         y = (*bx & 0xffff) - (ys & 0xffff) + borrow;
1470                         borrow = y >> 16;
1471                         Sign_Extend(borrow, y);
1472                         z = (*bx >> 16) - (zs & 0xffff) + borrow;
1473                         borrow = z >> 16;
1474                         Sign_Extend(borrow, z);
1475                         Storeinc(bx, z, y);
1476 #else
1477                         ys = *sx++ + carry;
1478                         carry = ys >> 16;
1479                         y = *bx - (ys & 0xffff) + borrow;
1480                         borrow = y >> 16;
1481                         Sign_Extend(borrow, y);
1482                         *bx++ = y & 0xffff;
1483 #endif
1484                 } while (sx <= sxe);
1485                 bx = b->x;
1486                 bxe = bx + n;
1487                 if (!*bxe) {
1488                         while (--bxe > bx && !*bxe)
1489                                 --n;
1490                         b->wds = n;
1491                 }
1492         }
1493         return q;
1494 }
1495
1496 /* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
1497  *
1498  * Inspired by "How to Print Floating-Point Numbers Accurately" by
1499  * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 92-101].
1500  *
1501  * Modifications:
1502  *      1. Rather than iterating, we use a simple numeric overestimate
1503  *         to determine k = floor(log10(d)).  We scale relevant
1504  *         quantities using O(log2(k)) rather than O(k) multiplications.
1505  *      2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
1506  *         try to generate digits strictly left to right.  Instead, we
1507  *         compute with fewer bits and propagate the carry if necessary
1508  *         when rounding the final digit up.  This is often faster.
1509  *      3. Under the assumption that input will be rounded nearest,
1510  *         mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
1511  *         That is, we allow equality in stopping tests when the
1512  *         round-nearest rule will give the same floating-point value
1513  *         as would satisfaction of the stopping test with strict
1514  *         inequality.
1515  *      4. We remove common factors of powers of 2 from relevant
1516  *         quantities.
1517  *      5. When converting floating-point integers less than 1e16,
1518  *         we use floating-point arithmetic rather than resorting
1519  *         to multiple-precision integers.
1520  *      6. When asked to produce fewer than 15 digits, we first try
1521  *         to get by with floating-point arithmetic; we resort to
1522  *         multiple-precision integer arithmetic only if we cannot
1523  *         guarantee that the floating-point calculation has given
1524  *         the correctly rounded result.  For k requested digits and
1525  *         "uniformly" distributed input, the probability is
1526  *         something like 10^(k-15) that we must resort to the long
1527  *         calculation.
1528  */
1529
1530 char *
1531 __dtoa(double d, int mode, int ndigits, int *decpt, int *sign, char **rve,
1532        char **resultp)
1533 {
1534  /*     Arguments ndigits, decpt, sign are similar to those
1535         of ecvt and fcvt; trailing zeros are suppressed from
1536         the returned string.  If not null, *rve is set to point
1537         to the end of the return value.  If d is +-Infinity or NaN,
1538         then *decpt is set to 9999.
1539
1540         mode:
1541                 0 ==> shortest string that yields d when read in
1542                         and rounded to nearest.
1543                 1 ==> like 0, but with Steele & White stopping rule;
1544                         e.g. with IEEE P754 arithmetic , mode 0 gives
1545                         1e23 whereas mode 1 gives 9.999999999999999e22.
1546                 2 ==> max(1,ndigits) significant digits.  This gives a
1547                         return value similar to that of ecvt, except
1548                         that trailing zeros are suppressed.
1549                 3 ==> through ndigits past the decimal point.  This
1550                         gives a return value similar to that from fcvt,
1551                         except that trailing zeros are suppressed, and
1552                         ndigits can be negative.
1553                 4-9 should give the same return values as 2-3, i.e.,
1554                         4 <= mode <= 9 ==> same return as mode
1555                         2 + (mode & 1).  These modes are mainly for
1556                         debugging; often they run slower but sometimes
1557                         faster than modes 2-3.
1558                 4,5,8,9 ==> left-to-right digit generation.
1559                 6-9 ==> don't try fast floating-point estimate
1560                         (if applicable).
1561
1562                 Values of mode other than 0-9 are treated as mode 0.
1563
1564                 Sufficient space is allocated to the return value
1565                 to hold the suppressed trailing zeros.
1566         */
1567
1568         int bbits, b2, b5, be, dig, i, ieps, ilim, ilim0, ilim1,
1569                 j, j1, k, k0, k_check, leftright, m2, m5, s2, s5,
1570                 spec_case, try_quick;
1571         long L;
1572 #ifndef Sudden_Underflow
1573         int denorm;
1574         unsigned long x;
1575 #endif
1576         Bigint *b, *b1, *delta, *mlo, *mhi, *S;
1577         double d2, ds, eps;
1578         char *s, *s0;
1579
1580         /*
1581          * XXX initialize to silence GCC warnings
1582          */
1583         ilim = 0;
1584         ilim1 = 0;
1585         mlo = NULL;
1586         spec_case = 0;
1587
1588         if (word0(d) & Sign_bit) {
1589                 /* set sign for everything, including 0's and NaNs */
1590                 *sign = 1;
1591                 word0(d) &= ~Sign_bit;  /* clear sign bit */
1592         }
1593         else
1594                 *sign = 0;
1595
1596 #ifdef IEEE_Arith
1597         if ((word0(d) & Exp_mask) == Exp_mask)
1598         {
1599                 /* Infinity or NaN */
1600                 *decpt = 9999;
1601                 s = !word1(d) && !(word0(d) & 0xfffff) ? "Infinity" : "NaN";
1602                 if (rve)
1603                         *rve = s[3] ? s + 8 : s + 3;
1604                 return s;
1605         }
1606 #endif
1607         if (!d) {
1608                 *decpt = 1;
1609                 s = "0";
1610                 if (rve)
1611                         *rve = s + 1;
1612                 return s;
1613         }
1614
1615         b = d2b(d, &be, &bbits);
1616 #ifdef Sudden_Underflow
1617         i = (int)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1));
1618 #else
1619         if ( (i = (int)((word0(d) >> Exp_shift1) & (Exp_mask>>Exp_shift1))) ) {
1620 #endif
1621                 d2 = d;
1622                 word0(d2) &= Frac_mask1;
1623                 word0(d2) |= Exp_11;
1624
1625                 /* log(x)       ~=~ log(1.5) + (x-1.5)/1.5
1626                  * log10(x)      =  log(x) / log(10)
1627                  *              ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
1628                  * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2)
1629                  *
1630                  * This suggests computing an approximation k to log10(d) by
1631                  *
1632                  * k = (i - Bias)*0.301029995663981
1633                  *      + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
1634                  *
1635                  * We want k to be too large rather than too small.
1636                  * The error in the first-order Taylor series approximation
1637                  * is in our favor, so we just round up the constant enough
1638                  * to compensate for any error in the multiplication of
1639                  * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
1640                  * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
1641                  * adding 1e-13 to the constant term more than suffices.
1642                  * Hence we adjust the constant term to 0.1760912590558.
1643                  * (We could get a more accurate k by invoking log10,
1644                  *  but this is probably not worthwhile.)
1645                  */
1646
1647                 i -= Bias;
1648 #ifndef Sudden_Underflow
1649                 denorm = 0;
1650         } else {
1651                 /* d is denormalized */
1652
1653                 i = bbits + be + (Bias + (P-1) - 1);
1654                 x = i > 32  ? ((word0(d) << (64 - i)) | (word1(d) >> (i - 32)))
1655                             : (word1(d) << (32 - i));
1656                 d2 = x;
1657                 word0(d2) -= 31*Exp_msk1; /* adjust exponent */
1658                 i -= (Bias + (P-1) - 1) + 1;
1659                 denorm = 1;
1660         }
1661 #endif
1662         ds = (d2-1.5)*0.289529654602168 + 0.1760912590558 + i*0.301029995663981;
1663         k = (int)ds;
1664         if (ds < 0. && ds != k)
1665                 k--;    /* want k = floor(ds) */
1666         k_check = 1;
1667         if (k >= 0 && k <= Ten_pmax) {
1668                 if (d < tens[k])
1669                         k--;
1670                 k_check = 0;
1671         }
1672         j = bbits - i - 1;
1673         if (j >= 0) {
1674                 b2 = 0;
1675                 s2 = j;
1676         } else {
1677                 b2 = -j;
1678                 s2 = 0;
1679         }
1680         if (k >= 0) {
1681                 b5 = 0;
1682                 s5 = k;
1683                 s2 += k;
1684         } else {
1685                 b2 -= k;
1686                 b5 = -k;
1687                 s5 = 0;
1688         }
1689         if (mode < 0 || mode > 9)
1690                 mode = 0;
1691         try_quick = 1;
1692         if (mode > 5) {
1693                 mode -= 4;
1694                 try_quick = 0;
1695         }
1696         leftright = 1;
1697         switch(mode) {
1698                 case 0:
1699                 case 1:
1700                         ilim = ilim1 = -1;
1701                         i = 18;
1702                         ndigits = 0;
1703                         break;
1704                 case 2:
1705                         leftright = 0;
1706                         /* no break */
1707                 case 4:
1708                         if (ndigits <= 0)
1709                                 ndigits = 1;
1710                         ilim = ilim1 = i = ndigits;
1711                         break;
1712                 case 3:
1713                         leftright = 0;
1714                         /* no break */
1715                 case 5:
1716                         i = ndigits + k + 1;
1717                         ilim = i;
1718                         ilim1 = i - 1;
1719                         if (i <= 0)
1720                                 i = 1;
1721         }
1722         *resultp = (char *) malloc(i + 1);
1723         s = s0 = *resultp;
1724
1725         if (ilim >= 0 && ilim <= Quick_max && try_quick) {
1726
1727                 /* Try to get by with floating-point arithmetic. */
1728
1729                 i = 0;
1730                 d2 = d;
1731                 k0 = k;
1732                 ilim0 = ilim;
1733                 ieps = 2; /* conservative */
1734                 if (k > 0) {
1735                         ds = tens[k&0xf];
1736                         j = k >> 4;
1737                         if (j & Bletch) {
1738                                 /* prevent overflows */
1739                                 j &= Bletch - 1;
1740                                 d /= bigtens[n_bigtens-1];
1741                                 ieps++;
1742                         }
1743                         for (; j; j >>= 1, i++)
1744                                 if (j & 1) {
1745                                         ieps++;
1746                                         ds *= bigtens[i];
1747                                 }
1748                         d /= ds;
1749                 } else if ( (j1 = -k) ) {
1750                         d *= tens[j1 & 0xf];
1751                         for (j = j1 >> 4; j; j >>= 1, i++)
1752                                 if (j & 1) {
1753                                         ieps++;
1754                                         d *= bigtens[i];
1755                                 }
1756                 }
1757                 if (k_check && d < 1. && ilim > 0) {
1758                         if (ilim1 <= 0)
1759                                 goto fast_failed;
1760                         ilim = ilim1;
1761                         k--;
1762                         d *= 10.;
1763                         ieps++;
1764                 }
1765                 eps = ieps*d + 7.;
1766                 word0(eps) -= (P-1)*Exp_msk1;
1767                 if (ilim == 0) {
1768                         S = mhi = 0;
1769                         d -= 5.;
1770                         if (d > eps)
1771                                 goto one_digit;
1772                         if (d < -eps)
1773                                 goto no_digits;
1774                         goto fast_failed;
1775                 }
1776 #ifndef No_leftright
1777                 if (leftright) {
1778                         /* Use Steele & White method of only
1779                          * generating digits needed.
1780                          */
1781                         eps = 0.5/tens[ilim-1] - eps;
1782                         for (i = 0;;) {
1783                                 L = d;
1784                                 d -= L;
1785                                 *s++ = '0' + (int)L;
1786                                 if (d < eps)
1787                                         goto ret1;
1788                                 if (1. - d < eps)
1789                                         goto bump_up;
1790                                 if (++i >= ilim)
1791                                         break;
1792                                 eps *= 10.;
1793                                 d *= 10.;
1794                         }
1795                 } else {
1796 #endif
1797                         /* Generate ilim digits, then fix them up. */
1798                         eps *= tens[ilim-1];
1799                         for (i = 1;; i++, d *= 10.) {
1800                                 L = d;
1801                                 d -= L;
1802                                 *s++ = '0' + (int)L;
1803                                 if (i == ilim) {
1804                                         if (d > 0.5 + eps)
1805                                                 goto bump_up;
1806                                         else if (d < 0.5 - eps) {
1807                                                 while (*--s == '0');
1808                                                 s++;
1809                                                 goto ret1;
1810                                         }
1811                                         break;
1812                                 }
1813                         }
1814 #ifndef No_leftright
1815                 }
1816 #endif
1817 fast_failed:
1818                 s = s0;
1819                 d = d2;
1820                 k = k0;
1821                 ilim = ilim0;
1822         }
1823
1824         /* Do we have a "small" integer? */
1825
1826         if (be >= 0 && k <= Int_max) {
1827                 /* Yes. */
1828                 ds = tens[k];
1829                 if (ndigits < 0 && ilim <= 0) {
1830                         S = mhi = 0;
1831                         if (ilim < 0 || d <= 5*ds)
1832                                 goto no_digits;
1833                         goto one_digit;
1834                 }
1835                 for (i = 1;; i++) {
1836                         L = d / ds;
1837                         d -= L*ds;
1838 #ifdef Check_FLT_ROUNDS
1839                         /* If FLT_ROUNDS == 2, L will usually be high by 1 */
1840                         if (d < 0) {
1841                                 L--;
1842                                 d += ds;
1843                         }
1844 #endif
1845                         *s++ = '0' + (int)L;
1846                         if (i == ilim) {
1847                                 d += d;
1848                                 if (d > ds || (d == ds && L & 1)) {
1849 bump_up:
1850                                         while (*--s == '9')
1851                                                 if (s == s0) {
1852                                                         k++;
1853                                                         *s = '0';
1854                                                         break;
1855                                                 }
1856                                         ++*s++;
1857                                 }
1858                                 break;
1859                         }
1860                         if (!(d *= 10.))
1861                                 break;
1862                 }
1863                 goto ret1;
1864         }
1865
1866         m2 = b2;
1867         m5 = b5;
1868         mhi = mlo = 0;
1869         if (leftright) {
1870                 if (mode < 2) {
1871                         i =
1872 #ifndef Sudden_Underflow
1873                                 denorm ? be + (Bias + (P-1) - 1 + 1) :
1874 #endif
1875                                 1 + P - bbits;
1876                 } else {
1877                         j = ilim - 1;
1878                         if (m5 >= j)
1879                                 m5 -= j;
1880                         else {
1881                                 s5 += j -= m5;
1882                                 b5 += j;
1883                                 m5 = 0;
1884                         }
1885                         if ((i = ilim) < 0) {
1886                                 m2 -= i;
1887                                 i = 0;
1888                         }
1889                 }
1890                 b2 += i;
1891                 s2 += i;
1892                 mhi = i2b(1);
1893         }
1894         if (m2 > 0 && s2 > 0) {
1895                 i = m2 < s2 ? m2 : s2;
1896                 b2 -= i;
1897                 m2 -= i;
1898                 s2 -= i;
1899         }
1900         if (b5 > 0) {
1901                 if (leftright) {
1902                         if (m5 > 0) {
1903                                 mhi = pow5mult(mhi, m5);
1904                                 b1 = mult(mhi, b);
1905                                 Bfree(b);
1906                                 b = b1;
1907                                 }
1908                         if ( (j = b5 - m5) )
1909                                 b = pow5mult(b, j);
1910                 } else
1911                         b = pow5mult(b, b5);
1912         }
1913         S = i2b(1);
1914         if (s5 > 0)
1915                 S = pow5mult(S, s5);
1916
1917         /* Check for special case that d is a normalized power of 2. */
1918
1919         if (mode < 2) {
1920                 if (!word1(d) && !(word0(d) & Bndry_mask)
1921 #ifndef Sudden_Underflow
1922                  && word0(d) & Exp_mask
1923 #endif
1924                                 ) {
1925                         /* The special case */
1926                         b2 += Log2P;
1927                         s2 += Log2P;
1928                         spec_case = 1;
1929                 } else
1930                         spec_case = 0;
1931         }
1932
1933         /* Arrange for convenient computation of quotients:
1934          * shift left if necessary so divisor has 4 leading 0 bits.
1935          *
1936          * Perhaps we should just compute leading 28 bits of S once
1937          * and for all and pass them and a shift to quorem, so it
1938          * can do shifts and ors to compute the numerator for q.
1939          */
1940 #ifdef Pack_32
1941         if ( (i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0x1f) )
1942                 i = 32 - i;
1943 #else
1944         if ( (i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0xf) )
1945                 i = 16 - i;
1946 #endif
1947         if (i > 4) {
1948                 i -= 4;
1949                 b2 += i;
1950                 m2 += i;
1951                 s2 += i;
1952         } else if (i < 4) {
1953                 i += 28;
1954                 b2 += i;
1955                 m2 += i;
1956                 s2 += i;
1957         }
1958         if (b2 > 0)
1959                 b = lshift(b, b2);
1960         if (s2 > 0)
1961                 S = lshift(S, s2);
1962         if (k_check) {
1963                 if (cmp(b,S) < 0) {
1964                         k--;
1965                         b = multadd(b, 10, 0);  /* we botched the k estimate */
1966                         if (leftright)
1967                                 mhi = multadd(mhi, 10, 0);
1968                         ilim = ilim1;
1969                 }
1970         }
1971         if (ilim <= 0 && mode > 2) {
1972                 if (ilim < 0 || cmp(b,S = multadd(S,5,0)) <= 0) {
1973                         /* no digits, fcvt style */
1974 no_digits:
1975                         k = -1 - ndigits;
1976                         goto ret;
1977                 }
1978 one_digit:
1979                 *s++ = '1';
1980                 k++;
1981                 goto ret;
1982         }
1983         if (leftright) {
1984                 if (m2 > 0)
1985                         mhi = lshift(mhi, m2);
1986
1987                 /* Compute mlo -- check for special case
1988                  * that d is a normalized power of 2.
1989                  */
1990
1991                 mlo = mhi;
1992                 if (spec_case) {
1993                         mhi = Balloc(mhi->k);
1994                         Bcopy(mhi, mlo);
1995                         mhi = lshift(mhi, Log2P);
1996                 }
1997
1998                 for (i = 1;;i++) {
1999                         dig = quorem(b,S) + '0';
2000                         /* Do we yet have the shortest decimal string
2001                          * that will round to d?
2002                          */
2003                         j = cmp(b, mlo);
2004                         delta = diff(S, mhi);
2005                         j1 = delta->sign ? 1 : cmp(b, delta);
2006                         Bfree(delta);
2007 #ifndef ROUND_BIASED
2008                         if (j1 == 0 && !mode && !(word1(d) & 1)) {
2009                                 if (dig == '9')
2010                                         goto round_9_up;
2011                                 if (j > 0)
2012                                         dig++;
2013                                 *s++ = dig;
2014                                 goto ret;
2015                         }
2016 #endif
2017                         if (j < 0 || (j == 0 && !mode
2018 #ifndef ROUND_BIASED
2019                                                         && !(word1(d) & 1)
2020 #endif
2021                                         )) {
2022                                 if (j1 > 0) {
2023                                         b = lshift(b, 1);
2024                                         j1 = cmp(b, S);
2025                                         if ((j1 > 0 || (j1 == 0 && dig & 1))
2026                                         && dig++ == '9')
2027                                                 goto round_9_up;
2028                                 }
2029                                 *s++ = dig;
2030                                 goto ret;
2031                         }
2032                         if (j1 > 0) {
2033                                 if (dig == '9') { /* possible if i == 1 */
2034 round_9_up:
2035                                         *s++ = '9';
2036                                         goto roundoff;
2037                                 }
2038                                 *s++ = dig + 1;
2039                                 goto ret;
2040                         }
2041                         *s++ = dig;
2042                         if (i == ilim)
2043                                 break;
2044                         b = multadd(b, 10, 0);
2045                         if (mlo == mhi)
2046                                 mlo = mhi = multadd(mhi, 10, 0);
2047                         else {
2048                                 mlo = multadd(mlo, 10, 0);
2049                                 mhi = multadd(mhi, 10, 0);
2050                         }
2051                 }
2052         } else
2053                 for (i = 1;; i++) {
2054                         *s++ = dig = quorem(b,S) + '0';
2055                         if (i >= ilim)
2056                                 break;
2057                         b = multadd(b, 10, 0);
2058                 }
2059
2060         /* Round off last digit */
2061
2062         b = lshift(b, 1);
2063         j = cmp(b, S);
2064         if (j > 0 || (j == 0 && dig & 1)) {
2065 roundoff:
2066                 while (*--s == '9')
2067                         if (s == s0) {
2068                                 k++;
2069                                 *s++ = '1';
2070                                 goto ret;
2071                         }
2072                 ++*s++;
2073         } else {
2074                 while (*--s == '0');
2075                 s++;
2076         }
2077 ret:
2078         Bfree(S);
2079         if (mhi) {
2080                 if (mlo && mlo != mhi)
2081                         Bfree(mlo);
2082                 Bfree(mhi);
2083         }
2084 ret1:
2085         Bfree(b);
2086         if (s == s0) {  /* don't return empty string */
2087                 *s++ = '0';
2088                 k = 0;
2089         }
2090         *s = 0;
2091         *decpt = k + 1;
2092         if (rve)
2093                 *rve = s;
2094         return s0;
2095         }
2096 #ifdef __cplusplus
2097 }
2098 #endif