The Ruby Cross Reference

Implementation: mri jruby rubinius
Version: 1.8.7-p374 1.9.1-p431 1.9.2-p381 1.9.3-p547 2.0.0-p481 2.1.0 2.1.1 2.1.2 HEAD
001 /**********************************************************************
002 
003   util.c -
004 
005   $Author$
006   created at: Fri Mar 10 17:22:34 JST 1995
007 
008   Copyright (C) 1993-2008 Yukihiro Matsumoto
009 
010 **********************************************************************/
011 
012 #include "ruby/ruby.h"
013 #include "internal.h"
014 
015 #include <ctype.h>
016 #include <stdio.h>
017 #include <errno.h>
018 #include <math.h>
019 #include <float.h>
020 
021 #ifdef _WIN32
022 #include "missing/file.h"
023 #endif
024 
025 #include "ruby/util.h"
026 
027 unsigned long
028 ruby_scan_oct(const char *start, size_t len, size_t *retlen)
029 {
030     register const char *s = start;
031     register unsigned long retval = 0;
032 
033     while (len-- && *s >= '0' && *s <= '7') {
034         retval <<= 3;
035         retval |= *s++ - '0';
036     }
037     *retlen = (int)(s - start); /* less than len */
038     return retval;
039 }
040 
041 unsigned long
042 ruby_scan_hex(const char *start, size_t len, size_t *retlen)
043 {
044     static const char hexdigit[] = "0123456789abcdef0123456789ABCDEF";
045     register const char *s = start;
046     register unsigned long retval = 0;
047     const char *tmp;
048 
049     while (len-- && *s && (tmp = strchr(hexdigit, *s))) {
050         retval <<= 4;
051         retval |= (tmp - hexdigit) & 15;
052         s++;
053     }
054     *retlen = (int)(s - start); /* less than len */
055     return retval;
056 }
057 
058 const signed char ruby_digit36_to_number_table[] = {
059     /*     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f */
060     /*0*/ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
061     /*1*/ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
062     /*2*/ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
063     /*3*/  0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1,
064     /*4*/ -1,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,
065     /*5*/ 25,26,27,28,29,30,31,32,33,34,35,-1,-1,-1,-1,-1,
066     /*6*/ -1,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,
067     /*7*/ 25,26,27,28,29,30,31,32,33,34,35,-1,-1,-1,-1,-1,
068     /*8*/ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
069     /*9*/ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
070     /*a*/ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
071     /*b*/ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
072     /*c*/ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
073     /*d*/ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
074     /*e*/ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
075     /*f*/ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
076 };
077 
078 static unsigned long
079 scan_digits(const char *str, int base, size_t *retlen, int *overflow)
080 {
081 
082     const char *start = str;
083     unsigned long ret = 0, x;
084     unsigned long mul_overflow = (~(unsigned long)0) / base;
085     int c;
086     *overflow = 0;
087 
088     while ((c = (unsigned char)*str++) != '\0') {
089         int d = ruby_digit36_to_number_table[c];
090         if (d == -1 || base <= d) {
091             *retlen = (str-1) - start;
092             return ret;
093         }
094         if (mul_overflow < ret)
095             *overflow = 1;
096         ret *= base;
097         x = ret;
098         ret += d;
099         if (ret < x)
100             *overflow = 1;
101     }
102     *retlen = (str-1) - start;
103     return ret;
104 }
105 
106 unsigned long
107 ruby_strtoul(const char *str, char **endptr, int base)
108 {
109     int c, b, overflow;
110     int sign = 0;
111     size_t len;
112     unsigned long ret;
113     const char *subject_found = str;
114 
115     if (base == 1 || 36 < base) {
116         errno = EINVAL;
117         return 0;
118     }
119 
120     while ((c = *str) && ISSPACE(c))
121         str++;
122 
123     if (c == '+') {
124         sign = 1;
125         str++;
126     }
127     else if (c == '-') {
128         sign = -1;
129         str++;
130     }
131 
132     if (str[0] == '0') {
133         subject_found = str+1;
134         if (base == 0 || base == 16) {
135             if (str[1] == 'x' || str[1] == 'X') {
136                 b = 16;
137                 str += 2;
138             }
139             else {
140                 b = base == 0 ? 8 : 16;
141                 str++;
142             }
143         }
144         else {
145             b = base;
146             str++;
147         }
148     }
149     else {
150         b = base == 0 ? 10 : base;
151     }
152 
153     ret = scan_digits(str, b, &len, &overflow);
154 
155     if (0 < len)
156         subject_found = str+len;
157 
158     if (endptr)
159         *endptr = (char*)subject_found;
160 
161     if (overflow) {
162         errno = ERANGE;
163         return ULONG_MAX;
164     }
165 
166     if (sign < 0) {
167         ret = (unsigned long)(-(long)ret);
168         return ret;
169     }
170     else {
171         return ret;
172     }
173 }
174 
175 #include <sys/types.h>
176 #include <sys/stat.h>
177 #ifdef HAVE_UNISTD_H
178 #include <unistd.h>
179 #endif
180 #if defined(HAVE_FCNTL_H)
181 #include <fcntl.h>
182 #endif
183 
184 #ifndef S_ISDIR
185 #   define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
186 #endif
187 
188 
189 /* mm.c */
190 
191 #define mmtype long
192 #define mmcount (16 / SIZEOF_LONG)
193 #define A ((mmtype*)a)
194 #define B ((mmtype*)b)
195 #define C ((mmtype*)c)
196 #define D ((mmtype*)d)
197 
198 #define mmstep (sizeof(mmtype) * mmcount)
199 #define mmprepare(base, size) do {\
200  if (((VALUE)(base) % sizeof(mmtype)) == 0 && ((size) % sizeof(mmtype)) == 0) \
201    if ((size) >= mmstep) mmkind = 1;\
202    else              mmkind = 0;\
203  else                mmkind = -1;\
204  high = ((size) / mmstep) * mmstep;\
205  low  = ((size) % mmstep);\
206 } while (0)\
207 
208 #define mmarg mmkind, size, high, low
209 #define mmargdecl int mmkind, size_t size, size_t high, size_t low
210 
211 static void mmswap_(register char *a, register char *b, mmargdecl)
212 {
213  if (a == b) return;
214  if (mmkind >= 0) {
215    register mmtype s;
216 #if mmcount > 1
217    if (mmkind > 0) {
218      register char *t = a + high;
219      do {
220        s = A[0]; A[0] = B[0]; B[0] = s;
221        s = A[1]; A[1] = B[1]; B[1] = s;
222 #if mmcount > 2
223        s = A[2]; A[2] = B[2]; B[2] = s;
224 #if mmcount > 3
225        s = A[3]; A[3] = B[3]; B[3] = s;
226 #endif
227 #endif
228        a += mmstep; b += mmstep;
229      } while (a < t);
230    }
231 #endif
232    if (low != 0) { s = A[0]; A[0] = B[0]; B[0] = s;
233 #if mmcount > 2
234      if (low >= 2 * sizeof(mmtype)) { s = A[1]; A[1] = B[1]; B[1] = s;
235 #if mmcount > 3
236        if (low >= 3 * sizeof(mmtype)) {s = A[2]; A[2] = B[2]; B[2] = s;}
237 #endif
238      }
239 #endif
240    }
241  }
242  else {
243    register char *t = a + size, s;
244    do {s = *a; *a++ = *b; *b++ = s;} while (a < t);
245  }
246 }
247 #define mmswap(a,b) mmswap_((a),(b),mmarg)
248 
249 /* a, b, c = b, c, a */
250 static void mmrot3_(register char *a, register char *b, register char *c, mmargdecl)
251 {
252  if (mmkind >= 0) {
253    register mmtype s;
254 #if mmcount > 1
255    if (mmkind > 0) {
256      register char *t = a + high;
257      do {
258        s = A[0]; A[0] = B[0]; B[0] = C[0]; C[0] = s;
259        s = A[1]; A[1] = B[1]; B[1] = C[1]; C[1] = s;
260 #if mmcount > 2
261        s = A[2]; A[2] = B[2]; B[2] = C[2]; C[2] = s;
262 #if mmcount > 3
263        s = A[3]; A[3] = B[3]; B[3] = C[3]; C[3] = s;
264 #endif
265 #endif
266        a += mmstep; b += mmstep; c += mmstep;
267      } while (a < t);
268    }
269 #endif
270    if (low != 0) { s = A[0]; A[0] = B[0]; B[0] = C[0]; C[0] = s;
271 #if mmcount > 2
272      if (low >= 2 * sizeof(mmtype)) { s = A[1]; A[1] = B[1]; B[1] = C[1]; C[1] = s;
273 #if mmcount > 3
274        if (low == 3 * sizeof(mmtype)) {s = A[2]; A[2] = B[2]; B[2] = C[2]; C[2] = s;}
275 #endif
276      }
277 #endif
278    }
279  }
280  else {
281    register char *t = a + size, s;
282    do {s = *a; *a++ = *b; *b++ = *c; *c++ = s;} while (a < t);
283  }
284 }
285 #define mmrot3(a,b,c) mmrot3_((a),(b),(c),mmarg)
286 
287 /* qs6.c */
288 /*****************************************************/
289 /*                                                   */
290 /*          qs6   (Quick sort function)              */
291 /*                                                   */
292 /* by  Tomoyuki Kawamura              1995.4.21      */
293 /* kawamura@tokuyama.ac.jp                           */
294 /*****************************************************/
295 
296 typedef struct { char *LL, *RR; } stack_node; /* Stack structure for L,l,R,r */
297 #define PUSH(ll,rr) do { top->LL = (ll); top->RR = (rr); ++top; } while (0)  /* Push L,l,R,r */
298 #define POP(ll,rr)  do { --top; (ll) = top->LL; (rr) = top->RR; } while (0)      /* Pop L,l,R,r */
299 
300 #define med3(a,b,c) ((*cmp)((a),(b),d)<0 ?                                   \
301                        ((*cmp)((b),(c),d)<0 ? (b) : ((*cmp)((a),(c),d)<0 ? (c) : (a))) : \
302                        ((*cmp)((b),(c),d)>0 ? (b) : ((*cmp)((a),(c),d)<0 ? (a) : (c))))
303 
304 typedef int (cmpfunc_t)(const void*, const void*, void*);
305 void
306 ruby_qsort(void* base, const size_t nel, const size_t size, cmpfunc_t *cmp, void *d)
307 {
308   register char *l, *r, *m;             /* l,r:left,right group   m:median point */
309   register int t, eq_l, eq_r;           /* eq_l: all items in left group are equal to S */
310   char *L = base;                       /* left end of current region */
311   char *R = (char*)base + size*(nel-1); /* right end of current region */
312   size_t chklim = 63;                   /* threshold of ordering element check */
313   stack_node stack[32], *top = stack;   /* 32 is enough for 32bit CPU */
314   int mmkind;
315   size_t high, low, n;
316 
317   if (nel <= 1) return;        /* need not to sort */
318   mmprepare(base, size);
319   goto start;
320 
321   nxt:
322   if (stack == top) return;    /* return if stack is empty */
323   POP(L,R);
324 
325   for (;;) {
326     start:
327     if (L + size == R) {       /* 2 elements */
328       if ((*cmp)(L,R,d) > 0) mmswap(L,R); goto nxt;
329     }
330 
331     l = L; r = R;
332     n = (r - l + size) / size;  /* number of elements */
333     m = l + size * (n >> 1);    /* calculate median value */
334 
335     if (n >= 60) {
336       register char *m1;
337       register char *m3;
338       if (n >= 200) {
339         n = size*(n>>3); /* number of bytes in splitting 8 */
340         {
341           register char *p1 = l  + n;
342           register char *p2 = p1 + n;
343           register char *p3 = p2 + n;
344           m1 = med3(p1, p2, p3);
345           p1 = m  + n;
346           p2 = p1 + n;
347           p3 = p2 + n;
348           m3 = med3(p1, p2, p3);
349         }
350       }
351       else {
352         n = size*(n>>2); /* number of bytes in splitting 4 */
353         m1 = l + n;
354         m3 = m + n;
355       }
356       m = med3(m1, m, m3);
357     }
358 
359     if ((t = (*cmp)(l,m,d)) < 0) {                           /*3-5-?*/
360       if ((t = (*cmp)(m,r,d)) < 0) {                         /*3-5-7*/
361         if (chklim && nel >= chklim) {   /* check if already ascending order */
362           char *p;
363           chklim = 0;
364           for (p=l; p<r; p+=size) if ((*cmp)(p,p+size,d) > 0) goto fail;
365           goto nxt;
366         }
367         fail: goto loopA;                                    /*3-5-7*/
368       }
369       if (t > 0) {
370         if ((*cmp)(l,r,d) <= 0) {mmswap(m,r); goto loopA;}     /*3-5-4*/
371         mmrot3(r,m,l); goto loopA;                           /*3-5-2*/
372       }
373       goto loopB;                                            /*3-5-5*/
374     }
375 
376     if (t > 0) {                                             /*7-5-?*/
377       if ((t = (*cmp)(m,r,d)) > 0) {                         /*7-5-3*/
378         if (chklim && nel >= chklim) {   /* check if already ascending order */
379           char *p;
380           chklim = 0;
381           for (p=l; p<r; p+=size) if ((*cmp)(p,p+size,d) < 0) goto fail2;
382           while (l<r) {mmswap(l,r); l+=size; r-=size;}  /* reverse region */
383           goto nxt;
384         }
385         fail2: mmswap(l,r); goto loopA;                      /*7-5-3*/
386       }
387       if (t < 0) {
388         if ((*cmp)(l,r,d) <= 0) {mmswap(l,m); goto loopB;}   /*7-5-8*/
389         mmrot3(l,m,r); goto loopA;                           /*7-5-6*/
390       }
391       mmswap(l,r); goto loopA;                               /*7-5-5*/
392     }
393 
394     if ((t = (*cmp)(m,r,d)) < 0)  {goto loopA;}              /*5-5-7*/
395     if (t > 0) {mmswap(l,r); goto loopB;}                    /*5-5-3*/
396 
397     /* determining splitting type in case 5-5-5 */           /*5-5-5*/
398     for (;;) {
399       if ((l += size) == r)      goto nxt;                   /*5-5-5*/
400       if (l == m) continue;
401       if ((t = (*cmp)(l,m,d)) > 0) {mmswap(l,r); l = L; goto loopA;}/*575-5*/
402       if (t < 0)                 {mmswap(L,l); l = L; goto loopB;}  /*535-5*/
403     }
404 
405     loopA: eq_l = 1; eq_r = 1;  /* splitting type A */ /* left <= median < right */
406     for (;;) {
407       for (;;) {
408         if ((l += size) == r)
409           {l -= size; if (l != m) mmswap(m,l); l -= size; goto fin;}
410         if (l == m) continue;
411         if ((t = (*cmp)(l,m,d)) > 0) {eq_r = 0; break;}
412         if (t < 0) eq_l = 0;
413       }
414       for (;;) {
415         if (l == (r -= size))
416           {l -= size; if (l != m) mmswap(m,l); l -= size; goto fin;}
417         if (r == m) {m = l; break;}
418         if ((t = (*cmp)(r,m,d)) < 0) {eq_l = 0; break;}
419         if (t == 0) break;
420       }
421       mmswap(l,r);    /* swap left and right */
422     }
423 
424     loopB: eq_l = 1; eq_r = 1;  /* splitting type B */ /* left < median <= right */
425     for (;;) {
426       for (;;) {
427         if (l == (r -= size))
428           {r += size; if (r != m) mmswap(r,m); r += size; goto fin;}
429         if (r == m) continue;
430         if ((t = (*cmp)(r,m,d)) < 0) {eq_l = 0; break;}
431         if (t > 0) eq_r = 0;
432       }
433       for (;;) {
434         if ((l += size) == r)
435           {r += size; if (r != m) mmswap(r,m); r += size; goto fin;}
436         if (l == m) {m = r; break;}
437         if ((t = (*cmp)(l,m,d)) > 0) {eq_r = 0; break;}
438         if (t == 0) break;
439       }
440       mmswap(l,r);    /* swap left and right */
441     }
442 
443     fin:
444     if (eq_l == 0)                         /* need to sort left side */
445       if (eq_r == 0)                       /* need to sort right side */
446         if (l-L < R-r) {PUSH(r,R); R = l;} /* sort left side first */
447         else           {PUSH(L,l); L = r;} /* sort right side first */
448       else R = l;                          /* need to sort left side only */
449     else if (eq_r == 0) L = r;             /* need to sort right side only */
450     else goto nxt;                         /* need not to sort both sides */
451   }
452 }
453 
454 char *
455 ruby_strdup(const char *str)
456 {
457     char *tmp;
458     size_t len = strlen(str) + 1;
459 
460     tmp = xmalloc(len);
461     memcpy(tmp, str, len);
462 
463     return tmp;
464 }
465 
466 #ifdef __native_client__
467 char *
468 ruby_getcwd(void)
469 {
470     char *buf = xmalloc(2);
471     strcpy(buf, ".");
472     return buf;
473 }
474 #else
475 char *
476 ruby_getcwd(void)
477 {
478 #ifdef HAVE_GETCWD
479     int size = 200;
480     char *buf = xmalloc(size);
481 
482     while (!getcwd(buf, size)) {
483         if (errno != ERANGE) {
484             xfree(buf);
485             rb_sys_fail("getcwd");
486         }
487         size *= 2;
488         buf = xrealloc(buf, size);
489     }
490 #else
491 # ifndef PATH_MAX
492 #  define PATH_MAX 8192
493 # endif
494     char *buf = xmalloc(PATH_MAX+1);
495 
496     if (!getwd(buf)) {
497         xfree(buf);
498         rb_sys_fail("getwd");
499     }
500 #endif
501     return buf;
502 }
503 #endif
504 
505 /****************************************************************
506  *
507  * The author of this software is David M. Gay.
508  *
509  * Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
510  *
511  * Permission to use, copy, modify, and distribute this software for any
512  * purpose without fee is hereby granted, provided that this entire notice
513  * is included in all copies of any software which is or includes a copy
514  * or modification of this software and in all copies of the supporting
515  * documentation for such software.
516  *
517  * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
518  * WARRANTY.  IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
519  * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
520  * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
521  *
522  ***************************************************************/
523 
524 /* Please send bug reports to David M. Gay (dmg at acm dot org,
525  * with " at " changed at "@" and " dot " changed to ".").      */
526 
527 /* On a machine with IEEE extended-precision registers, it is
528  * necessary to specify double-precision (53-bit) rounding precision
529  * before invoking strtod or dtoa.  If the machine uses (the equivalent
530  * of) Intel 80x87 arithmetic, the call
531  *      _control87(PC_53, MCW_PC);
532  * does this with many compilers.  Whether this or another call is
533  * appropriate depends on the compiler; for this to work, it may be
534  * necessary to #include "float.h" or another system-dependent header
535  * file.
536  */
537 
538 /* strtod for IEEE-, VAX-, and IBM-arithmetic machines.
539  *
540  * This strtod returns a nearest machine number to the input decimal
541  * string (or sets errno to ERANGE).  With IEEE arithmetic, ties are
542  * broken by the IEEE round-even rule.  Otherwise ties are broken by
543  * biased rounding (add half and chop).
544  *
545  * Inspired loosely by William D. Clinger's paper "How to Read Floating
546  * Point Numbers Accurately" [Proc. ACM SIGPLAN '90, pp. 92-101].
547  *
548  * Modifications:
549  *
550  *      1. We only require IEEE, IBM, or VAX double-precision
551  *              arithmetic (not IEEE double-extended).
552  *      2. We get by with floating-point arithmetic in a case that
553  *              Clinger missed -- when we're computing d * 10^n
554  *              for a small integer d and the integer n is not too
555  *              much larger than 22 (the maximum integer k for which
556  *              we can represent 10^k exactly), we may be able to
557  *              compute (d*10^k) * 10^(e-k) with just one roundoff.
558  *      3. Rather than a bit-at-a-time adjustment of the binary
559  *              result in the hard case, we use floating-point
560  *              arithmetic to determine the adjustment to within
561  *              one bit; only in really hard cases do we need to
562  *              compute a second residual.
563  *      4. Because of 3., we don't need a large table of powers of 10
564  *              for ten-to-e (just some small tables, e.g. of 10^k
565  *              for 0 <= k <= 22).
566  */
567 
568 /*
569  * #define IEEE_LITTLE_ENDIAN for IEEE-arithmetic machines where the least
570  *      significant byte has the lowest address.
571  * #define IEEE_BIG_ENDIAN for IEEE-arithmetic machines where the most
572  *      significant byte has the lowest address.
573  * #define Long int on machines with 32-bit ints and 64-bit longs.
574  * #define IBM for IBM mainframe-style floating-point arithmetic.
575  * #define VAX for VAX-style floating-point arithmetic (D_floating).
576  * #define No_leftright to omit left-right logic in fast floating-point
577  *      computation of dtoa.
578  * #define Honor_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3
579  *      and strtod and dtoa should round accordingly.
580  * #define Check_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3
581  *      and Honor_FLT_ROUNDS is not #defined.
582  * #define RND_PRODQUOT to use rnd_prod and rnd_quot (assembly routines
583  *      that use extended-precision instructions to compute rounded
584  *      products and quotients) with IBM.
585  * #define ROUND_BIASED for IEEE-format with biased rounding.
586  * #define Inaccurate_Divide for IEEE-format with correctly rounded
587  *      products but inaccurate quotients, e.g., for Intel i860.
588  * #define NO_LONG_LONG on machines that do not have a "long long"
589  *      integer type (of >= 64 bits).  On such machines, you can
590  *      #define Just_16 to store 16 bits per 32-bit Long when doing
591  *      high-precision integer arithmetic.  Whether this speeds things
592  *      up or slows things down depends on the machine and the number
593  *      being converted.  If long long is available and the name is
594  *      something other than "long long", #define Llong to be the name,
595  *      and if "unsigned Llong" does not work as an unsigned version of
596  *      Llong, #define #ULLong to be the corresponding unsigned type.
597  * #define KR_headers for old-style C function headers.
598  * #define Bad_float_h if your system lacks a float.h or if it does not
599  *      define some or all of DBL_DIG, DBL_MAX_10_EXP, DBL_MAX_EXP,
600  *      FLT_RADIX, FLT_ROUNDS, and DBL_MAX.
601  * #define MALLOC your_malloc, where your_malloc(n) acts like malloc(n)
602  *      if memory is available and otherwise does something you deem
603  *      appropriate.  If MALLOC is undefined, malloc will be invoked
604  *      directly -- and assumed always to succeed.
605  * #define Omit_Private_Memory to omit logic (added Jan. 1998) for making
606  *      memory allocations from a private pool of memory when possible.
607  *      When used, the private pool is PRIVATE_MEM bytes long:  2304 bytes,
608  *      unless #defined to be a different length.  This default length
609  *      suffices to get rid of MALLOC calls except for unusual cases,
610  *      such as decimal-to-binary conversion of a very long string of
611  *      digits.  The longest string dtoa can return is about 751 bytes
612  *      long.  For conversions by strtod of strings of 800 digits and
613  *      all dtoa conversions in single-threaded executions with 8-byte
614  *      pointers, PRIVATE_MEM >= 7400 appears to suffice; with 4-byte
615  *      pointers, PRIVATE_MEM >= 7112 appears adequate.
616  * #define INFNAN_CHECK on IEEE systems to cause strtod to check for
617  *      Infinity and NaN (case insensitively).  On some systems (e.g.,
618  *      some HP systems), it may be necessary to #define NAN_WORD0
619  *      appropriately -- to the most significant word of a quiet NaN.
620  *      (On HP Series 700/800 machines, -DNAN_WORD0=0x7ff40000 works.)
621  *      When INFNAN_CHECK is #defined and No_Hex_NaN is not #defined,
622  *      strtod also accepts (case insensitively) strings of the form
623  *      NaN(x), where x is a string of hexadecimal digits and spaces;
624  *      if there is only one string of hexadecimal digits, it is taken
625  *      for the 52 fraction bits of the resulting NaN; if there are two
626  *      or more strings of hex digits, the first is for the high 20 bits,
627  *      the second and subsequent for the low 32 bits, with intervening
628  *      white space ignored; but if this results in none of the 52
629  *      fraction bits being on (an IEEE Infinity symbol), then NAN_WORD0
630  *      and NAN_WORD1 are used instead.
631  * #define MULTIPLE_THREADS if the system offers preemptively scheduled
632  *      multiple threads.  In this case, you must provide (or suitably
633  *      #define) two locks, acquired by ACQUIRE_DTOA_LOCK(n) and freed
634  *      by FREE_DTOA_LOCK(n) for n = 0 or 1.  (The second lock, accessed
635  *      in pow5mult, ensures lazy evaluation of only one copy of high
636  *      powers of 5; omitting this lock would introduce a small
637  *      probability of wasting memory, but would otherwise be harmless.)
638  *      You must also invoke freedtoa(s) to free the value s returned by
639  *      dtoa.  You may do so whether or not MULTIPLE_THREADS is #defined.
640  * #define NO_IEEE_Scale to disable new (Feb. 1997) logic in strtod that
641  *      avoids underflows on inputs whose result does not underflow.
642  *      If you #define NO_IEEE_Scale on a machine that uses IEEE-format
643  *      floating-point numbers and flushes underflows to zero rather
644  *      than implementing gradual underflow, then you must also #define
645  *      Sudden_Underflow.
646  * #define YES_ALIAS to permit aliasing certain double values with
647  *      arrays of ULongs.  This leads to slightly better code with
648  *      some compilers and was always used prior to 19990916, but it
649  *      is not strictly legal and can cause trouble with aggressively
650  *      optimizing compilers (e.g., gcc 2.95.1 under -O2).
651  * #define USE_LOCALE to use the current locale's decimal_point value.
652  * #define SET_INEXACT if IEEE arithmetic is being used and extra
653  *      computation should be done to set the inexact flag when the
654  *      result is inexact and avoid setting inexact when the result
655  *      is exact.  In this case, dtoa.c must be compiled in
656  *      an environment, perhaps provided by #include "dtoa.c" in a
657  *      suitable wrapper, that defines two functions,
658  *              int get_inexact(void);
659  *              void clear_inexact(void);
660  *      such that get_inexact() returns a nonzero value if the
661  *      inexact bit is already set, and clear_inexact() sets the
662  *      inexact bit to 0.  When SET_INEXACT is #defined, strtod
663  *      also does extra computations to set the underflow and overflow
664  *      flags when appropriate (i.e., when the result is tiny and
665  *      inexact or when it is a numeric value rounded to +-infinity).
666  * #define NO_ERRNO if strtod should not assign errno = ERANGE when
667  *      the result overflows to +-Infinity or underflows to 0.
668  */
669 
670 #ifdef WORDS_BIGENDIAN
671 #define IEEE_BIG_ENDIAN
672 #else
673 #define IEEE_LITTLE_ENDIAN
674 #endif
675 
676 #ifdef __vax__
677 #define VAX
678 #undef IEEE_BIG_ENDIAN
679 #undef IEEE_LITTLE_ENDIAN
680 #endif
681 
682 #if defined(__arm__) && !defined(__VFP_FP__)
683 #define IEEE_BIG_ENDIAN
684 #undef IEEE_LITTLE_ENDIAN
685 #endif
686 
687 #undef Long
688 #undef ULong
689 
690 #if SIZEOF_INT == 4
691 #define Long int
692 #define ULong unsigned int
693 #elif SIZEOF_LONG == 4
694 #define Long long int
695 #define ULong unsigned long int
696 #endif
697 
698 #if HAVE_LONG_LONG
699 #define Llong LONG_LONG
700 #endif
701 
702 #ifdef DEBUG
703 #include "stdio.h"
704 #define Bug(x) {fprintf(stderr, "%s\n", (x)); exit(EXIT_FAILURE);}
705 #endif
706 
707 #include "stdlib.h"
708 #include "string.h"
709 
710 #ifdef USE_LOCALE
711 #include "locale.h"
712 #endif
713 
714 #ifdef MALLOC
715 extern void *MALLOC(size_t);
716 #else
717 #define MALLOC malloc
718 #endif
719 
720 #ifndef Omit_Private_Memory
721 #ifndef PRIVATE_MEM
722 #define PRIVATE_MEM 2304
723 #endif
724 #define PRIVATE_mem ((PRIVATE_MEM+sizeof(double)-1)/sizeof(double))
725 static double private_mem[PRIVATE_mem], *pmem_next = private_mem;
726 #endif
727 
728 #undef IEEE_Arith
729 #undef Avoid_Underflow
730 #ifdef IEEE_BIG_ENDIAN
731 #define IEEE_Arith
732 #endif
733 #ifdef IEEE_LITTLE_ENDIAN
734 #define IEEE_Arith
735 #endif
736 
737 #ifdef Bad_float_h
738 
739 #ifdef IEEE_Arith
740 #define DBL_DIG 15
741 #define DBL_MAX_10_EXP 308
742 #define DBL_MAX_EXP 1024
743 #define FLT_RADIX 2
744 #endif /*IEEE_Arith*/
745 
746 #ifdef IBM
747 #define DBL_DIG 16
748 #define DBL_MAX_10_EXP 75
749 #define DBL_MAX_EXP 63
750 #define FLT_RADIX 16
751 #define DBL_MAX 7.2370055773322621e+75
752 #endif
753 
754 #ifdef VAX
755 #define DBL_DIG 16
756 #define DBL_MAX_10_EXP 38
757 #define DBL_MAX_EXP 127
758 #define FLT_RADIX 2
759 #define DBL_MAX 1.7014118346046923e+38
760 #endif
761 
762 #ifndef LONG_MAX
763 #define LONG_MAX 2147483647
764 #endif
765 
766 #else /* ifndef Bad_float_h */
767 #include "float.h"
768 #endif /* Bad_float_h */
769 
770 #ifndef __MATH_H__
771 #include "math.h"
772 #endif
773 
774 #ifdef __cplusplus
775 extern "C" {
776 #if 0
777 } /* satisfy cc-mode */
778 #endif
779 #endif
780 
781 #if defined(IEEE_LITTLE_ENDIAN) + defined(IEEE_BIG_ENDIAN) + defined(VAX) + defined(IBM) != 1
782 Exactly one of IEEE_LITTLE_ENDIAN, IEEE_BIG_ENDIAN, VAX, or IBM should be defined.
783 #endif
784 
785 typedef union { double d; ULong L[2]; } U;
786 
787 #ifdef YES_ALIAS
788 typedef double double_u;
789 #  define dval(x) (x)
790 #  ifdef IEEE_LITTLE_ENDIAN
791 #    define word0(x) (((ULong *)&(x))[1])
792 #    define word1(x) (((ULong *)&(x))[0])
793 #  else
794 #    define word0(x) (((ULong *)&(x))[0])
795 #    define word1(x) (((ULong *)&(x))[1])
796 #  endif
797 #else
798 typedef U double_u;
799 #  ifdef IEEE_LITTLE_ENDIAN
800 #    define word0(x) ((x).L[1])
801 #    define word1(x) ((x).L[0])
802 #  else
803 #    define word0(x) ((x).L[0])
804 #    define word1(x) ((x).L[1])
805 #  endif
806 #  define dval(x) ((x).d)
807 #endif
808 
809 /* The following definition of Storeinc is appropriate for MIPS processors.
810  * An alternative that might be better on some machines is
811  * #define Storeinc(a,b,c) (*a++ = b << 16 | c & 0xffff)
812  */
813 #if defined(IEEE_LITTLE_ENDIAN) + defined(VAX) + defined(__arm__)
814 #define Storeinc(a,b,c) (((unsigned short *)(a))[1] = (unsigned short)(b), \
815 ((unsigned short *)(a))[0] = (unsigned short)(c), (a)++)
816 #else
817 #define Storeinc(a,b,c) (((unsigned short *)(a))[0] = (unsigned short)(b), \
818 ((unsigned short *)(a))[1] = (unsigned short)(c), (a)++)
819 #endif
820 
821 /* #define P DBL_MANT_DIG */
822 /* Ten_pmax = floor(P*log(2)/log(5)) */
823 /* Bletch = (highest power of 2 < DBL_MAX_10_EXP) / 16 */
824 /* Quick_max = floor((P-1)*log(FLT_RADIX)/log(10) - 1) */
825 /* Int_max = floor(P*log(FLT_RADIX)/log(10) - 1) */
826 
827 #ifdef IEEE_Arith
828 #define Exp_shift  20
829 #define Exp_shift1 20
830 #define Exp_msk1    0x100000
831 #define Exp_msk11   0x100000
832 #define Exp_mask  0x7ff00000
833 #define P 53
834 #define Bias 1023
835 #define Emin (-1022)
836 #define Exp_1  0x3ff00000
837 #define Exp_11 0x3ff00000
838 #define Ebits 11
839 #define Frac_mask  0xfffff
840 #define Frac_mask1 0xfffff
841 #define Ten_pmax 22
842 #define Bletch 0x10
843 #define Bndry_mask  0xfffff
844 #define Bndry_mask1 0xfffff
845 #define LSB 1
846 #define Sign_bit 0x80000000
847 #define Log2P 1
848 #define Tiny0 0
849 #define Tiny1 1
850 #define Quick_max 14
851 #define Int_max 14
852 #ifndef NO_IEEE_Scale
853 #define Avoid_Underflow
854 #ifdef Flush_Denorm     /* debugging option */
855 #undef Sudden_Underflow
856 #endif
857 #endif
858 
859 #ifndef Flt_Rounds
860 #ifdef FLT_ROUNDS
861 #define Flt_Rounds FLT_ROUNDS
862 #else
863 #define Flt_Rounds 1
864 #endif
865 #endif /*Flt_Rounds*/
866 
867 #ifdef Honor_FLT_ROUNDS
868 #define Rounding rounding
869 #undef Check_FLT_ROUNDS
870 #define Check_FLT_ROUNDS
871 #else
872 #define Rounding Flt_Rounds
873 #endif
874 
875 #else /* ifndef IEEE_Arith */
876 #undef Check_FLT_ROUNDS
877 #undef Honor_FLT_ROUNDS
878 #undef SET_INEXACT
879 #undef  Sudden_Underflow
880 #define Sudden_Underflow
881 #ifdef IBM
882 #undef Flt_Rounds
883 #define Flt_Rounds 0
884 #define Exp_shift  24
885 #define Exp_shift1 24
886 #define Exp_msk1   0x1000000
887 #define Exp_msk11  0x1000000
888 #define Exp_mask  0x7f000000
889 #define P 14
890 #define Bias 65
891 #define Exp_1  0x41000000
892 #define Exp_11 0x41000000
893 #define Ebits 8 /* exponent has 7 bits, but 8 is the right value in b2d */
894 #define Frac_mask  0xffffff
895 #define Frac_mask1 0xffffff
896 #define Bletch 4
897 #define Ten_pmax 22
898 #define Bndry_mask  0xefffff
899 #define Bndry_mask1 0xffffff
900 #define LSB 1
901 #define Sign_bit 0x80000000
902 #define Log2P 4
903 #define Tiny0 0x100000
904 #define Tiny1 0
905 #define Quick_max 14
906 #define Int_max 15
907 #else /* VAX */
908 #undef Flt_Rounds
909 #define Flt_Rounds 1
910 #define Exp_shift  23
911 #define Exp_shift1 7
912 #define Exp_msk1    0x80
913 #define Exp_msk11   0x800000
914 #define Exp_mask  0x7f80
915 #define P 56
916 #define Bias 129
917 #define Exp_1  0x40800000
918 #define Exp_11 0x4080
919 #define Ebits 8
920 #define Frac_mask  0x7fffff
921 #define Frac_mask1 0xffff007f
922 #define Ten_pmax 24
923 #define Bletch 2
924 #define Bndry_mask  0xffff007f
925 #define Bndry_mask1 0xffff007f
926 #define LSB 0x10000
927 #define Sign_bit 0x8000
928 #define Log2P 1
929 #define Tiny0 0x80
930 #define Tiny1 0
931 #define Quick_max 15
932 #define Int_max 15
933 #endif /* IBM, VAX */
934 #endif /* IEEE_Arith */
935 
936 #ifndef IEEE_Arith
937 #define ROUND_BIASED
938 #endif
939 
940 #ifdef RND_PRODQUOT
941 #define rounded_product(a,b) ((a) = rnd_prod((a), (b)))
942 #define rounded_quotient(a,b) ((a) = rnd_quot((a), (b)))
943 extern double rnd_prod(double, double), rnd_quot(double, double);
944 #else
945 #define rounded_product(a,b) ((a) *= (b))
946 #define rounded_quotient(a,b) ((a) /= (b))
947 #endif
948 
949 #define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
950 #define Big1 0xffffffff
951 
952 #ifndef Pack_32
953 #define Pack_32
954 #endif
955 
956 #define FFFFFFFF 0xffffffffUL
957 
958 #ifdef NO_LONG_LONG
959 #undef ULLong
960 #ifdef Just_16
961 #undef Pack_32
962 /* When Pack_32 is not defined, we store 16 bits per 32-bit Long.
963  * This makes some inner loops simpler and sometimes saves work
964  * during multiplications, but it often seems to make things slightly
965  * slower.  Hence the default is now to store 32 bits per Long.
966  */
967 #endif
968 #else   /* long long available */
969 #ifndef Llong
970 #define Llong long long
971 #endif
972 #ifndef ULLong
973 #define ULLong unsigned Llong
974 #endif
975 #endif /* NO_LONG_LONG */
976 
977 #define MULTIPLE_THREADS 1
978 
979 #ifndef MULTIPLE_THREADS
980 #define ACQUIRE_DTOA_LOCK(n)    /*nothing*/
981 #define FREE_DTOA_LOCK(n)       /*nothing*/
982 #else
983 #define ACQUIRE_DTOA_LOCK(n)    /*unused right now*/
984 #define FREE_DTOA_LOCK(n)       /*unused right now*/
985 #endif
986 
987 #define Kmax 15
988 
989 struct Bigint {
990     struct Bigint *next;
991     int k, maxwds, sign, wds;
992     ULong x[1];
993 };
994 
995 typedef struct Bigint Bigint;
996 
997 static Bigint *freelist[Kmax+1];
998 
999 static Bigint *
1000 Balloc(int k)
1001 {
1002     int x;
1003     Bigint *rv;
1004 #ifndef Omit_Private_Memory
1005     size_t len;
1006 #endif
1007 
1008     ACQUIRE_DTOA_LOCK(0);
1009     if ((rv = freelist[k]) != 0) {
1010         freelist[k] = rv->next;
1011     }
1012     else {
1013         x = 1 << k;
1014 #ifdef Omit_Private_Memory
1015         rv = (Bigint *)MALLOC(sizeof(Bigint) + (x-1)*sizeof(ULong));
1016 #else
1017         len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)
1018                 /sizeof(double);
1019         if (pmem_next - private_mem + len <= PRIVATE_mem) {
1020             rv = (Bigint*)pmem_next;
1021             pmem_next += len;
1022         }
1023         else
1024             rv = (Bigint*)MALLOC(len*sizeof(double));
1025 #endif
1026         rv->k = k;
1027         rv->maxwds = x;
1028     }
1029     FREE_DTOA_LOCK(0);
1030     rv->sign = rv->wds = 0;
1031     return rv;
1032 }
1033 
1034 static void
1035 Bfree(Bigint *v)
1036 {
1037     if (v) {
1038         ACQUIRE_DTOA_LOCK(0);
1039         v->next = freelist[v->k];
1040         freelist[v->k] = v;
1041         FREE_DTOA_LOCK(0);
1042     }
1043 }
1044 
1045 #define Bcopy(x,y) memcpy((char *)&(x)->sign, (char *)&(y)->sign, \
1046 (y)->wds*sizeof(Long) + 2*sizeof(int))
1047 
1048 static Bigint *
1049 multadd(Bigint *b, int m, int a)   /* multiply by m and add a */
1050 {
1051     int i, wds;
1052     ULong *x;
1053 #ifdef ULLong
1054     ULLong carry, y;
1055 #else
1056     ULong carry, y;
1057 #ifdef Pack_32
1058     ULong xi, z;
1059 #endif
1060 #endif
1061     Bigint *b1;
1062 
1063     wds = b->wds;
1064     x = b->x;
1065     i = 0;
1066     carry = a;
1067     do {
1068 #ifdef ULLong
1069         y = *x * (ULLong)m + carry;
1070         carry = y >> 32;
1071         *x++ = (ULong)(y & FFFFFFFF);
1072 #else
1073 #ifdef Pack_32
1074         xi = *x;
1075         y = (xi & 0xffff) * m + carry;
1076         z = (xi >> 16) * m + (y >> 16);
1077         carry = z >> 16;
1078         *x++ = (z << 16) + (y & 0xffff);
1079 #else
1080         y = *x * m + carry;
1081         carry = y >> 16;
1082         *x++ = y & 0xffff;
1083 #endif
1084 #endif
1085     } while (++i < wds);
1086     if (carry) {
1087         if (wds >= b->maxwds) {
1088             b1 = Balloc(b->k+1);
1089             Bcopy(b1, b);
1090             Bfree(b);
1091             b = b1;
1092         }
1093         b->x[wds++] = (ULong)carry;
1094         b->wds = wds;
1095     }
1096     return b;
1097 }
1098 
1099 static Bigint *
1100 s2b(const char *s, int nd0, int nd, ULong y9)
1101 {
1102     Bigint *b;
1103     int i, k;
1104     Long x, y;
1105 
1106     x = (nd + 8) / 9;
1107     for (k = 0, y = 1; x > y; y <<= 1, k++) ;
1108 #ifdef Pack_32
1109     b = Balloc(k);
1110     b->x[0] = y9;
1111     b->wds = 1;
1112 #else
1113     b = Balloc(k+1);
1114     b->x[0] = y9 & 0xffff;
1115     b->wds = (b->x[1] = y9 >> 16) ? 2 : 1;
1116 #endif
1117 
1118     i = 9;
1119     if (9 < nd0) {
1120         s += 9;
1121         do {
1122             b = multadd(b, 10, *s++ - '0');
1123         } while (++i < nd0);
1124         s++;
1125     }
1126     else
1127         s += 10;
1128     for (; i < nd; i++)
1129         b = multadd(b, 10, *s++ - '0');
1130     return b;
1131 }
1132 
1133 static int
1134 hi0bits(register ULong x)
1135 {
1136     register int k = 0;
1137 
1138     if (!(x & 0xffff0000)) {
1139         k = 16;
1140         x <<= 16;
1141     }
1142     if (!(x & 0xff000000)) {
1143         k += 8;
1144         x <<= 8;
1145     }
1146     if (!(x & 0xf0000000)) {
1147         k += 4;
1148         x <<= 4;
1149     }
1150     if (!(x & 0xc0000000)) {
1151         k += 2;
1152         x <<= 2;
1153     }
1154     if (!(x & 0x80000000)) {
1155         k++;
1156         if (!(x & 0x40000000))
1157             return 32;
1158     }
1159     return k;
1160 }
1161 
1162 static int
1163 lo0bits(ULong *y)
1164 {
1165     register int k;
1166     register ULong x = *y;
1167 
1168     if (x & 7) {
1169         if (x & 1)
1170             return 0;
1171         if (x & 2) {
1172             *y = x >> 1;
1173             return 1;
1174         }
1175         *y = x >> 2;
1176         return 2;
1177     }
1178     k = 0;
1179     if (!(x & 0xffff)) {
1180         k = 16;
1181         x >>= 16;
1182     }
1183     if (!(x & 0xff)) {
1184         k += 8;
1185         x >>= 8;
1186     }
1187     if (!(x & 0xf)) {
1188         k += 4;
1189         x >>= 4;
1190     }
1191     if (!(x & 0x3)) {
1192         k += 2;
1193         x >>= 2;
1194     }
1195     if (!(x & 1)) {
1196         k++;
1197         x >>= 1;
1198         if (!x)
1199             return 32;
1200     }
1201     *y = x;
1202     return k;
1203 }
1204 
1205 static Bigint *
1206 i2b(int i)
1207 {
1208     Bigint *b;
1209 
1210     b = Balloc(1);
1211     b->x[0] = i;
1212     b->wds = 1;
1213     return b;
1214 }
1215 
1216 static Bigint *
1217 mult(Bigint *a, Bigint *b)
1218 {
1219     Bigint *c;
1220     int k, wa, wb, wc;
1221     ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
1222     ULong y;
1223 #ifdef ULLong
1224     ULLong carry, z;
1225 #else
1226     ULong carry, z;
1227 #ifdef Pack_32
1228     ULong z2;
1229 #endif
1230 #endif
1231 
1232     if (a->wds < b->wds) {
1233         c = a;
1234         a = b;
1235         b = c;
1236     }
1237     k = a->k;
1238     wa = a->wds;
1239     wb = b->wds;
1240     wc = wa + wb;
1241     if (wc > a->maxwds)
1242         k++;
1243     c = Balloc(k);
1244     for (x = c->x, xa = x + wc; x < xa; x++)
1245         *x = 0;
1246     xa = a->x;
1247     xae = xa + wa;
1248     xb = b->x;
1249     xbe = xb + wb;
1250     xc0 = c->x;
1251 #ifdef ULLong
1252     for (; xb < xbe; xc0++) {
1253         if ((y = *xb++) != 0) {
1254             x = xa;
1255             xc = xc0;
1256             carry = 0;
1257             do {
1258                 z = *x++ * (ULLong)y + *xc + carry;
1259                 carry = z >> 32;
1260                 *xc++ = (ULong)(z & FFFFFFFF);
1261             } while (x < xae);
1262             *xc = (ULong)carry;
1263         }
1264     }
1265 #else
1266 #ifdef Pack_32
1267     for (; xb < xbe; xb++, xc0++) {
1268         if (y = *xb & 0xffff) {
1269             x = xa;
1270             xc = xc0;
1271             carry = 0;
1272             do {
1273                 z = (*x & 0xffff) * y + (*xc & 0xffff) + carry;
1274                 carry = z >> 16;
1275                 z2 = (*x++ >> 16) * y + (*xc >> 16) + carry;
1276                 carry = z2 >> 16;
1277                 Storeinc(xc, z2, z);
1278             } while (x < xae);
1279             *xc = (ULong)carry;
1280         }
1281         if (y = *xb >> 16) {
1282             x = xa;
1283             xc = xc0;
1284             carry = 0;
1285             z2 = *xc;
1286             do {
1287                 z = (*x & 0xffff) * y + (*xc >> 16) + carry;
1288                 carry = z >> 16;
1289                 Storeinc(xc, z, z2);
1290                 z2 = (*x++ >> 16) * y + (*xc & 0xffff) + carry;
1291                 carry = z2 >> 16;
1292             } while (x < xae);
1293             *xc = z2;
1294         }
1295     }
1296 #else
1297     for (; xb < xbe; xc0++) {
1298         if (y = *xb++) {
1299             x = xa;
1300             xc = xc0;
1301             carry = 0;
1302             do {
1303                 z = *x++ * y + *xc + carry;
1304                 carry = z >> 16;
1305                 *xc++ = z & 0xffff;
1306             } while (x < xae);
1307             *xc = (ULong)carry;
1308         }
1309     }
1310 #endif
1311 #endif
1312     for (xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ;
1313     c->wds = wc;
1314     return c;
1315 }
1316 
1317 static Bigint *p5s;
1318 
1319 static Bigint *
1320 pow5mult(Bigint *b, int k)
1321 {
1322     Bigint *b1, *p5, *p51;
1323     int i;
1324     static int p05[3] = { 5, 25, 125 };
1325 
1326     if ((i = k & 3) != 0)
1327         b = multadd(b, p05[i-1], 0);
1328 
1329     if (!(k >>= 2))
1330         return b;
1331     if (!(p5 = p5s)) {
1332         /* first time */
1333 #ifdef MULTIPLE_THREADS
1334         ACQUIRE_DTOA_LOCK(1);
1335         if (!(p5 = p5s)) {
1336             p5 = p5s = i2b(625);
1337             p5->next = 0;
1338         }
1339         FREE_DTOA_LOCK(1);
1340 #else
1341         p5 = p5s = i2b(625);
1342         p5->next = 0;
1343 #endif
1344     }
1345     for (;;) {
1346         if (k & 1) {
1347             b1 = mult(b, p5);
1348             Bfree(b);
1349             b = b1;
1350         }
1351         if (!(k >>= 1))
1352             break;
1353         if (!(p51 = p5->next)) {
1354 #ifdef MULTIPLE_THREADS
1355             ACQUIRE_DTOA_LOCK(1);
1356             if (!(p51 = p5->next)) {
1357                 p51 = p5->next = mult(p5,p5);
1358                 p51->next = 0;
1359             }
1360             FREE_DTOA_LOCK(1);
1361 #else
1362             p51 = p5->next = mult(p5,p5);
1363             p51->next = 0;
1364 #endif
1365         }
1366         p5 = p51;
1367     }
1368     return b;
1369 }
1370 
1371 static Bigint *
1372 lshift(Bigint *b, int k)
1373 {
1374     int i, k1, n, n1;
1375     Bigint *b1;
1376     ULong *x, *x1, *xe, z;
1377 
1378 #ifdef Pack_32
1379     n = k >> 5;
1380 #else
1381     n = k >> 4;
1382 #endif
1383     k1 = b->k;
1384     n1 = n + b->wds + 1;
1385     for (i = b->maxwds; n1 > i; i <<= 1)
1386         k1++;
1387     b1 = Balloc(k1);
1388     x1 = b1->x;
1389     for (i = 0; i < n; i++)
1390         *x1++ = 0;
1391     x = b->x;
1392     xe = x + b->wds;
1393 #ifdef Pack_32
1394     if (k &= 0x1f) {
1395         k1 = 32 - k;
1396         z = 0;
1397         do {
1398             *x1++ = *x << k | z;
1399             z = *x++ >> k1;
1400         } while (x < xe);
1401         if ((*x1 = z) != 0)
1402             ++n1;
1403     }
1404 #else
1405     if (k &= 0xf) {
1406         k1 = 16 - k;
1407         z = 0;
1408         do {
1409             *x1++ = *x << k  & 0xffff | z;
1410             z = *x++ >> k1;
1411         } while (x < xe);
1412         if (*x1 = z)
1413             ++n1;
1414     }
1415 #endif
1416     else
1417         do {
1418             *x1++ = *x++;
1419         } while (x < xe);
1420     b1->wds = n1 - 1;
1421     Bfree(b);
1422     return b1;
1423 }
1424 
1425 static int
1426 cmp(Bigint *a, Bigint *b)
1427 {
1428     ULong *xa, *xa0, *xb, *xb0;
1429     int i, j;
1430 
1431     i = a->wds;
1432     j = b->wds;
1433 #ifdef DEBUG
1434     if (i > 1 && !a->x[i-1])
1435         Bug("cmp called with a->x[a->wds-1] == 0");
1436     if (j > 1 && !b->x[j-1])
1437         Bug("cmp called with b->x[b->wds-1] == 0");
1438 #endif
1439     if (i -= j)
1440         return i;
1441     xa0 = a->x;
1442     xa = xa0 + j;
1443     xb0 = b->x;
1444     xb = xb0 + j;
1445     for (;;) {
1446         if (*--xa != *--xb)
1447             return *xa < *xb ? -1 : 1;
1448         if (xa <= xa0)
1449             break;
1450     }
1451     return 0;
1452 }
1453 
1454 static Bigint *
1455 diff(Bigint *a, Bigint *b)
1456 {
1457     Bigint *c;
1458     int i, wa, wb;
1459     ULong *xa, *xae, *xb, *xbe, *xc;
1460 #ifdef ULLong
1461     ULLong borrow, y;
1462 #else
1463     ULong borrow, y;
1464 #ifdef Pack_32
1465     ULong z;
1466 #endif
1467 #endif
1468 
1469     i = cmp(a,b);
1470     if (!i) {
1471         c = Balloc(0);
1472         c->wds = 1;
1473         c->x[0] = 0;
1474         return c;
1475     }
1476     if (i < 0) {
1477         c = a;
1478         a = b;
1479         b = c;
1480         i = 1;
1481     }
1482     else
1483         i = 0;
1484     c = Balloc(a->k);
1485     c->sign = i;
1486     wa = a->wds;
1487     xa = a->x;
1488     xae = xa + wa;
1489     wb = b->wds;
1490     xb = b->x;
1491     xbe = xb + wb;
1492     xc = c->x;
1493     borrow = 0;
1494 #ifdef ULLong
1495     do {
1496         y = (ULLong)*xa++ - *xb++ - borrow;
1497         borrow = y >> 32 & (ULong)1;
1498         *xc++ = (ULong)(y & FFFFFFFF);
1499     } while (xb < xbe);
1500     while (xa < xae) {
1501         y = *xa++ - borrow;
1502         borrow = y >> 32 & (ULong)1;
1503         *xc++ = (ULong)(y & FFFFFFFF);
1504     }
1505 #else
1506 #ifdef Pack_32
1507     do {
1508         y = (*xa & 0xffff) - (*xb & 0xffff) - borrow;
1509         borrow = (y & 0x10000) >> 16;
1510         z = (*xa++ >> 16) - (*xb++ >> 16) - borrow;
1511         borrow = (z & 0x10000) >> 16;
1512         Storeinc(xc, z, y);
1513     } while (xb < xbe);
1514     while (xa < xae) {
1515         y = (*xa & 0xffff) - borrow;
1516         borrow = (y & 0x10000) >> 16;
1517         z = (*xa++ >> 16) - borrow;
1518         borrow = (z & 0x10000) >> 16;
1519         Storeinc(xc, z, y);
1520     }
1521 #else
1522     do {
1523         y = *xa++ - *xb++ - borrow;
1524         borrow = (y & 0x10000) >> 16;
1525         *xc++ = y & 0xffff;
1526     } while (xb < xbe);
1527     while (xa < xae) {
1528         y = *xa++ - borrow;
1529         borrow = (y & 0x10000) >> 16;
1530         *xc++ = y & 0xffff;
1531     }
1532 #endif
1533 #endif
1534     while (!*--xc)
1535         wa--;
1536     c->wds = wa;
1537     return c;
1538 }
1539 
1540 static double
1541 ulp(double x_)
1542 {
1543     register Long L;
1544     double_u x, a;
1545     dval(x) = x_;
1546 
1547     L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1;
1548 #ifndef Avoid_Underflow
1549 #ifndef Sudden_Underflow
1550     if (L > 0) {
1551 #endif
1552 #endif
1553 #ifdef IBM
1554         L |= Exp_msk1 >> 4;
1555 #endif
1556         word0(a) = L;
1557         word1(a) = 0;
1558 #ifndef Avoid_Underflow
1559 #ifndef Sudden_Underflow
1560     }
1561     else {
1562         L = -L >> Exp_shift;
1563         if (L < Exp_shift) {
1564             word0(a) = 0x80000 >> L;
1565             word1(a) = 0;
1566         }
1567         else {
1568             word0(a) = 0;
1569             L -= Exp_shift;
1570             word1(a) = L >= 31 ? 1 : 1 << 31 - L;
1571         }
1572     }
1573 #endif
1574 #endif
1575     return dval(a);
1576 }
1577 
1578 static double
1579 b2d(Bigint *a, int *e)
1580 {
1581     ULong *xa, *xa0, w, y, z;
1582     int k;
1583     double_u d;
1584 #ifdef VAX
1585     ULong d0, d1;
1586 #else
1587 #define d0 word0(d)
1588 #define d1 word1(d)
1589 #endif
1590 
1591     xa0 = a->x;
1592     xa = xa0 + a->wds;
1593     y = *--xa;
1594 #ifdef DEBUG
1595     if (!y) Bug("zero y in b2d");
1596 #endif
1597     k = hi0bits(y);
1598     *e = 32 - k;
1599 #ifdef Pack_32
1600     if (k < Ebits) {
1601         d0 = Exp_1 | y >> (Ebits - k);
1602         w = xa > xa0 ? *--xa : 0;
1603         d1 = y << ((32-Ebits) + k) | w >> (Ebits - k);
1604         goto ret_d;
1605     }
1606     z = xa > xa0 ? *--xa : 0;
1607     if (k -= Ebits) {
1608         d0 = Exp_1 | y << k | z >> (32 - k);
1609         y = xa > xa0 ? *--xa : 0;
1610         d1 = z << k | y >> (32 - k);
1611     }
1612     else {
1613         d0 = Exp_1 | y;
1614         d1 = z;
1615     }
1616 #else
1617     if (k < Ebits + 16) {
1618         z = xa > xa0 ? *--xa : 0;
1619         d0 = Exp_1 | y << k - Ebits | z >> Ebits + 16 - k;
1620         w = xa > xa0 ? *--xa : 0;
1621         y = xa > xa0 ? *--xa : 0;
1622         d1 = z << k + 16 - Ebits | w << k - Ebits | y >> 16 + Ebits - k;
1623         goto ret_d;
1624     }
1625     z = xa > xa0 ? *--xa : 0;
1626     w = xa > xa0 ? *--xa : 0;
1627     k -= Ebits + 16;
1628     d0 = Exp_1 | y << k + 16 | z << k | w >> 16 - k;
1629     y = xa > xa0 ? *--xa : 0;
1630     d1 = w << k + 16 | y << k;
1631 #endif
1632 ret_d:
1633 #ifdef VAX
1634     word0(d) = d0 >> 16 | d0 << 16;
1635     word1(d) = d1 >> 16 | d1 << 16;
1636 #else
1637 #undef d0
1638 #undef d1
1639 #endif
1640     return dval(d);
1641 }
1642 
1643 static Bigint *
1644 d2b(double d_, int *e, int *bits)
1645 {
1646     double_u d;
1647     Bigint *b;
1648     int de, k;
1649     ULong *x, y, z;
1650 #ifndef Sudden_Underflow
1651     int i;
1652 #endif
1653 #ifdef VAX
1654     ULong d0, d1;
1655 #endif
1656     dval(d) = d_;
1657 #ifdef VAX
1658     d0 = word0(d) >> 16 | word0(d) << 16;
1659     d1 = word1(d) >> 16 | word1(d) << 16;
1660 #else
1661 #define d0 word0(d)
1662 #define d1 word1(d)
1663 #endif
1664 
1665 #ifdef Pack_32
1666     b = Balloc(1);
1667 #else
1668     b = Balloc(2);
1669 #endif
1670     x = b->x;
1671 
1672     z = d0 & Frac_mask;
1673     d0 &= 0x7fffffff;   /* clear sign bit, which we ignore */
1674 #ifdef Sudden_Underflow
1675     de = (int)(d0 >> Exp_shift);
1676 #ifndef IBM
1677     z |= Exp_msk11;
1678 #endif
1679 #else
1680     if ((de = (int)(d0 >> Exp_shift)) != 0)
1681         z |= Exp_msk1;
1682 #endif
1683 #ifdef Pack_32
1684     if ((y = d1) != 0) {
1685         if ((k = lo0bits(&y)) != 0) {
1686             x[0] = y | z << (32 - k);
1687             z >>= k;
1688         }
1689         else
1690             x[0] = y;
1691 #ifndef Sudden_Underflow
1692         i =
1693 #endif
1694         b->wds = (x[1] = z) ? 2 : 1;
1695     }
1696     else {
1697 #ifdef DEBUG
1698         if (!z)
1699             Bug("Zero passed to d2b");
1700 #endif
1701         k = lo0bits(&z);
1702         x[0] = z;
1703 #ifndef Sudden_Underflow
1704         i =
1705 #endif
1706         b->wds = 1;
1707         k += 32;
1708     }
1709 #else
1710     if (y = d1) {
1711         if (k = lo0bits(&y))
1712             if (k >= 16) {
1713                 x[0] = y | z << 32 - k & 0xffff;
1714                 x[1] = z >> k - 16 & 0xffff;
1715                 x[2] = z >> k;
1716                 i = 2;
1717             }
1718             else {
1719                 x[0] = y & 0xffff;
1720                 x[1] = y >> 16 | z << 16 - k & 0xffff;
1721                 x[2] = z >> k & 0xffff;
1722                 x[3] = z >> k+16;
1723                 i = 3;
1724             }
1725         else {
1726             x[0] = y & 0xffff;
1727             x[1] = y >> 16;
1728             x[2] = z & 0xffff;
1729             x[3] = z >> 16;
1730             i = 3;
1731         }
1732     }
1733     else {
1734 #ifdef DEBUG
1735         if (!z)
1736             Bug("Zero passed to d2b");
1737 #endif
1738         k = lo0bits(&z);
1739         if (k >= 16) {
1740             x[0] = z;
1741             i = 0;
1742         }
1743         else {
1744             x[0] = z & 0xffff;
1745             x[1] = z >> 16;
1746             i = 1;
1747         }
1748         k += 32;
1749     }
1750     while (!x[i])
1751         --i;
1752     b->wds = i + 1;
1753 #endif
1754 #ifndef Sudden_Underflow
1755     if (de) {
1756 #endif
1757 #ifdef IBM
1758         *e = (de - Bias - (P-1) << 2) + k;
1759         *bits = 4*P + 8 - k - hi0bits(word0(d) & Frac_mask);
1760 #else
1761         *e = de - Bias - (P-1) + k;
1762         *bits = P - k;
1763 #endif
1764 #ifndef Sudden_Underflow
1765     }
1766     else {
1767         *e = de - Bias - (P-1) + 1 + k;
1768 #ifdef Pack_32
1769         *bits = 32*i - hi0bits(x[i-1]);
1770 #else
1771         *bits = (i+2)*16 - hi0bits(x[i]);
1772 #endif
1773     }
1774 #endif
1775     return b;
1776 }
1777 #undef d0
1778 #undef d1
1779 
1780 static double
1781 ratio(Bigint *a, Bigint *b)
1782 {
1783     double_u da, db;
1784     int k, ka, kb;
1785 
1786     dval(da) = b2d(a, &ka);
1787     dval(db) = b2d(b, &kb);
1788 #ifdef Pack_32
1789     k = ka - kb + 32*(a->wds - b->wds);
1790 #else
1791     k = ka - kb + 16*(a->wds - b->wds);
1792 #endif
1793 #ifdef IBM
1794     if (k > 0) {
1795         word0(da) += (k >> 2)*Exp_msk1;
1796         if (k &= 3)
1797             dval(da) *= 1 << k;
1798     }
1799     else {
1800         k = -k;
1801         word0(db) += (k >> 2)*Exp_msk1;
1802         if (k &= 3)
1803             dval(db) *= 1 << k;
1804     }
1805 #else
1806     if (k > 0)
1807         word0(da) += k*Exp_msk1;
1808     else {
1809         k = -k;
1810         word0(db) += k*Exp_msk1;
1811     }
1812 #endif
1813     return dval(da) / dval(db);
1814 }
1815 
1816 static const double
1817 tens[] = {
1818     1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
1819     1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
1820     1e20, 1e21, 1e22
1821 #ifdef VAX
1822     , 1e23, 1e24
1823 #endif
1824 };
1825 
1826 static const double
1827 #ifdef IEEE_Arith
1828 bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 };
1829 static const double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128,
1830 #ifdef Avoid_Underflow
1831     9007199254740992.*9007199254740992.e-256
1832     /* = 2^106 * 1e-53 */
1833 #else
1834     1e-256
1835 #endif
1836 };
1837 /* The factor of 2^53 in tinytens[4] helps us avoid setting the underflow */
1838 /* flag unnecessarily.  It leads to a song and dance at the end of strtod. */
1839 #define Scale_Bit 0x10
1840 #define n_bigtens 5
1841 #else
1842 #ifdef IBM
1843 bigtens[] = { 1e16, 1e32, 1e64 };
1844 static const double tinytens[] = { 1e-16, 1e-32, 1e-64 };
1845 #define n_bigtens 3
1846 #else
1847 bigtens[] = { 1e16, 1e32 };
1848 static const double tinytens[] = { 1e-16, 1e-32 };
1849 #define n_bigtens 2
1850 #endif
1851 #endif
1852 
1853 #ifndef IEEE_Arith
1854 #undef INFNAN_CHECK
1855 #endif
1856 
1857 #ifdef INFNAN_CHECK
1858 
1859 #ifndef NAN_WORD0
1860 #define NAN_WORD0 0x7ff80000
1861 #endif
1862 
1863 #ifndef NAN_WORD1
1864 #define NAN_WORD1 0
1865 #endif
1866 
1867 static int
1868 match(const char **sp, char *t)
1869 {
1870     int c, d;
1871     const char *s = *sp;
1872 
1873     while (d = *t++) {
1874         if ((c = *++s) >= 'A' && c <= 'Z')
1875             c += 'a' - 'A';
1876         if (c != d)
1877             return 0;
1878     }
1879     *sp = s + 1;
1880     return 1;
1881 }
1882 
1883 #ifndef No_Hex_NaN
1884 static void
1885 hexnan(double *rvp, const char **sp)
1886 {
1887     ULong c, x[2];
1888     const char *s;
1889     int havedig, udx0, xshift;
1890 
1891     x[0] = x[1] = 0;
1892     havedig = xshift = 0;
1893     udx0 = 1;
1894     s = *sp;
1895     while (c = *(const unsigned char*)++s) {
1896         if (c >= '0' && c <= '9')
1897             c -= '0';
1898         else if (c >= 'a' && c <= 'f')
1899             c += 10 - 'a';
1900         else if (c >= 'A' && c <= 'F')
1901             c += 10 - 'A';
1902         else if (c <= ' ') {
1903             if (udx0 && havedig) {
1904                 udx0 = 0;
1905                 xshift = 1;
1906             }
1907             continue;
1908         }
1909         else if (/*(*/ c == ')' && havedig) {
1910             *sp = s + 1;
1911             break;
1912         }
1913         else
1914             return; /* invalid form: don't change *sp */
1915         havedig = 1;
1916         if (xshift) {
1917             xshift = 0;
1918             x[0] = x[1];
1919             x[1] = 0;
1920         }
1921         if (udx0)
1922             x[0] = (x[0] << 4) | (x[1] >> 28);
1923         x[1] = (x[1] << 4) | c;
1924     }
1925     if ((x[0] &= 0xfffff) || x[1]) {
1926         word0(*rvp) = Exp_mask | x[0];
1927         word1(*rvp) = x[1];
1928     }
1929 }
1930 #endif /*No_Hex_NaN*/
1931 #endif /* INFNAN_CHECK */
1932 
1933 double
1934 ruby_strtod(const char *s00, char **se)
1935 {
1936 #ifdef Avoid_Underflow
1937     int scale;
1938 #endif
1939     int bb2, bb5, bbe, bd2, bd5, bbbits, bs2, c, dsign,
1940          e, e1, esign, i, j, k, nd, nd0, nf, nz, nz0, sign;
1941     const char *s, *s0, *s1;
1942     double aadj, adj;
1943     double_u aadj1, rv, rv0;
1944     Long L;
1945     ULong y, z;
1946     Bigint *bb, *bb1, *bd, *bd0, *bs, *delta;
1947 #ifdef SET_INEXACT
1948     int inexact, oldinexact;
1949 #endif
1950 #ifdef Honor_FLT_ROUNDS
1951     int rounding;
1952 #endif
1953 #ifdef USE_LOCALE
1954     const char *s2;
1955 #endif
1956 
1957     errno = 0;
1958     sign = nz0 = nz = 0;
1959     dval(rv) = 0.;
1960     for (s = s00;;s++)
1961         switch (*s) {
1962           case '-':
1963             sign = 1;
1964             /* no break */
1965           case '+':
1966             if (*++s)
1967                 goto break2;
1968             /* no break */
1969           case 0:
1970             goto ret0;
1971           case '\t':
1972           case '\n':
1973           case '\v':
1974           case '\f':
1975           case '\r':
1976           case ' ':
1977             continue;
1978           default:
1979             goto break2;
1980         }
1981 break2:
1982     if (*s == '0') {
1983         if (s[1] == 'x' || s[1] == 'X') {
1984             static const char hexdigit[] = "0123456789abcdef0123456789ABCDEF";
1985             s0 = ++s;
1986             adj = 0;
1987             aadj = 1.0;
1988             nd0 = -4;
1989 
1990             if (!*++s || !(s1 = strchr(hexdigit, *s))) goto ret0;
1991             if (*s == '0') {
1992                 while (*++s == '0');
1993                 s1 = strchr(hexdigit, *s);
1994             }
1995             if (s1 != NULL) {
1996                 do {
1997                     adj += aadj * ((s1 - hexdigit) & 15);
1998                     nd0 += 4;
1999                     aadj /= 16;
2000                 } while (*++s && (s1 = strchr(hexdigit, *s)));
2001             }
2002 
2003             if (*s == '.') {
2004                 dsign = 1;
2005                 if (!*++s || !(s1 = strchr(hexdigit, *s))) goto ret0;
2006                 if (nd0 < 0) {
2007                     while (*s == '0') {
2008                         s++;
2009                         nd0 -= 4;
2010                     }
2011                 }
2012                 for (; *s && (s1 = strchr(hexdigit, *s)); ++s) {
2013                     adj += aadj * ((s1 - hexdigit) & 15);
2014                     if ((aadj /= 16) == 0.0) {
2015                         while (strchr(hexdigit, *++s));
2016                         break;
2017                     }
2018                 }
2019             }
2020             else {
2021                 dsign = 0;
2022             }
2023 
2024             if (*s == 'P' || *s == 'p') {
2025                 dsign = 0x2C - *++s; /* +: 2B, -: 2D */
2026                 if (abs(dsign) == 1) s++;
2027                 else dsign = 1;
2028 
2029                 nd = 0;
2030                 c = *s;
2031                 if (c < '0' || '9' < c) goto ret0;
2032                 do {
2033                     nd *= 10;
2034                     nd += c;
2035                     nd -= '0';
2036                     c = *++s;
2037                     /* Float("0x0."+("0"*267)+"1fp2095") */
2038                     if (nd + dsign * nd0 > 2095) {
2039                         while ('0' <= c && c <= '9') c = *++s;
2040                         break;
2041                     }
2042                 } while ('0' <= c && c <= '9');
2043                 nd0 += nd * dsign;
2044             }
2045             else {
2046                 if (dsign) goto ret0;
2047             }
2048             dval(rv) = ldexp(adj, nd0);
2049             goto ret;
2050         }
2051         nz0 = 1;
2052         while (*++s == '0') ;
2053         if (!*s)
2054             goto ret;
2055     }
2056     s0 = s;
2057     y = z = 0;
2058     for (nd = nf = 0; (c = *s) >= '0' && c <= '9'; nd++, s++)
2059         if (nd < 9)
2060             y = 10*y + c - '0';
2061         else if (nd < 16)
2062             z = 10*z + c - '0';
2063     nd0 = nd;
2064 #ifdef USE_LOCALE
2065     s1 = localeconv()->decimal_point;
2066     if (c == *s1) {
2067         c = '.';
2068         if (*++s1) {
2069             s2 = s;
2070             for (;;) {
2071                 if (*++s2 != *s1) {
2072                     c = 0;
2073                     break;
2074                 }
2075                 if (!*++s1) {
2076                     s = s2;
2077                     break;
2078                 }
2079             }
2080         }
2081     }
2082 #endif
2083     if (c == '.') {
2084         if (!ISDIGIT(s[1]))
2085             goto dig_done;
2086         c = *++s;
2087         if (!nd) {
2088             for (; c == '0'; c = *++s)
2089                 nz++;
2090             if (c > '0' && c <= '9') {
2091                 s0 = s;
2092                 nf += nz;
2093                 nz = 0;
2094                 goto have_dig;
2095             }
2096             goto dig_done;
2097         }
2098         for (; c >= '0' && c <= '9'; c = *++s) {
2099 have_dig:
2100             nz++;
2101             if (c -= '0') {
2102                 nf += nz;
2103                 for (i = 1; i < nz; i++)
2104                     if (nd++ < 9)
2105                         y *= 10;
2106                     else if (nd <= DBL_DIG + 1)
2107                         z *= 10;
2108                 if (nd++ < 9)
2109                     y = 10*y + c;
2110                 else if (nd <= DBL_DIG + 1)
2111                     z = 10*z + c;
2112                 nz = 0;
2113             }
2114         }
2115     }
2116 dig_done:
2117     e = 0;
2118     if (c == 'e' || c == 'E') {
2119         if (!nd && !nz && !nz0) {
2120             goto ret0;
2121         }
2122         s00 = s;
2123         esign = 0;
2124         switch (c = *++s) {
2125           case '-':
2126             esign = 1;
2127           case '+':
2128             c = *++s;
2129         }
2130         if (c >= '0' && c <= '9') {
2131             while (c == '0')
2132                 c = *++s;
2133             if (c > '0' && c <= '9') {
2134                 L = c - '0';
2135                 s1 = s;
2136                 while ((c = *++s) >= '0' && c <= '9')
2137                     L = 10*L + c - '0';
2138                 if (s - s1 > 8 || L > 19999)
2139                     /* Avoid confusion from exponents
2140                      * so large that e might overflow.
2141                      */
2142                     e = 19999; /* safe for 16 bit ints */
2143                 else
2144                     e = (int)L;
2145                 if (esign)
2146                     e = -e;
2147             }
2148             else
2149                 e = 0;
2150         }
2151         else
2152             s = s00;
2153     }
2154     if (!nd) {
2155         if (!nz && !nz0) {
2156 #ifdef INFNAN_CHECK
2157             /* Check for Nan and Infinity */
2158             switch (c) {
2159               case 'i':
2160               case 'I':
2161                 if (match(&s,"nf")) {
2162                     --s;
2163                     if (!match(&s,"inity"))
2164                         ++s;
2165                     word0(rv) = 0x7ff00000;
2166                     word1(rv) = 0;
2167                     goto ret;
2168                 }
2169                 break;
2170               case 'n':
2171               case 'N':
2172                 if (match(&s, "an")) {
2173                     word0(rv) = NAN_WORD0;
2174                     word1(rv) = NAN_WORD1;
2175 #ifndef No_Hex_NaN
2176                     if (*s == '(') /*)*/
2177                         hexnan(&rv, &s);
2178 #endif
2179                     goto ret;
2180                 }
2181             }
2182 #endif /* INFNAN_CHECK */
2183 ret0:
2184             s = s00;
2185             sign = 0;
2186         }
2187         goto ret;
2188     }
2189     e1 = e -= nf;
2190 
2191     /* Now we have nd0 digits, starting at s0, followed by a
2192      * decimal point, followed by nd-nd0 digits.  The number we're
2193      * after is the integer represented by those digits times
2194      * 10**e */
2195 
2196     if (!nd0)
2197         nd0 = nd;
2198     k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;
2199     dval(rv) = y;
2200     if (k > 9) {
2201 #ifdef SET_INEXACT
2202         if (k > DBL_DIG)
2203             oldinexact = get_inexact();
2204 #endif
2205         dval(rv) = tens[k - 9] * dval(rv) + z;
2206     }
2207     bd0 = bb = bd = bs = delta = 0;
2208     if (nd <= DBL_DIG
2209 #ifndef RND_PRODQUOT
2210 #ifndef Honor_FLT_ROUNDS
2211         && Flt_Rounds == 1
2212 #endif
2213 #endif
2214     ) {
2215         if (!e)
2216             goto ret;
2217         if (e > 0) {
2218             if (e <= Ten_pmax) {
2219 #ifdef VAX
2220                 goto vax_ovfl_check;
2221 #else
2222 #ifdef Honor_FLT_ROUNDS
2223                 /* round correctly FLT_ROUNDS = 2 or 3 */
2224                 if (sign) {
2225                     dval(rv) = -dval(rv);
2226                     sign = 0;
2227                 }
2228 #endif
2229                 /* rv = */ rounded_product(dval(rv), tens[e]);
2230                 goto ret;
2231 #endif
2232             }
2233             i = DBL_DIG - nd;
2234             if (e <= Ten_pmax + i) {
2235                 /* A fancier test would sometimes let us do
2236                  * this for larger i values.
2237                  */
2238 #ifdef Honor_FLT_ROUNDS
2239                 /* round correctly FLT_ROUNDS = 2 or 3 */
2240                 if (sign) {
2241                     dval(rv) = -dval(rv);
2242                     sign = 0;
2243                 }
2244 #endif
2245                 e -= i;
2246                 dval(rv) *= tens[i];
2247 #ifdef VAX
2248                 /* VAX exponent range is so narrow we must
2249                  * worry about overflow here...
2250                  */
2251 vax_ovfl_check:
2252                 word0(rv) -= P*Exp_msk1;
2253                 /* rv = */ rounded_product(dval(rv), tens[e]);
2254                 if ((word0(rv) & Exp_mask)
2255                         > Exp_msk1*(DBL_MAX_EXP+Bias-1-P))
2256                     goto ovfl;
2257                 word0(rv) += P*Exp_msk1;
2258 #else
2259                 /* rv = */ rounded_product(dval(rv), tens[e]);
2260 #endif
2261                 goto ret;
2262             }
2263         }
2264 #ifndef Inaccurate_Divide
2265         else if (e >= -Ten_pmax) {
2266 #ifdef Honor_FLT_ROUNDS
2267             /* round correctly FLT_ROUNDS = 2 or 3 */
2268             if (sign) {
2269                 dval(rv) = -dval(rv);
2270                 sign = 0;
2271             }
2272 #endif
2273             /* rv = */ rounded_quotient(dval(rv), tens[-e]);
2274             goto ret;
2275         }
2276 #endif
2277     }
2278     e1 += nd - k;
2279 
2280 #ifdef IEEE_Arith
2281 #ifdef SET_INEXACT
2282     inexact = 1;
2283     if (k <= DBL_DIG)
2284         oldinexact = get_inexact();
2285 #endif
2286 #ifdef Avoid_Underflow
2287     scale = 0;
2288 #endif
2289 #ifdef Honor_FLT_ROUNDS
2290     if ((rounding = Flt_Rounds) >= 2) {
2291         if (sign)
2292             rounding = rounding == 2 ? 0 : 2;
2293         else
2294             if (rounding != 2)
2295                 rounding = 0;
2296     }
2297 #endif
2298 #endif /*IEEE_Arith*/
2299 
2300     /* Get starting approximation = rv * 10**e1 */
2301 
2302     if (e1 > 0) {
2303         if ((i = e1 & 15) != 0)
2304             dval(rv) *= tens[i];
2305         if (e1 &= ~15) {
2306             if (e1 > DBL_MAX_10_EXP) {
2307 ovfl:
2308 #ifndef NO_ERRNO
2309                 errno = ERANGE;
2310 #endif
2311                 /* Can't trust HUGE_VAL */
2312 #ifdef IEEE_Arith
2313 #ifdef Honor_FLT_ROUNDS
2314                 switch (rounding) {
2315                   case 0: /* toward 0 */
2316                   case 3: /* toward -infinity */
2317                     word0(rv) = Big0;
2318                     word1(rv) = Big1;
2319                     break;
2320                   default:
2321                     word0(rv) = Exp_mask;
2322                     word1(rv) = 0;
2323                 }
2324 #else /*Honor_FLT_ROUNDS*/
2325                 word0(rv) = Exp_mask;
2326                 word1(rv) = 0;
2327 #endif /*Honor_FLT_ROUNDS*/
2328 #ifdef SET_INEXACT
2329                 /* set overflow bit */
2330                 dval(rv0) = 1e300;
2331                 dval(rv0) *= dval(rv0);
2332 #endif
2333 #else /*IEEE_Arith*/
2334                 word0(rv) = Big0;
2335                 word1(rv) = Big1;
2336 #endif /*IEEE_Arith*/
2337                 if (bd0)
2338                     goto retfree;
2339                 goto ret;
2340             }
2341             e1 >>= 4;
2342             for (j = 0; e1 > 1; j++, e1 >>= 1)
2343                 if (e1 & 1)
2344                     dval(rv) *= bigtens[j];
2345             /* The last multiplication could overflow. */
2346             word0(rv) -= P*Exp_msk1;
2347             dval(rv) *= bigtens[j];
2348             if ((z = word0(rv) & Exp_mask)
2349                     > Exp_msk1*(DBL_MAX_EXP+Bias-P))
2350                 goto ovfl;
2351             if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) {
2352                 /* set to largest number */
2353                 /* (Can't trust DBL_MAX) */
2354                 word0(rv) = Big0;
2355                 word1(rv) = Big1;
2356             }
2357             else
2358                 word0(rv) += P*Exp_msk1;
2359         }
2360     }
2361     else if (e1 < 0) {
2362         e1 = -e1;
2363         if ((i = e1 & 15) != 0)
2364             dval(rv) /= tens[i];
2365         if (e1 >>= 4) {
2366             if (e1 >= 1 << n_bigtens)
2367                 goto undfl;
2368 #ifdef Avoid_Underflow
2369             if (e1 & Scale_Bit)
2370                 scale = 2*P;
2371             for (j = 0; e1 > 0; j++, e1 >>= 1)
2372                 if (e1 & 1)
2373                     dval(rv) *= tinytens[j];
2374             if (scale && (j = 2*P + 1 - ((word0(rv) & Exp_mask)
2375                     >> Exp_shift)) > 0) {
2376                 /* scaled rv is denormal; zap j low bits */
2377                 if (j >= 32) {
2378                     word1(rv) = 0;
2379                     if (j >= 53)
2380                         word0(rv) = (P+2)*Exp_msk1;
2381                     else
2382                         word0(rv) &= 0xffffffff << (j-32);
2383                 }
2384                 else
2385                     word1(rv) &= 0xffffffff << j;
2386             }
2387 #else
2388             for (j = 0; e1 > 1; j++, e1 >>= 1)
2389                 if (e1 & 1)
2390                     dval(rv) *= tinytens[j];
2391             /* The last multiplication could underflow. */
2392             dval(rv0) = dval(rv);
2393             dval(rv) *= tinytens[j];
2394             if (!dval(rv)) {
2395                 dval(rv) = 2.*dval(rv0);
2396                 dval(rv) *= tinytens[j];
2397 #endif
2398                 if (!dval(rv)) {
2399 undfl:
2400                     dval(rv) = 0.;
2401 #ifndef NO_ERRNO
2402                     errno = ERANGE;
2403 #endif
2404                     if (bd0)
2405                         goto retfree;
2406                     goto ret;
2407                 }
2408 #ifndef Avoid_Underflow
2409                 word0(rv) = Tiny0;
2410                 word1(rv) = Tiny1;
2411                 /* The refinement below will clean
2412                  * this approximation up.
2413                  */
2414             }
2415 #endif
2416         }
2417     }
2418 
2419     /* Now the hard part -- adjusting rv to the correct value.*/
2420 
2421     /* Put digits into bd: true value = bd * 10^e */
2422 
2423     bd0 = s2b(s0, nd0, nd, y);
2424 
2425     for (;;) {
2426         bd = Balloc(bd0->k);
2427         Bcopy(bd, bd0);
2428         bb = d2b(dval(rv), &bbe, &bbbits);  /* rv = bb * 2^bbe */
2429         bs = i2b(1);
2430 
2431         if (e >= 0) {
2432             bb2 = bb5 = 0;
2433             bd2 = bd5 = e;
2434         }
2435         else {
2436             bb2 = bb5 = -e;
2437             bd2 = bd5 = 0;
2438         }
2439         if (bbe >= 0)
2440             bb2 += bbe;
2441         else
2442             bd2 -= bbe;
2443         bs2 = bb2;
2444 #ifdef Honor_FLT_ROUNDS
2445         if (rounding != 1)
2446             bs2++;
2447 #endif
2448 #ifdef Avoid_Underflow
2449         j = bbe - scale;
2450         i = j + bbbits - 1; /* logb(rv) */
2451         if (i < Emin)   /* denormal */
2452             j += P - Emin;
2453         else
2454             j = P + 1 - bbbits;
2455 #else /*Avoid_Underflow*/
2456 #ifdef Sudden_Underflow
2457 #ifdef IBM
2458         j = 1 + 4*P - 3 - bbbits + ((bbe + bbbits - 1) & 3);
2459 #else
2460         j = P + 1 - bbbits;
2461 #endif
2462 #else /*Sudden_Underflow*/
2463         j = bbe;
2464         i = j + bbbits - 1; /* logb(rv) */
2465         if (i < Emin)   /* denormal */
2466             j += P - Emin;
2467         else
2468             j = P + 1 - bbbits;
2469 #endif /*Sudden_Underflow*/
2470 #endif /*Avoid_Underflow*/
2471         bb2 += j;
2472         bd2 += j;
2473 #ifdef Avoid_Underflow
2474         bd2 += scale;
2475 #endif
2476         i = bb2 < bd2 ? bb2 : bd2;
2477         if (i > bs2)
2478             i = bs2;
2479         if (i > 0) {
2480             bb2 -= i;
2481             bd2 -= i;
2482             bs2 -= i;
2483         }
2484         if (bb5 > 0) {
2485             bs = pow5mult(bs, bb5);
2486             bb1 = mult(bs, bb);
2487             Bfree(bb);
2488             bb = bb1;
2489         }
2490         if (bb2 > 0)
2491             bb = lshift(bb, bb2);
2492         if (bd5 > 0)
2493             bd = pow5mult(bd, bd5);
2494         if (bd2 > 0)
2495             bd = lshift(bd, bd2);
2496         if (bs2 > 0)
2497             bs = lshift(bs, bs2);
2498         delta = diff(bb, bd);
2499         dsign = delta->sign;
2500         delta->sign = 0;
2501         i = cmp(delta, bs);
2502 #ifdef Honor_FLT_ROUNDS
2503         if (rounding != 1) {
2504             if (i < 0) {
2505                 /* Error is less than an ulp */
2506                 if (!delta->x[0] && delta->wds <= 1) {
2507                     /* exact */
2508 #ifdef SET_INEXACT
2509                     inexact = 0;
2510 #endif
2511                     break;
2512                 }
2513                 if (rounding) {
2514                     if (dsign) {
2515                         adj = 1.;
2516                         goto apply_adj;
2517                     }
2518                 }
2519                 else if (!dsign) {
2520                     adj = -1.;
2521                     if (!word1(rv)
2522                      && !(word0(rv) & Frac_mask)) {
2523                         y = word0(rv) & Exp_mask;
2524 #ifdef Avoid_Underflow
2525                         if (!scale || y > 2*P*Exp_msk1)
2526 #else
2527                         if (y)
2528 #endif
2529                         {
2530                             delta = lshift(delta,Log2P);
2531                             if (cmp(delta, bs) <= 0)
2532                                 adj = -0.5;
2533                         }
2534                     }
2535 apply_adj:
2536 #ifdef Avoid_Underflow
2537                     if (scale && (y = word0(rv) & Exp_mask)
2538                             <= 2*P*Exp_msk1)
2539                         word0(adj) += (2*P+1)*Exp_msk1 - y;
2540 #else
2541 #ifdef Sudden_Underflow
2542                     if ((word0(rv) & Exp_mask) <=
2543                             P*Exp_msk1) {
2544                         word0(rv) += P*Exp_msk1;
2545                         dval(rv) += adj*ulp(dval(rv));
2546                         word0(rv) -= P*Exp_msk1;
2547                     }
2548                     else
2549 #endif /*Sudden_Underflow*/
2550 #endif /*Avoid_Underflow*/
2551                     dval(rv) += adj*ulp(dval(rv));
2552                 }
2553                 break;
2554             }
2555             adj = ratio(delta, bs);
2556             if (adj < 1.)
2557                 adj = 1.;
2558             if (adj <= 0x7ffffffe) {
2559                 /* adj = rounding ? ceil(adj) : floor(adj); */
2560                 y = adj;
2561                 if (y != adj) {
2562                     if (!((rounding>>1) ^ dsign))
2563                         y++;
2564                     adj = y;
2565                 }
2566             }
2567 #ifdef Avoid_Underflow
2568             if (scale && (y = word0(rv) & Exp_mask) <= 2*P*Exp_msk1)
2569                 word0(adj) += (2*P+1)*Exp_msk1 - y;
2570 #else
2571 #ifdef Sudden_Underflow
2572             if ((word0(rv) & Exp_mask) <= P*Exp_msk1) {
2573                 word0(rv) += P*Exp_msk1;
2574                 adj *= ulp(dval(rv));
2575                 if (dsign)
2576                     dval(rv) += adj;
2577                 else
2578                     dval(rv) -= adj;
2579                 word0(rv) -= P*Exp_msk1;
2580                 goto cont;
2581             }
2582 #endif /*Sudden_Underflow*/
2583 #endif /*Avoid_Underflow*/
2584             adj *= ulp(dval(rv));
2585             if (dsign)
2586                 dval(rv) += adj;
2587             else
2588                 dval(rv) -= adj;
2589             goto cont;
2590         }
2591 #endif /*Honor_FLT_ROUNDS*/
2592 
2593         if (i < 0) {
2594             /* Error is less than half an ulp -- check for
2595              * special case of mantissa a power of two.
2596              */
2597             if (dsign || word1(rv) || word0(rv) & Bndry_mask
2598 #ifdef IEEE_Arith
2599 #ifdef Avoid_Underflow
2600                 || (word0(rv) & Exp_mask) <= (2*P+1)*Exp_msk1
2601 #else
2602                 || (word0(rv) & Exp_mask) <= Exp_msk1
2603 #endif
2604 #endif
2605             ) {
2606 #ifdef SET_INEXACT
2607                 if (!delta->x[0] && delta->wds <= 1)
2608                     inexact = 0;
2609 #endif
2610                 break;
2611             }
2612             if (!delta->x[0] && delta->wds <= 1) {
2613                 /* exact result */
2614 #ifdef SET_INEXACT
2615                 inexact = 0;
2616 #endif
2617                 break;
2618             }
2619             delta = lshift(delta,Log2P);
2620             if (cmp(delta, bs) > 0)
2621                 goto drop_down;
2622             break;
2623         }
2624         if (i == 0) {
2625             /* exactly half-way between */
2626             if (dsign) {
2627                 if ((word0(rv) & Bndry_mask1) == Bndry_mask1
2628                         &&  word1(rv) == (
2629 #ifdef Avoid_Underflow
2630                         (scale && (y = word0(rv) & Exp_mask) <= 2*P*Exp_msk1)
2631                         ? (0xffffffff & (0xffffffff << (2*P+1-(y>>Exp_shift)))) :
2632 #endif
2633                         0xffffffff)) {
2634                     /*boundary case -- increment exponent*/
2635                     word0(rv) = (word0(rv) & Exp_mask)
2636                                 + Exp_msk1
2637 #ifdef IBM
2638                                 | Exp_msk1 >> 4
2639 #endif
2640                     ;
2641                     word1(rv) = 0;
2642 #ifdef Avoid_Underflow
2643                     dsign = 0;
2644 #endif
2645                     break;
2646                 }
2647             }
2648             else if (!(word0(rv) & Bndry_mask) && !word1(rv)) {
2649 drop_down:
2650                 /* boundary case -- decrement exponent */
2651 #ifdef Sudden_Underflow /*{{*/
2652                 L = word0(rv) & Exp_mask;
2653 #ifdef IBM
2654                 if (L <  Exp_msk1)
2655 #else
2656 #ifdef Avoid_Underflow
2657                 if (L <= (scale ? (2*P+1)*Exp_msk1 : Exp_msk1))
2658 #else
2659                 if (L <= Exp_msk1)
2660 #endif /*Avoid_Underflow*/
2661 #endif /*IBM*/
2662                     goto undfl;
2663                 L -= Exp_msk1;
2664 #else /*Sudden_Underflow}{*/
2665 #ifdef Avoid_Underflow
2666                 if (scale) {
2667                     L = word0(rv) & Exp_mask;
2668                     if (L <= (2*P+1)*Exp_msk1) {
2669                         if (L > (P+2)*Exp_msk1)
2670                             /* round even ==> */
2671                             /* accept rv */
2672                             break;
2673                         /* rv = smallest denormal */
2674                         goto undfl;
2675                     }
2676                 }
2677 #endif /*Avoid_Underflow*/
2678                 L = (word0(rv) & Exp_mask) - Exp_msk1;
2679 #endif /*Sudden_Underflow}}*/
2680                 word0(rv) = L | Bndry_mask1;
2681                 word1(rv) = 0xffffffff;
2682 #ifdef IBM
2683                 goto cont;
2684 #else
2685                 break;
2686 #endif
2687             }
2688 #ifndef ROUND_BIASED
2689             if (!(word1(rv) & LSB))
2690                 break;
2691 #endif
2692             if (dsign)
2693                 dval(rv) += ulp(dval(rv));
2694 #ifndef ROUND_BIASED
2695             else {
2696                 dval(rv) -= ulp(dval(rv));
2697 #ifndef Sudden_Underflow
2698                 if (!dval(rv))
2699                     goto undfl;
2700 #endif
2701             }
2702 #ifdef Avoid_Underflow
2703             dsign = 1 - dsign;
2704 #endif
2705 #endif
2706             break;
2707         }
2708         if ((aadj = ratio(delta, bs)) <= 2.) {
2709             if (dsign)
2710                 aadj = dval(aadj1) = 1.;
2711             else if (word1(rv) || word0(rv) & Bndry_mask) {
2712 #ifndef Sudden_Underflow
2713                 if (word1(rv) == Tiny1 && !word0(rv))
2714                     goto undfl;
2715 #endif
2716                 aadj = 1.;
2717                 dval(aadj1) = -1.;
2718             }
2719             else {
2720                 /* special case -- power of FLT_RADIX to be */
2721                 /* rounded down... */
2722 
2723                 if (aadj < 2./FLT_RADIX)
2724                     aadj = 1./FLT_RADIX;
2725                 else
2726                     aadj *= 0.5;
2727                 dval(aadj1) = -aadj;
2728             }
2729         }
2730         else {
2731             aadj *= 0.5;
2732             dval(aadj1) = dsign ? aadj : -aadj;
2733 #ifdef Check_FLT_ROUNDS
2734             switch (Rounding) {
2735               case 2: /* towards +infinity */
2736                 dval(aadj1) -= 0.5;
2737                 break;
2738               case 0: /* towards 0 */
2739               case 3: /* towards -infinity */
2740                 dval(aadj1) += 0.5;
2741             }
2742 #else
2743             if (Flt_Rounds == 0)
2744                 dval(aadj1) += 0.5;
2745 #endif /*Check_FLT_ROUNDS*/
2746         }
2747         y = word0(rv) & Exp_mask;
2748 
2749         /* Check for overflow */
2750 
2751         if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) {
2752             dval(rv0) = dval(rv);
2753             word0(rv) -= P*Exp_msk1;
2754             adj = dval(aadj1) * ulp(dval(rv));
2755             dval(rv) += adj;
2756             if ((word0(rv) & Exp_mask) >=
2757                     Exp_msk1*(DBL_MAX_EXP+Bias-P)) {
2758                 if (word0(rv0) == Big0 && word1(rv0) == Big1)
2759                     goto ovfl;
2760                 word0(rv) = Big0;
2761                 word1(rv) = Big1;
2762                 goto cont;
2763             }
2764             else
2765                 word0(rv) += P*Exp_msk1;
2766         }
2767         else {
2768 #ifdef Avoid_Underflow
2769             if (scale && y <= 2*P*Exp_msk1) {
2770                 if (aadj <= 0x7fffffff) {
2771                     if ((z = (int)aadj) <= 0)
2772                         z = 1;
2773                     aadj = z;
2774                     dval(aadj1) = dsign ? aadj : -aadj;
2775                 }
2776                 word0(aadj1) += (2*P+1)*Exp_msk1 - y;
2777             }
2778             adj = dval(aadj1) * ulp(dval(rv));
2779             dval(rv) += adj;
2780 #else
2781 #ifdef Sudden_Underflow
2782             if ((word0(rv) & Exp_mask) <= P*Exp_msk1) {
2783                 dval(rv0) = dval(rv);
2784                 word0(rv) += P*Exp_msk1;
2785                 adj = dval(aadj1) * ulp(dval(rv));
2786                 dval(rv) += adj;
2787 #ifdef IBM
2788                 if ((word0(rv) & Exp_mask) <  P*Exp_msk1)
2789 #else
2790                 if ((word0(rv) & Exp_mask) <= P*Exp_msk1)
2791 #endif
2792                 {
2793                     if (word0(rv0) == Tiny0 && word1(rv0) == Tiny1)
2794                         goto undfl;
2795                     word0(rv) = Tiny0;
2796                     word1(rv) = Tiny1;
2797                     goto cont;
2798                 }
2799                 else
2800                     word0(rv) -= P*Exp_msk1;
2801             }
2802             else {
2803                 adj = dval(aadj1) * ulp(dval(rv));
2804                 dval(rv) += adj;
2805             }
2806 #else /*Sudden_Underflow*/
2807             /* Compute adj so that the IEEE rounding rules will
2808              * correctly round rv + adj in some half-way cases.
2809              * If rv * ulp(rv) is denormalized (i.e.,
2810              * y <= (P-1)*Exp_msk1), we must adjust aadj to avoid
2811              * trouble from bits lost to denormalization;
2812              * example: 1.2e-307 .
2813              */
2814             if (y <= (P-1)*Exp_msk1 && aadj > 1.) {
2815                 dval(aadj1) = (double)(int)(aadj + 0.5);
2816                 if (!dsign)
2817                     dval(aadj1) = -dval(aadj1);
2818             }
2819             adj = dval(aadj1) * ulp(dval(rv));
2820             dval(rv) += adj;
2821 #endif /*Sudden_Underflow*/
2822 #endif /*Avoid_Underflow*/
2823         }
2824         z = word0(rv) & Exp_mask;
2825 #ifndef SET_INEXACT
2826 #ifdef Avoid_Underflow
2827         if (!scale)
2828 #endif
2829         if (y == z) {
2830             /* Can we stop now? */
2831             L = (Long)aadj;
2832             aadj -= L;
2833             /* The tolerances below are conservative. */
2834             if (dsign || word1(rv) || word0(rv) & Bndry_mask) {
2835                 if (aadj < .4999999 || aadj > .5000001)
2836                     break;
2837             }
2838             else if (aadj < .4999999/FLT_RADIX)
2839                 break;
2840         }
2841 #endif
2842 cont:
2843         Bfree(bb);
2844         Bfree(bd);
2845         Bfree(bs);
2846         Bfree(delta);
2847     }
2848 #ifdef SET_INEXACT
2849     if (inexact) {
2850         if (!oldinexact) {
2851             word0(rv0) = Exp_1 + (70 << Exp_shift);
2852             word1(rv0) = 0;
2853             dval(rv0) += 1.;
2854         }
2855     }
2856     else if (!oldinexact)
2857         clear_inexact();
2858 #endif
2859 #ifdef Avoid_Underflow
2860     if (scale) {
2861         word0(rv0) = Exp_1 - 2*P*Exp_msk1;
2862         word1(rv0) = 0;
2863         dval(rv) *= dval(rv0);
2864 #ifndef NO_ERRNO
2865         /* try to avoid the bug of testing an 8087 register value */
2866         if (word0(rv) == 0 && word1(rv) == 0)
2867             errno = ERANGE;
2868 #endif
2869     }
2870 #endif /* Avoid_Underflow */
2871 #ifdef SET_INEXACT
2872     if (inexact && !(word0(rv) & Exp_mask)) {
2873         /* set underflow bit */
2874         dval(rv0) = 1e-300;
2875         dval(rv0) *= dval(rv0);
2876     }
2877 #endif
2878 retfree:
2879     Bfree(bb);
2880     Bfree(bd);
2881     Bfree(bs);
2882     Bfree(bd0);
2883     Bfree(delta);
2884 ret:
2885     if (se)
2886         *se = (char *)s;
2887     return sign ? -dval(rv) : dval(rv);
2888 }
2889 
2890 static int
2891 quorem(Bigint *b, Bigint *S)
2892 {
2893     int n;
2894     ULong *bx, *bxe, q, *sx, *sxe;
2895 #ifdef ULLong
2896     ULLong borrow, carry, y, ys;
2897 #else
2898     ULong borrow, carry, y, ys;
2899 #ifdef Pack_32
2900     ULong si, z, zs;
2901 #endif
2902 #endif
2903 
2904     n = S->wds;
2905 #ifdef DEBUG
2906     /*debug*/ if (b->wds > n)
2907     /*debug*/   Bug("oversize b in quorem");
2908 #endif
2909     if (b->wds < n)
2910         return 0;
2911     sx = S->x;
2912     sxe = sx + --n;
2913     bx = b->x;
2914     bxe = bx + n;
2915     q = *bxe / (*sxe + 1);  /* ensure q <= true quotient */
2916 #ifdef DEBUG
2917     /*debug*/ if (q > 9)
2918     /*debug*/   Bug("oversized quotient in quorem");
2919 #endif
2920     if (q) {
2921         borrow = 0;
2922         carry = 0;
2923         do {
2924 #ifdef ULLong
2925             ys = *sx++ * (ULLong)q + carry;
2926             carry = ys >> 32;
2927             y = *bx - (ys & FFFFFFFF) - borrow;
2928             borrow = y >> 32 & (ULong)1;
2929             *bx++ = (ULong)(y & FFFFFFFF);
2930 #else
2931 #ifdef Pack_32
2932             si = *sx++;
2933             ys = (si & 0xffff) * q + carry;
2934             zs = (si >> 16) * q + (ys >> 16);
2935             carry = zs >> 16;
2936             y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
2937             borrow = (y & 0x10000) >> 16;
2938             z = (*bx >> 16) - (zs & 0xffff) - borrow;
2939             borrow = (z & 0x10000) >> 16;
2940             Storeinc(bx, z, y);
2941 #else
2942             ys = *sx++ * q + carry;
2943             carry = ys >> 16;
2944             y = *bx - (ys & 0xffff) - borrow;
2945             borrow = (y & 0x10000) >> 16;
2946             *bx++ = y & 0xffff;
2947 #endif
2948 #endif
2949         } while (sx <= sxe);
2950         if (!*bxe) {
2951             bx = b->x;
2952             while (--bxe > bx && !*bxe)
2953                 --n;
2954             b->wds = n;
2955         }
2956     }
2957     if (cmp(b, S) >= 0) {
2958         q++;
2959         borrow = 0;
2960         carry = 0;
2961         bx = b->x;
2962         sx = S->x;
2963         do {
2964 #ifdef ULLong
2965             ys = *sx++ + carry;
2966             carry = ys >> 32;
2967             y = *bx - (ys & FFFFFFFF) - borrow;
2968             borrow = y >> 32 & (ULong)1;
2969             *bx++ = (ULong)(y & FFFFFFFF);
2970 #else
2971 #ifdef Pack_32
2972             si = *sx++;
2973             ys = (si & 0xffff) + carry;
2974             zs = (si >> 16) + (ys >> 16);
2975             carry = zs >> 16;
2976             y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
2977             borrow = (y & 0x10000) >> 16;
2978             z = (*bx >> 16) - (zs & 0xffff) - borrow;
2979             borrow = (z & 0x10000) >> 16;
2980             Storeinc(bx, z, y);
2981 #else
2982             ys = *sx++ + carry;
2983             carry = ys >> 16;
2984             y = *bx - (ys & 0xffff) - borrow;
2985             borrow = (y & 0x10000) >> 16;
2986             *bx++ = y & 0xffff;
2987 #endif
2988 #endif
2989         } while (sx <= sxe);
2990         bx = b->x;
2991         bxe = bx + n;
2992         if (!*bxe) {
2993             while (--bxe > bx && !*bxe)
2994                 --n;
2995             b->wds = n;
2996         }
2997     }
2998     return q;
2999 }
3000 
3001 #ifndef MULTIPLE_THREADS
3002 static char *dtoa_result;
3003 #endif
3004 
3005 #ifndef MULTIPLE_THREADS
3006 static char *
3007 rv_alloc(int i)
3008 {
3009     return dtoa_result = xmalloc(i);
3010 }
3011 #else
3012 #define rv_alloc(i) xmalloc(i)
3013 #endif
3014 
3015 static char *
3016 nrv_alloc(const char *s, char **rve, size_t n)
3017 {
3018     char *rv, *t;
3019 
3020     t = rv = rv_alloc(n);
3021     while ((*t = *s++) != 0) t++;
3022     if (rve)
3023         *rve = t;
3024     return rv;
3025 }
3026 
3027 #define rv_strdup(s, rve) nrv_alloc((s), (rve), strlen(s)+1)
3028 
3029 #ifndef MULTIPLE_THREADS
3030 /* freedtoa(s) must be used to free values s returned by dtoa
3031  * when MULTIPLE_THREADS is #defined.  It should be used in all cases,
3032  * but for consistency with earlier versions of dtoa, it is optional
3033  * when MULTIPLE_THREADS is not defined.
3034  */
3035 
3036 static void
3037 freedtoa(char *s)
3038 {
3039     xfree(s);
3040 }
3041 #endif
3042 
3043 static const char INFSTR[] = "Infinity";
3044 static const char NANSTR[] = "NaN";
3045 static const char ZEROSTR[] = "0";
3046 
3047 /* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
3048  *
3049  * Inspired by "How to Print Floating-Point Numbers Accurately" by
3050  * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 112-126].
3051  *
3052  * Modifications:
3053  *  1. Rather than iterating, we use a simple numeric overestimate
3054  *     to determine k = floor(log10(d)).  We scale relevant
3055  *     quantities using O(log2(k)) rather than O(k) multiplications.
3056  *  2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
3057  *     try to generate digits strictly left to right.  Instead, we
3058  *     compute with fewer bits and propagate the carry if necessary
3059  *     when rounding the final digit up.  This is often faster.
3060  *  3. Under the assumption that input will be rounded nearest,
3061  *     mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
3062  *     That is, we allow equality in stopping tests when the
3063  *     round-nearest rule will give the same floating-point value
3064  *     as would satisfaction of the stopping test with strict
3065  *     inequality.
3066  *  4. We remove common factors of powers of 2 from relevant
3067  *     quantities.
3068  *  5. When converting floating-point integers less than 1e16,
3069  *     we use floating-point arithmetic rather than resorting
3070  *     to multiple-precision integers.
3071  *  6. When asked to produce fewer than 15 digits, we first try
3072  *     to get by with floating-point arithmetic; we resort to
3073  *     multiple-precision integer arithmetic only if we cannot
3074  *     guarantee that the floating-point calculation has given
3075  *     the correctly rounded result.  For k requested digits and
3076  *     "uniformly" distributed input, the probability is
3077  *     something like 10^(k-15) that we must resort to the Long
3078  *     calculation.
3079  */
3080 
3081 char *
3082 ruby_dtoa(double d_, int mode, int ndigits, int *decpt, int *sign, char **rve)
3083 {
3084  /* Arguments ndigits, decpt, sign are similar to those
3085     of ecvt and fcvt; trailing zeros are suppressed from
3086     the returned string.  If not null, *rve is set to point
3087     to the end of the return value.  If d is +-Infinity or NaN,
3088     then *decpt is set to 9999.
3089 
3090     mode:
3091         0 ==> shortest string that yields d when read in
3092             and rounded to nearest.
3093         1 ==> like 0, but with Steele & White stopping rule;
3094             e.g. with IEEE P754 arithmetic , mode 0 gives
3095             1e23 whereas mode 1 gives 9.999999999999999e22.
3096         2 ==> max(1,ndigits) significant digits.  This gives a
3097             return value similar to that of ecvt, except
3098             that trailing zeros are suppressed.
3099         3 ==> through ndigits past the decimal point.  This
3100             gives a return value similar to that from fcvt,
3101             except that trailing zeros are suppressed, and
3102             ndigits can be negative.
3103         4,5 ==> similar to 2 and 3, respectively, but (in
3104             round-nearest mode) with the tests of mode 0 to
3105             possibly return a shorter string that rounds to d.
3106             With IEEE arithmetic and compilation with
3107             -DHonor_FLT_ROUNDS, modes 4 and 5 behave the same
3108             as modes 2 and 3 when FLT_ROUNDS != 1.
3109         6-9 ==> Debugging modes similar to mode - 4:  don't try
3110             fast floating-point estimate (if applicable).
3111 
3112         Values of mode other than 0-9 are treated as mode 0.
3113 
3114         Sufficient space is allocated to the return value
3115         to hold the suppressed trailing zeros.
3116     */
3117 
3118     int bbits, b2, b5, be, dig, i, ieps, ilim, ilim0, ilim1,
3119         j, j1, k, k0, k_check, leftright, m2, m5, s2, s5,
3120         spec_case, try_quick;
3121     Long L;
3122 #ifndef Sudden_Underflow
3123     int denorm;
3124     ULong x;
3125 #endif
3126     Bigint *b, *b1, *delta, *mlo = 0, *mhi = 0, *S;
3127     double ds;
3128     double_u d, d2, eps;
3129     char *s, *s0;
3130 #ifdef Honor_FLT_ROUNDS
3131     int rounding;
3132 #endif
3133 #ifdef SET_INEXACT
3134     int inexact, oldinexact;
3135 #endif
3136 
3137     dval(d) = d_;
3138 
3139 #ifndef MULTIPLE_THREADS
3140     if (dtoa_result) {
3141         freedtoa(dtoa_result);
3142         dtoa_result = 0;
3143     }
3144 #endif
3145 
3146     if (word0(d) & Sign_bit) {
3147         /* set sign for everything, including 0's and NaNs */
3148         *sign = 1;
3149         word0(d) &= ~Sign_bit;  /* clear sign bit */
3150     }
3151     else
3152         *sign = 0;
3153 
3154 #if defined(IEEE_Arith) + defined(VAX)
3155 #ifdef IEEE_Arith
3156     if ((word0(d) & Exp_mask) == Exp_mask)
3157 #else
3158     if (word0(d)  == 0x8000)
3159 #endif
3160     {
3161         /* Infinity or NaN */
3162         *decpt = 9999;
3163 #ifdef IEEE_Arith
3164         if (!word1(d) && !(word0(d) & 0xfffff))
3165             return rv_strdup(INFSTR, rve);
3166 #endif
3167         return rv_strdup(NANSTR, rve);
3168     }
3169 #endif
3170 #ifdef IBM
3171     dval(d) += 0; /* normalize */
3172 #endif
3173     if (!dval(d)) {
3174         *decpt = 1;
3175         return rv_strdup(ZEROSTR, rve);
3176     }
3177 
3178 #ifdef SET_INEXACT
3179     try_quick = oldinexact = get_inexact();
3180     inexact = 1;
3181 #endif
3182 #ifdef Honor_FLT_ROUNDS
3183     if ((rounding = Flt_Rounds) >= 2) {
3184         if (*sign)
3185             rounding = rounding == 2 ? 0 : 2;
3186         else
3187             if (rounding != 2)
3188                 rounding = 0;
3189     }
3190 #endif
3191 
3192     b = d2b(dval(d), &be, &bbits);
3193 #ifdef Sudden_Underflow
3194     i = (int)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1));
3195 #else
3196     if ((i = (int)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1))) != 0) {
3197 #endif
3198         dval(d2) = dval(d);
3199         word0(d2) &= Frac_mask1;
3200         word0(d2) |= Exp_11;
3201 #ifdef IBM
3202         if (j = 11 - hi0bits(word0(d2) & Frac_mask))
3203             dval(d2) /= 1 << j;
3204 #endif
3205 
3206         /* log(x)   ~=~ log(1.5) + (x-1.5)/1.5
3207          * log10(x)  =  log(x) / log(10)
3208          *      ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
3209          * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2)
3210          *
3211          * This suggests computing an approximation k to log10(d) by
3212          *
3213          * k = (i - Bias)*0.301029995663981
3214          *  + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
3215          *
3216          * We want k to be too large rather than too small.
3217          * The error in the first-order Taylor series approximation
3218          * is in our favor, so we just round up the constant enough
3219          * to compensate for any error in the multiplication of
3220          * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
3221          * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
3222          * adding 1e-13 to the constant term more than suffices.
3223          * Hence we adjust the constant term to 0.1760912590558.
3224          * (We could get a more accurate k by invoking log10,
3225          *  but this is probably not worthwhile.)
3226          */
3227 
3228         i -= Bias;
3229 #ifdef IBM
3230         i <<= 2;
3231         i += j;
3232 #endif
3233 #ifndef Sudden_Underflow
3234         denorm = 0;
3235     }
3236     else {
3237         /* d is denormalized */
3238 
3239         i = bbits + be + (Bias + (P-1) - 1);
3240         x = i > 32  ? word0(d) << (64 - i) | word1(d) >> (i - 32)
3241             : word1(d) << (32 - i);
3242         dval(d2) = x;
3243         word0(d2) -= 31*Exp_msk1; /* adjust exponent */
3244         i -= (Bias + (P-1) - 1) + 1;
3245         denorm = 1;
3246     }
3247 #endif
3248     ds = (dval(d2)-1.5)*0.289529654602168 + 0.1760912590558 + i*0.301029995663981;
3249     k = (int)ds;
3250     if (ds < 0. && ds != k)
3251         k--;    /* want k = floor(ds) */
3252     k_check = 1;
3253     if (k >= 0 && k <= Ten_pmax) {
3254         if (dval(d) < tens[k])
3255             k--;
3256         k_check = 0;
3257     }
3258     j = bbits - i - 1;
3259     if (j >= 0) {
3260         b2 = 0;
3261         s2 = j;
3262     }
3263     else {
3264         b2 = -j;
3265         s2 = 0;
3266     }
3267     if (k >= 0) {
3268         b5 = 0;
3269         s5 = k;
3270         s2 += k;
3271     }
3272     else {
3273         b2 -= k;
3274         b5 = -k;
3275         s5 = 0;
3276     }
3277     if (mode < 0 || mode > 9)
3278         mode = 0;
3279 
3280 #ifndef SET_INEXACT
3281 #ifdef Check_FLT_ROUNDS
3282     try_quick = Rounding == 1;
3283 #else
3284     try_quick = 1;
3285 #endif
3286 #endif /*SET_INEXACT*/
3287 
3288     if (mode > 5) {
3289         mode -= 4;
3290         try_quick = 0;
3291     }
3292     leftright = 1;
3293     ilim = ilim1 = -1;
3294     switch (mode) {
3295       case 0:
3296       case 1:
3297         i = 18;
3298         ndigits = 0;
3299         break;
3300       case 2:
3301         leftright = 0;
3302         /* no break */
3303       case 4:
3304         if (ndigits <= 0)
3305             ndigits = 1;
3306         ilim = ilim1 = i = ndigits;
3307         break;
3308       case 3:
3309         leftright = 0;
3310         /* no break */
3311       case 5:
3312         i = ndigits + k + 1;
3313         ilim = i;
3314         ilim1 = i - 1;
3315         if (i <= 0)
3316             i = 1;
3317     }
3318     s = s0 = rv_alloc(i+1);
3319 
3320 #ifdef Honor_FLT_ROUNDS
3321     if (mode > 1 && rounding != 1)
3322         leftright = 0;
3323 #endif
3324 
3325     if (ilim >= 0 && ilim <= Quick_max && try_quick) {
3326 
3327         /* Try to get by with floating-point arithmetic. */
3328 
3329         i = 0;
3330         dval(d2) = dval(d);
3331         k0 = k;
3332         ilim0 = ilim;
3333         ieps = 2; /* conservative */
3334         if (k > 0) {
3335             ds = tens[k&0xf];
3336             j = k >> 4;
3337             if (j & Bletch) {
3338                 /* prevent overflows */
3339                 j &= Bletch - 1;
3340                 dval(d) /= bigtens[n_bigtens-1];
3341                 ieps++;
3342             }
3343             for (; j; j >>= 1, i++)
3344                 if (j & 1) {
3345                     ieps++;
3346                     ds *= bigtens[i];
3347                 }
3348             dval(d) /= ds;
3349         }
3350         else if ((j1 = -k) != 0) {
3351             dval(d) *= tens[j1 & 0xf];
3352             for (j = j1 >> 4; j; j >>= 1, i++)
3353                 if (j & 1) {
3354                     ieps++;
3355                     dval(d) *= bigtens[i];
3356                 }
3357         }
3358         if (k_check && dval(d) < 1. && ilim > 0) {
3359             if (ilim1 <= 0)
3360                 goto fast_failed;
3361             ilim = ilim1;
3362             k--;
3363             dval(d) *= 10.;
3364             ieps++;
3365         }
3366         dval(eps) = ieps*dval(d) + 7.;
3367         word0(eps) -= (P-1)*Exp_msk1;
3368         if (ilim == 0) {
3369             S = mhi = 0;
3370             dval(d) -= 5.;
3371             if (dval(d) > dval(eps))
3372                 goto one_digit;
3373             if (dval(d) < -dval(eps))
3374                 goto no_digits;
3375             goto fast_failed;
3376         }
3377 #ifndef No_leftright
3378         if (leftright) {
3379             /* Use Steele & White method of only
3380              * generating digits needed.
3381              */
3382             dval(eps) = 0.5/tens[ilim-1] - dval(eps);
3383             for (i = 0;;) {
3384                 L = (int)dval(d);
3385                 dval(d) -= L;
3386                 *s++ = '0' + (int)L;
3387                 if (dval(d) < dval(eps))
3388                     goto ret1;
3389                 if (1. - dval(d) < dval(eps))
3390                     goto bump_up;
3391                 if (++i >= ilim)
3392                     break;
3393                 dval(eps) *= 10.;
3394                 dval(d) *= 10.;
3395             }
3396         }
3397         else {
3398 #endif
3399             /* Generate ilim digits, then fix them up. */
3400             dval(eps) *= tens[ilim-1];
3401             for (i = 1;; i++, dval(d) *= 10.) {
3402                 L = (Long)(dval(d));
3403                 if (!(dval(d) -= L))
3404                     ilim = i;
3405                 *s++ = '0' + (int)L;
3406                 if (i == ilim) {
3407                     if (dval(d) > 0.5 + dval(eps))
3408                         goto bump_up;
3409                     else if (dval(d) < 0.5 - dval(eps)) {
3410                         while (*--s == '0') ;
3411                         s++;
3412                         goto ret1;
3413                     }
3414                     break;
3415                 }
3416             }
3417 #ifndef No_leftright
3418         }
3419 #endif
3420 fast_failed:
3421         s = s0;
3422         dval(d) = dval(d2);
3423         k = k0;
3424         ilim = ilim0;
3425     }
3426 
3427     /* Do we have a "small" integer? */
3428 
3429     if (be >= 0 && k <= Int_max) {
3430         /* Yes. */
3431         ds = tens[k];
3432         if (ndigits < 0 && ilim <= 0) {
3433             S = mhi = 0;
3434             if (ilim < 0 || dval(d) <= 5*ds)
3435                 goto no_digits;
3436             goto one_digit;
3437         }
3438         for (i = 1;; i++, dval(d) *= 10.) {
3439             L = (Long)(dval(d) / ds);
3440             dval(d) -= L*ds;
3441 #ifdef Check_FLT_ROUNDS
3442             /* If FLT_ROUNDS == 2, L will usually be high by 1 */
3443             if (dval(d) < 0) {
3444                 L--;
3445                 dval(d) += ds;
3446             }
3447 #endif
3448             *s++ = '0' + (int)L;
3449             if (!dval(d)) {
3450 #ifdef SET_INEXACT
3451                 inexact = 0;
3452 #endif
3453                 break;
3454             }
3455             if (i == ilim) {
3456 #ifdef Honor_FLT_ROUNDS
3457                 if (mode > 1)
3458                 switch (rounding) {
3459                   case 0: goto ret1;
3460                   case 2: goto bump_up;
3461                 }
3462 #endif
3463                 dval(d) += dval(d);
3464                 if (dval(d) > ds || (dval(d) == ds && (L & 1))) {
3465 bump_up:
3466                     while (*--s == '9')
3467                         if (s == s0) {
3468                             k++;
3469                             *s = '0';
3470                             break;
3471                         }
3472                     ++*s++;
3473                 }
3474                 break;
3475             }
3476         }
3477         goto ret1;
3478     }
3479 
3480     m2 = b2;
3481     m5 = b5;
3482     if (leftright) {
3483         i =
3484 #ifndef Sudden_Underflow
3485             denorm ? be + (Bias + (P-1) - 1 + 1) :
3486 #endif
3487 #ifdef IBM
3488             1 + 4*P - 3 - bbits + ((bbits + be - 1) & 3);
3489 #else
3490             1 + P - bbits;
3491 #endif
3492         b2 += i;
3493         s2 += i;
3494         mhi = i2b(1);
3495     }
3496     if (m2 > 0 && s2 > 0) {
3497         i = m2 < s2 ? m2 : s2;
3498         b2 -= i;
3499         m2 -= i;
3500         s2 -= i;
3501     }
3502     if (b5 > 0) {
3503         if (leftright) {
3504             if (m5 > 0) {
3505                 mhi = pow5mult(mhi, m5);
3506                 b1 = mult(mhi, b);
3507                 Bfree(b);
3508                 b = b1;
3509             }
3510             if ((j = b5 - m5) != 0)
3511                 b = pow5mult(b, j);
3512         }
3513         else
3514             b = pow5mult(b, b5);
3515     }
3516     S = i2b(1);
3517     if (s5 > 0)
3518         S = pow5mult(S, s5);
3519 
3520     /* Check for special case that d is a normalized power of 2. */
3521 
3522     spec_case = 0;
3523     if ((mode < 2 || leftright)
3524 #ifdef Honor_FLT_ROUNDS
3525             && rounding == 1
3526 #endif
3527     ) {
3528         if (!word1(d) && !(word0(d) & Bndry_mask)
3529 #ifndef Sudden_Underflow
3530             && word0(d) & (Exp_mask & ~Exp_msk1)
3531 #endif
3532         ) {
3533             /* The special case */
3534             b2 += Log2P;
3535             s2 += Log2P;
3536             spec_case = 1;
3537         }
3538     }
3539 
3540     /* Arrange for convenient computation of quotients:
3541      * shift left if necessary so divisor has 4 leading 0 bits.
3542      *
3543      * Perhaps we should just compute leading 28 bits of S once
3544      * and for all and pass them and a shift to quorem, so it
3545      * can do shifts and ors to compute the numerator for q.
3546      */
3547 #ifdef Pack_32
3548     if ((i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0x1f) != 0)
3549         i = 32 - i;
3550 #else
3551     if ((i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0xf) != 0)
3552         i = 16 - i;
3553 #endif
3554     if (i > 4) {
3555         i -= 4;
3556         b2 += i;
3557         m2 += i;
3558         s2 += i;
3559     }
3560     else if (i < 4) {
3561         i += 28;
3562         b2 += i;
3563         m2 += i;
3564         s2 += i;
3565     }
3566     if (b2 > 0)
3567         b = lshift(b, b2);
3568     if (s2 > 0)
3569         S = lshift(S, s2);
3570     if (k_check) {
3571         if (cmp(b,S) < 0) {
3572             k--;
3573             b = multadd(b, 10, 0);  /* we botched the k estimate */
3574             if (leftright)
3575                 mhi = multadd(mhi, 10, 0);
3576             ilim = ilim1;
3577         }
3578     }
3579     if (ilim <= 0 && (mode == 3 || mode == 5)) {
3580         if (ilim < 0 || cmp(b,S = multadd(S,5,0)) <= 0) {
3581             /* no digits, fcvt style */
3582 no_digits:
3583             k = -1 - ndigits;
3584             goto ret;
3585         }
3586 one_digit:
3587         *s++ = '1';
3588         k++;
3589         goto ret;
3590     }
3591     if (leftright) {
3592         if (m2 > 0)
3593             mhi = lshift(mhi, m2);
3594 
3595         /* Compute mlo -- check for special case
3596          * that d is a normalized power of 2.
3597          */
3598 
3599         mlo = mhi;
3600         if (spec_case) {
3601             mhi = Balloc(mhi->k);
3602             Bcopy(mhi, mlo);
3603             mhi = lshift(mhi, Log2P);
3604         }
3605 
3606         for (i = 1;;i++) {
3607             dig = quorem(b,S) + '0';
3608             /* Do we yet have the shortest decimal string
3609              * that will round to d?
3610              */
3611             j = cmp(b, mlo);
3612             delta = diff(S, mhi);
3613             j1 = delta->sign ? 1 : cmp(b, delta);
3614             Bfree(delta);
3615 #ifndef ROUND_BIASED
3616             if (j1 == 0 && mode != 1 && !(word1(d) & 1)
3617 #ifdef Honor_FLT_ROUNDS
3618                 && rounding >= 1
3619 #endif
3620             ) {
3621                 if (dig == '9')
3622                     goto round_9_up;
3623                 if (j > 0)
3624                     dig++;
3625 #ifdef SET_INEXACT
3626                 else if (!b->x[0] && b->wds <= 1)
3627                     inexact = 0;
3628 #endif
3629                 *s++ = dig;
3630                 goto ret;
3631             }
3632 #endif
3633             if (j < 0 || (j == 0 && mode != 1
3634 #ifndef ROUND_BIASED
3635                 && !(word1(d) & 1)
3636 #endif
3637             )) {
3638                 if (!b->x[0] && b->wds <= 1) {
3639 #ifdef SET_INEXACT
3640                     inexact = 0;
3641 #endif
3642                     goto accept_dig;
3643                 }
3644 #ifdef Honor_FLT_ROUNDS
3645                 if (mode > 1)
3646                     switch (rounding) {
3647                       case 0: goto accept_dig;
3648                       case 2: goto keep_dig;
3649                     }
3650 #endif /*Honor_FLT_ROUNDS*/
3651                 if (j1 > 0) {
3652                     b = lshift(b, 1);
3653                     j1 = cmp(b, S);
3654                     if ((j1 > 0 || (j1 == 0 && (dig & 1))) && dig++ == '9')
3655                         goto round_9_up;
3656                 }
3657 accept_dig:
3658                 *s++ = dig;
3659                 goto ret;
3660             }
3661             if (j1 > 0) {
3662 #ifdef Honor_FLT_ROUNDS
3663                 if (!rounding)
3664                     goto accept_dig;
3665 #endif
3666                 if (dig == '9') { /* possible if i == 1 */
3667 round_9_up:
3668                     *s++ = '9';
3669                     goto roundoff;
3670                 }
3671                 *s++ = dig + 1;
3672                 goto ret;
3673             }
3674 #ifdef Honor_FLT_ROUNDS
3675 keep_dig:
3676 #endif
3677             *s++ = dig;
3678             if (i == ilim)
3679                 break;
3680             b = multadd(b, 10, 0);
3681             if (mlo == mhi)
3682                 mlo = mhi = multadd(mhi, 10, 0);
3683             else {
3684                 mlo = multadd(mlo, 10, 0);
3685                 mhi = multadd(mhi, 10, 0);
3686             }
3687         }
3688     }
3689     else
3690         for (i = 1;; i++) {
3691             *s++ = dig = quorem(b,S) + '0';
3692             if (!b->x[0] && b->wds <= 1) {
3693 #ifdef SET_INEXACT
3694                 inexact = 0;
3695 #endif
3696                 goto ret;
3697             }
3698             if (i >= ilim)
3699                 break;
3700             b = multadd(b, 10, 0);
3701         }
3702 
3703     /* Round off last digit */
3704 
3705 #ifdef Honor_FLT_ROUNDS
3706     switch (rounding) {
3707       case 0: goto trimzeros;
3708       case 2: goto roundoff;
3709     }
3710 #endif
3711     b = lshift(b, 1);
3712     j = cmp(b, S);
3713     if (j > 0 || (j == 0 && (dig & 1))) {
3714  roundoff:
3715         while (*--s == '9')
3716             if (s == s0) {
3717                 k++;
3718                 *s++ = '1';
3719                 goto ret;
3720             }
3721         ++*s++;
3722     }
3723     else {
3724         while (*--s == '0') ;
3725         s++;
3726     }
3727 ret:
3728     Bfree(S);
3729     if (mhi) {
3730         if (mlo && mlo != mhi)
3731             Bfree(mlo);
3732         Bfree(mhi);
3733     }
3734 ret1:
3735 #ifdef SET_INEXACT
3736     if (inexact) {
3737         if (!oldinexact) {
3738             word0(d) = Exp_1 + (70 << Exp_shift);
3739             word1(d) = 0;
3740             dval(d) += 1.;
3741         }
3742     }
3743     else if (!oldinexact)
3744         clear_inexact();
3745 #endif
3746     Bfree(b);
3747     *s = 0;
3748     *decpt = k + 1;
3749     if (rve)
3750         *rve = s;
3751     return s0;
3752 }
3753 
3754 void
3755 ruby_each_words(const char *str, void (*func)(const char*, int, void*), void *arg)
3756 {
3757     const char *end;
3758     int len;
3759 
3760     if (!str) return;
3761     for (; *str; str = end) {
3762         while (ISSPACE(*str) || *str == ',') str++;
3763         if (!*str) break;
3764         end = str;
3765         while (*end && !ISSPACE(*end) && *end != ',') end++;
3766         len = (int)(end - str); /* assume no string exceeds INT_MAX */
3767         (*func)(str, len, arg);
3768     }
3769 }
3770 
3771 /*-
3772  * Copyright (c) 2004-2008 David Schultz <das@FreeBSD.ORG>
3773  * All rights reserved.
3774  *
3775  * Redistribution and use in source and binary forms, with or without
3776  * modification, are permitted provided that the following conditions
3777  * are met:
3778  * 1. Redistributions of source code must retain the above copyright
3779  *    notice, this list of conditions and the following disclaimer.
3780  * 2. Redistributions in binary form must reproduce the above copyright
3781  *    notice, this list of conditions and the following disclaimer in the
3782  *    documentation and/or other materials provided with the distribution.
3783  *
3784  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
3785  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3786  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3787  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
3788  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3789  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3790  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3791  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3792  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3793  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3794  * SUCH DAMAGE.
3795  */
3796 
3797 #define DBL_MANH_SIZE   20
3798 #define DBL_MANL_SIZE   32
3799 #define DBL_ADJ (DBL_MAX_EXP - 2)
3800 #define SIGFIGS ((DBL_MANT_DIG + 3) / 4 + 1)
3801 #define dexp_get(u) ((int)(word0(u) >> Exp_shift) & ~Exp_msk1)
3802 #define dexp_set(u,v) (word0(u) = (((int)(word0(u)) & ~Exp_mask) | ((v) << Exp_shift)))
3803 #define dmanh_get(u) ((uint32_t)(word0(u) & Frac_mask))
3804 #define dmanl_get(u) ((uint32_t)word1(u))
3805 
3806 
3807 /*
3808  * This procedure converts a double-precision number in IEEE format
3809  * into a string of hexadecimal digits and an exponent of 2.  Its
3810  * behavior is bug-for-bug compatible with dtoa() in mode 2, with the
3811  * following exceptions:
3812  *
3813  * - An ndigits < 0 causes it to use as many digits as necessary to
3814  *   represent the number exactly.
3815  * - The additional xdigs argument should point to either the string
3816  *   "0123456789ABCDEF" or the string "0123456789abcdef", depending on
3817  *   which case is desired.
3818  * - This routine does not repeat dtoa's mistake of setting decpt
3819  *   to 9999 in the case of an infinity or NaN.  INT_MAX is used
3820  *   for this purpose instead.
3821  *
3822  * Note that the C99 standard does not specify what the leading digit
3823  * should be for non-zero numbers.  For instance, 0x1.3p3 is the same
3824  * as 0x2.6p2 is the same as 0x4.cp3.  This implementation always makes
3825  * the leading digit a 1. This ensures that the exponent printed is the
3826  * actual base-2 exponent, i.e., ilogb(d).
3827  *
3828  * Inputs:      d, xdigs, ndigits
3829  * Outputs:     decpt, sign, rve
3830  */
3831 char *
3832 ruby_hdtoa(double d, const char *xdigs, int ndigits, int *decpt, int *sign,
3833     char **rve)
3834 {
3835         U u;
3836         char *s, *s0;
3837         int bufsize;
3838         uint32_t manh, manl;
3839 
3840         u.d = d;
3841         if (word0(u) & Sign_bit) {
3842             /* set sign for everything, including 0's and NaNs */
3843             *sign = 1;
3844             word0(u) &= ~Sign_bit;  /* clear sign bit */
3845         }
3846         else
3847             *sign = 0;
3848 
3849         if (isinf(d)) { /* FP_INFINITE */
3850             *decpt = INT_MAX;
3851             return rv_strdup(INFSTR, rve);
3852         }
3853         else if (isnan(d)) { /* FP_NAN */
3854             *decpt = INT_MAX;
3855             return rv_strdup(NANSTR, rve);
3856         }
3857         else if (d == 0.0) { /* FP_ZERO */
3858             *decpt = 1;
3859             return rv_strdup(ZEROSTR, rve);
3860         }
3861         else if (dexp_get(u)) { /* FP_NORMAL */
3862             *decpt = dexp_get(u) - DBL_ADJ;
3863         }
3864         else { /* FP_SUBNORMAL */
3865             u.d *= 5.363123171977039e+154 /* 0x1p514 */;
3866             *decpt = dexp_get(u) - (514 + DBL_ADJ);
3867         }
3868 
3869         if (ndigits == 0)               /* dtoa() compatibility */
3870                 ndigits = 1;
3871 
3872         /*
3873          * If ndigits < 0, we are expected to auto-size, so we allocate
3874          * enough space for all the digits.
3875          */
3876         bufsize = (ndigits > 0) ? ndigits : SIGFIGS;
3877         s0 = rv_alloc(bufsize+1);
3878 
3879         /* Round to the desired number of digits. */
3880         if (SIGFIGS > ndigits && ndigits > 0) {
3881                 float redux = 1.0f;
3882                 int offset = 4 * ndigits + DBL_MAX_EXP - 4 - DBL_MANT_DIG;
3883                 dexp_set(u, offset);
3884                 u.d += redux;
3885                 u.d -= redux;
3886                 *decpt += dexp_get(u) - offset;
3887         }
3888 
3889         manh = dmanh_get(u);
3890         manl = dmanl_get(u);
3891         *s0 = '1';
3892         for (s = s0 + 1; s < s0 + bufsize; s++) {
3893                 *s = xdigs[(manh >> (DBL_MANH_SIZE - 4)) & 0xf];
3894                 manh = (manh << 4) | (manl >> (DBL_MANL_SIZE - 4));
3895                 manl <<= 4;
3896         }
3897 
3898         /* If ndigits < 0, we are expected to auto-size the precision. */
3899         if (ndigits < 0) {
3900                 for (ndigits = SIGFIGS; s0[ndigits - 1] == '0'; ndigits--)
3901                         ;
3902         }
3903 
3904         s = s0 + ndigits;
3905         *s = '\0';
3906         if (rve != NULL)
3907                 *rve = s;
3908         return (s0);
3909 }
3910 
3911 #ifdef __cplusplus
3912 #if 0
3913 { /* satisfy cc-mode */
3914 #endif
3915 }
3916 #endif