* gc.c (set_heaps_increment): fix memory allocation strategy by
[ruby-svn.git] / util.c
blobfc8874c942250a26bfed778e11682c712f0825bd
1 /**********************************************************************
3 util.c -
5 $Author$
6 created at: Fri Mar 10 17:22:34 JST 1995
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
10 **********************************************************************/
12 #include "ruby/ruby.h"
14 #include <ctype.h>
15 #include <stdio.h>
16 #include <errno.h>
17 #include <math.h>
18 #include <float.h>
20 #ifdef _WIN32
21 #include "missing/file.h"
22 #endif
23 #if defined(__CYGWIN32__)
24 #define _open open
25 #define _close close
26 #define _unlink unlink
27 #define _access access
28 #elif defined(_WIN32)
29 #include <io.h>
30 #endif
32 #include "ruby/util.h"
34 unsigned long
35 ruby_scan_oct(const char *start, int len, int *retlen)
37 register const char *s = start;
38 register unsigned long retval = 0;
40 while (len-- && *s >= '0' && *s <= '7') {
41 retval <<= 3;
42 retval |= *s++ - '0';
44 *retlen = s - start;
45 return retval;
48 unsigned long
49 ruby_scan_hex(const char *start, int len, int *retlen)
51 static char hexdigit[] = "0123456789abcdef0123456789ABCDEF";
52 register const char *s = start;
53 register unsigned long retval = 0;
54 char *tmp;
56 while (len-- && *s && (tmp = strchr(hexdigit, *s))) {
57 retval <<= 4;
58 retval |= (tmp - hexdigit) & 15;
59 s++;
61 *retlen = s - start;
62 return retval;
65 static unsigned long
66 scan_digits(const char *str, int base, size_t *retlen, int *overflow)
68 static signed char table[] = {
69 /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */
70 /*0*/ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
71 /*1*/ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
72 /*2*/ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
73 /*3*/ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1,
74 /*4*/ -1,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,
75 /*5*/ 25,26,27,28,29,30,31,32,33,34,35,-1,-1,-1,-1,-1,
76 /*6*/ -1,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,
77 /*7*/ 25,26,27,28,29,30,31,32,33,34,35,-1,-1,-1,-1,-1,
78 /*8*/ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
79 /*9*/ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
80 /*a*/ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
81 /*b*/ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
82 /*c*/ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
83 /*d*/ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
84 /*e*/ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
85 /*f*/ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
88 const char *start = str;
89 unsigned long ret = 0, x;
90 unsigned long mul_overflow = (~(unsigned long)0) / base;
91 int c;
92 *overflow = 0;
94 while ((c = (unsigned char)*str++) != '\0') {
95 int d = table[c];
96 if (d == -1 || base <= d) {
97 *retlen = (str-1) - start;
98 return ret;
100 if (mul_overflow < ret)
101 *overflow = 1;
102 ret *= base;
103 x = ret;
104 ret += d;
105 if (ret < x)
106 *overflow = 1;
108 *retlen = (str-1) - start;
109 return ret;
112 unsigned long
113 ruby_strtoul(const char *str, char **endptr, int base)
115 int c, b, overflow;
116 int sign = 0;
117 size_t len;
118 unsigned long ret;
119 const char *subject_found = str;
121 if (base == 1 || 36 < base) {
122 errno = EINVAL;
123 return 0;
126 while ((c = *str) && ISSPACE(c))
127 str++;
129 if (c == '+') {
130 sign = 1;
131 str++;
133 else if (c == '-') {
134 sign = -1;
135 str++;
138 if (str[0] == '0') {
139 subject_found = str+1;
140 if (base == 0 || base == 16) {
141 if (str[1] == 'x' || str[1] == 'X') {
142 b = 16;
143 str += 2;
145 else {
146 b = base == 0 ? 8 : 16;
147 str++;
150 else {
151 b = base;
152 str++;
155 else {
156 b = base == 0 ? 10 : base;
159 ret = scan_digits(str, b, &len, &overflow);
161 if (0 < len)
162 subject_found = str+len;
164 if (endptr)
165 *endptr = (char*)subject_found;
167 if (overflow) {
168 errno = ERANGE;
169 return ULONG_MAX;
172 if (sign < 0) {
173 ret = -ret;
174 return ret;
176 else {
177 return ret;
181 #include <sys/types.h>
182 #include <sys/stat.h>
183 #ifdef HAVE_UNISTD_H
184 #include <unistd.h>
185 #endif
186 #if defined(HAVE_FCNTL_H)
187 #include <fcntl.h>
188 #endif
190 #ifndef S_ISDIR
191 # define S_ISDIR(m) ((m & S_IFMT) == S_IFDIR)
192 #endif
194 #if defined(MSDOS) || defined(__CYGWIN32__) || defined(_WIN32)
196 * Copyright (c) 1993, Intergraph Corporation
198 * You may distribute under the terms of either the GNU General Public
199 * License or the Artistic License, as specified in the perl README file.
201 * Various Unix compatibility functions and NT specific functions.
203 * Some of this code was derived from the MSDOS port(s) and the OS/2 port.
209 * Suffix appending for in-place editing under MS-DOS and OS/2 (and now NT!).
211 * Here are the rules:
213 * Style 0: Append the suffix exactly as standard perl would do it.
214 * If the filesystem groks it, use it. (HPFS will always
215 * grok it. So will NTFS. FAT will rarely accept it.)
217 * Style 1: The suffix begins with a '.'. The extension is replaced.
218 * If the name matches the original name, use the fallback method.
220 * Style 2: The suffix is a single character, not a '.'. Try to add the
221 * suffix to the following places, using the first one that works.
222 * [1] Append to extension.
223 * [2] Append to filename,
224 * [3] Replace end of extension,
225 * [4] Replace end of filename.
226 * If the name matches the original name, use the fallback method.
228 * Style 3: Any other case: Ignore the suffix completely and use the
229 * fallback method.
231 * Fallback method: Change the extension to ".$$$". If that matches the
232 * original name, then change the extension to ".~~~".
234 * If filename is more than 1000 characters long, we die a horrible
235 * death. Sorry.
237 * The filename restriction is a cheat so that we can use buf[] to store
238 * assorted temporary goo.
240 * Examples, assuming style 0 failed.
242 * suffix = ".bak" (style 1)
243 * foo.bar => foo.bak
244 * foo.bak => foo.$$$ (fallback)
245 * foo.$$$ => foo.~~~ (fallback)
246 * makefile => makefile.bak
248 * suffix = "~" (style 2)
249 * foo.c => foo.c~
250 * foo.c~ => foo.c~~
251 * foo.c~~ => foo~.c~~
252 * foo~.c~~ => foo~~.c~~
253 * foo~~~~~.c~~ => foo~~~~~.$$$ (fallback)
255 * foo.pas => foo~.pas
256 * makefile => makefile.~
257 * longname.fil => longname.fi~
258 * longname.fi~ => longnam~.fi~
259 * longnam~.fi~ => longnam~.$$$
264 static int valid_filename(const char *s);
266 static const char suffix1[] = ".$$$";
267 static const char suffix2[] = ".~~~";
269 #define ext (&buf[1000])
271 #define strEQ(s1,s2) (strcmp(s1,s2) == 0)
273 void
274 ruby_add_suffix(VALUE str, const char *suffix)
276 int baselen;
277 int extlen = strlen(suffix);
278 char *s, *t, *p;
279 long slen;
280 char buf[1024];
282 if (RSTRING_LEN(str) > 1000)
283 rb_fatal("Cannot do inplace edit on long filename (%ld characters)",
284 RSTRING_LEN(str));
286 #if defined(DJGPP) || defined(__CYGWIN32__) || defined(_WIN32)
287 /* Style 0 */
288 slen = RSTRING_LEN(str);
289 rb_str_cat(str, suffix, extlen);
290 #if defined(DJGPP)
291 if (_USE_LFN) return;
292 #else
293 if (valid_filename(RSTRING_PTR(str))) return;
294 #endif
296 /* Fooey, style 0 failed. Fix str before continuing. */
297 rb_str_resize(str, slen);
298 #endif
300 slen = extlen;
301 t = buf; baselen = 0; s = RSTRING_PTR(str);
302 while ((*t = *s) && *s != '.') {
303 baselen++;
304 if (*s == '\\' || *s == '/') baselen = 0;
305 s++; t++;
307 p = t;
309 t = ext; extlen = 0;
310 while ((*t++ = *s++) != 0) extlen++;
311 if (extlen == 0) { ext[0] = '.'; ext[1] = 0; extlen++; }
313 if (*suffix == '.') { /* Style 1 */
314 if (strEQ(ext, suffix)) goto fallback;
315 strcpy(p, suffix);
317 else if (suffix[1] == '\0') { /* Style 2 */
318 if (extlen < 4) {
319 ext[extlen] = *suffix;
320 ext[++extlen] = '\0';
322 else if (baselen < 8) {
323 *p++ = *suffix;
325 else if (ext[3] != *suffix) {
326 ext[3] = *suffix;
328 else if (buf[7] != *suffix) {
329 buf[7] = *suffix;
331 else goto fallback;
332 strcpy(p, ext);
334 else { /* Style 3: Panic */
335 fallback:
336 (void)memcpy(p, strEQ(ext, suffix1) ? suffix2 : suffix1, 5);
338 rb_str_resize(str, strlen(buf));
339 memcpy(RSTRING_PTR(str), buf, RSTRING_LEN(str));
342 #if defined(__CYGWIN32__) || defined(_WIN32)
343 static int
344 valid_filename(const char *s)
346 int fd;
349 // It doesn't exist, so see if we can open it.
352 if ((fd = _open(s, O_CREAT|O_EXCL, 0666)) >= 0) {
353 _close(fd);
354 _unlink(s); /* don't leave it laying around */
355 return 1;
357 else if (errno == EEXIST) {
358 /* if the file exists, then it's a valid filename! */
359 return 1;
361 return 0;
363 #endif
364 #endif
366 #if defined __DJGPP__
368 #include <dpmi.h>
370 static char dbcs_table[256];
373 make_dbcs_table()
375 __dpmi_regs r;
376 struct {
377 unsigned char start;
378 unsigned char end;
379 } vec;
380 int offset;
382 memset(&r, 0, sizeof(r));
383 r.x.ax = 0x6300;
384 __dpmi_int(0x21, &r);
385 offset = r.x.ds * 16 + r.x.si;
387 for (;;) {
388 int i;
389 dosmemget(offset, sizeof vec, &vec);
390 if (!vec.start && !vec.end)
391 break;
392 for (i = vec.start; i <= vec.end; i++)
393 dbcs_table[i] = 1;
394 offset += 2;
399 mblen(const char *s, size_t n)
401 static int need_init = 1;
402 if (need_init) {
403 make_dbcs_table();
404 need_init = 0;
406 if (s) {
407 if (n == 0 || *s == 0)
408 return 0;
409 else if (!s[1])
410 return 1;
411 return dbcs_table[(unsigned char)*s] + 1;
413 else
414 return 1;
417 struct PathList {
418 struct PathList *next;
419 char *path;
422 struct PathInfo {
423 struct PathList *head;
424 int count;
427 static int
428 push_element(const char *path, VALUE vinfo)
430 struct PathList *p;
431 struct PathInfo *info = (struct PathInfo *)vinfo;
433 p = ALLOC(struct PathList);
434 MEMZERO(p, struct PathList, 1);
435 p->path = ruby_strdup(path);
436 p->next = info->head;
437 info->head = p;
438 info->count++;
440 return 0;
443 #include <dirent.h>
444 int __opendir_flags = __OPENDIR_PRESERVE_CASE;
446 char **
447 __crt0_glob_function(char *path)
449 int len = strlen(path);
450 int i;
451 char **rv;
452 char path_buffer[PATH_MAX];
453 char *buf = path_buffer;
454 char *p;
455 struct PathInfo info;
456 struct PathList *plist;
458 if (PATH_MAX <= len)
459 buf = ruby_xmalloc(len + 1);
461 strncpy(buf, path, len);
462 buf[len] = '\0';
464 for (p = buf; *p; p += mblen(p, RUBY_MBCHAR_MAXSIZE))
465 if (*p == '\\')
466 *p = '/';
468 info.count = 0;
469 info.head = 0;
471 ruby_glob(buf, 0, push_element, (VALUE)&info);
473 if (buf != path_buffer)
474 ruby_xfree(buf);
476 if (info.count == 0)
477 return 0;
479 rv = ruby_xmalloc((info.count + 1) * sizeof (char *));
481 plist = info.head;
482 i = 0;
483 while (plist) {
484 struct PathList *cur;
485 rv[i] = plist->path;
486 cur = plist;
487 plist = plist->next;
488 ruby_xfree(cur);
489 i++;
491 rv[i] = 0;
492 return rv;
495 #endif
497 /* mm.c */
499 #define A ((int*)a)
500 #define B ((int*)b)
501 #define C ((int*)c)
502 #define D ((int*)d)
504 #define mmprepare(base, size) do {\
505 if (((long)base & (0x3)) == 0)\
506 if (size >= 16) mmkind = 1;\
507 else mmkind = 0;\
508 else mmkind = -1;\
509 high = (size & (~0xf));\
510 low = (size & 0x0c);\
511 } while (0)\
513 #define mmarg mmkind, size, high, low
515 static void mmswap_(register char *a, register char *b, int mmkind, int size, int high, int low)
517 register int s;
518 if (a == b) return;
519 if (mmkind >= 0) {
520 if (mmkind > 0) {
521 register char *t = a + high;
522 do {
523 s = A[0]; A[0] = B[0]; B[0] = s;
524 s = A[1]; A[1] = B[1]; B[1] = s;
525 s = A[2]; A[2] = B[2]; B[2] = s;
526 s = A[3]; A[3] = B[3]; B[3] = s; a += 16; b += 16;
527 } while (a < t);
529 if (low != 0) { s = A[0]; A[0] = B[0]; B[0] = s;
530 if (low >= 8) { s = A[1]; A[1] = B[1]; B[1] = s;
531 if (low == 12) {s = A[2]; A[2] = B[2]; B[2] = s;}}}
533 else {
534 register char *t = a + size;
535 do {s = *a; *a++ = *b; *b++ = s;} while (a < t);
538 #define mmswap(a,b) mmswap_((a),(b),mmarg)
540 static void mmrot3_(register char *a, register char *b, register char *c, int mmkind, int size, int high, int low)
542 register int s;
543 if (mmkind >= 0) {
544 if (mmkind > 0) {
545 register char *t = a + high;
546 do {
547 s = A[0]; A[0] = B[0]; B[0] = C[0]; C[0] = s;
548 s = A[1]; A[1] = B[1]; B[1] = C[1]; C[1] = s;
549 s = A[2]; A[2] = B[2]; B[2] = C[2]; C[2] = s;
550 s = A[3]; A[3] = B[3]; B[3] = C[3]; C[3] = s; a += 16; b += 16; c += 16;
551 } while (a < t);
553 if (low != 0) { s = A[0]; A[0] = B[0]; B[0] = C[0]; C[0] = s;
554 if (low >= 8) { s = A[1]; A[1] = B[1]; B[1] = C[1]; C[1] = s;
555 if (low == 12) {s = A[2]; A[2] = B[2]; B[2] = C[2]; C[2] = s;}}}
557 else {
558 register char *t = a + size;
559 do {s = *a; *a++ = *b; *b++ = *c; *c++ = s;} while (a < t);
562 #define mmrot3(a,b,c) mmrot3_((a),(b),(c),mmarg)
564 /* qs6.c */
565 /*****************************************************/
566 /* */
567 /* qs6 (Quick sort function) */
568 /* */
569 /* by Tomoyuki Kawamura 1995.4.21 */
570 /* kawamura@tokuyama.ac.jp */
571 /*****************************************************/
573 typedef struct { char *LL, *RR; } stack_node; /* Stack structure for L,l,R,r */
574 #define PUSH(ll,rr) do { top->LL = (ll); top->RR = (rr); ++top; } while (0) /* Push L,l,R,r */
575 #define POP(ll,rr) do { --top; ll = top->LL; rr = top->RR; } while (0) /* Pop L,l,R,r */
577 #define med3(a,b,c) ((*cmp)(a,b,d)<0 ? \
578 ((*cmp)(b,c,d)<0 ? b : ((*cmp)(a,c,d)<0 ? c : a)) : \
579 ((*cmp)(b,c,d)>0 ? b : ((*cmp)(a,c,d)<0 ? a : c)))
581 void
582 ruby_qsort(void* base, const int nel, const int size,
583 int (*cmp)(const void*, const void*, void*), void *d)
585 register char *l, *r, *m; /* l,r:left,right group m:median point */
586 register int t, eq_l, eq_r; /* eq_l: all items in left group are equal to S */
587 char *L = base; /* left end of curren region */
588 char *R = (char*)base + size*(nel-1); /* right end of current region */
589 int chklim = 63; /* threshold of ordering element check */
590 stack_node stack[32], *top = stack; /* 32 is enough for 32bit CPU */
591 int mmkind, high, low;
593 if (nel <= 1) return; /* need not to sort */
594 mmprepare(base, size);
595 goto start;
597 nxt:
598 if (stack == top) return; /* return if stack is empty */
599 POP(L,R);
601 for (;;) {
602 start:
603 if (L + size == R) { /* 2 elements */
604 if ((*cmp)(L,R,d) > 0) mmswap(L,R); goto nxt;
607 l = L; r = R;
608 t = (r - l + size) / size; /* number of elements */
609 m = l + size * (t >> 1); /* calculate median value */
611 if (t >= 60) {
612 register char *m1;
613 register char *m3;
614 if (t >= 200) {
615 t = size*(t>>3); /* number of bytes in splitting 8 */
617 register char *p1 = l + t;
618 register char *p2 = p1 + t;
619 register char *p3 = p2 + t;
620 m1 = med3(p1, p2, p3);
621 p1 = m + t;
622 p2 = p1 + t;
623 p3 = p2 + t;
624 m3 = med3(p1, p2, p3);
627 else {
628 t = size*(t>>2); /* number of bytes in splitting 4 */
629 m1 = l + t;
630 m3 = m + t;
632 m = med3(m1, m, m3);
635 if ((t = (*cmp)(l,m,d)) < 0) { /*3-5-?*/
636 if ((t = (*cmp)(m,r,d)) < 0) { /*3-5-7*/
637 if (chklim && nel >= chklim) { /* check if already ascending order */
638 char *p;
639 chklim = 0;
640 for (p=l; p<r; p+=size) if ((*cmp)(p,p+size,d) > 0) goto fail;
641 goto nxt;
643 fail: goto loopA; /*3-5-7*/
645 if (t > 0) {
646 if ((*cmp)(l,r,d) <= 0) {mmswap(m,r); goto loopA;} /*3-5-4*/
647 mmrot3(r,m,l); goto loopA; /*3-5-2*/
649 goto loopB; /*3-5-5*/
652 if (t > 0) { /*7-5-?*/
653 if ((t = (*cmp)(m,r,d)) > 0) { /*7-5-3*/
654 if (chklim && nel >= chklim) { /* check if already ascending order */
655 char *p;
656 chklim = 0;
657 for (p=l; p<r; p+=size) if ((*cmp)(p,p+size,d) < 0) goto fail2;
658 while (l<r) {mmswap(l,r); l+=size; r-=size;} /* reverse region */
659 goto nxt;
661 fail2: mmswap(l,r); goto loopA; /*7-5-3*/
663 if (t < 0) {
664 if ((*cmp)(l,r,d) <= 0) {mmswap(l,m); goto loopB;} /*7-5-8*/
665 mmrot3(l,m,r); goto loopA; /*7-5-6*/
667 mmswap(l,r); goto loopA; /*7-5-5*/
670 if ((t = (*cmp)(m,r,d)) < 0) {goto loopA;} /*5-5-7*/
671 if (t > 0) {mmswap(l,r); goto loopB;} /*5-5-3*/
673 /* determining splitting type in case 5-5-5 */ /*5-5-5*/
674 for (;;) {
675 if ((l += size) == r) goto nxt; /*5-5-5*/
676 if (l == m) continue;
677 if ((t = (*cmp)(l,m,d)) > 0) {mmswap(l,r); l = L; goto loopA;}/*575-5*/
678 if (t < 0) {mmswap(L,l); l = L; goto loopB;} /*535-5*/
681 loopA: eq_l = 1; eq_r = 1; /* splitting type A */ /* left <= median < right */
682 for (;;) {
683 for (;;) {
684 if ((l += size) == r)
685 {l -= size; if (l != m) mmswap(m,l); l -= size; goto fin;}
686 if (l == m) continue;
687 if ((t = (*cmp)(l,m,d)) > 0) {eq_r = 0; break;}
688 if (t < 0) eq_l = 0;
690 for (;;) {
691 if (l == (r -= size))
692 {l -= size; if (l != m) mmswap(m,l); l -= size; goto fin;}
693 if (r == m) {m = l; break;}
694 if ((t = (*cmp)(r,m,d)) < 0) {eq_l = 0; break;}
695 if (t == 0) break;
697 mmswap(l,r); /* swap left and right */
700 loopB: eq_l = 1; eq_r = 1; /* splitting type B */ /* left < median <= right */
701 for (;;) {
702 for (;;) {
703 if (l == (r -= size))
704 {r += size; if (r != m) mmswap(r,m); r += size; goto fin;}
705 if (r == m) continue;
706 if ((t = (*cmp)(r,m,d)) < 0) {eq_l = 0; break;}
707 if (t > 0) eq_r = 0;
709 for (;;) {
710 if ((l += size) == r)
711 {r += size; if (r != m) mmswap(r,m); r += size; goto fin;}
712 if (l == m) {m = r; break;}
713 if ((t = (*cmp)(l,m,d)) > 0) {eq_r = 0; break;}
714 if (t == 0) break;
716 mmswap(l,r); /* swap left and right */
719 fin:
720 if (eq_l == 0) /* need to sort left side */
721 if (eq_r == 0) /* need to sort right side */
722 if (l-L < R-r) {PUSH(r,R); R = l;} /* sort left side first */
723 else {PUSH(L,l); L = r;} /* sort right side first */
724 else R = l; /* need to sort left side only */
725 else if (eq_r == 0) L = r; /* need to sort right side only */
726 else goto nxt; /* need not to sort both sides */
730 char *
731 ruby_strdup(const char *str)
733 char *tmp;
734 int len = strlen(str) + 1;
736 tmp = xmalloc(len);
737 memcpy(tmp, str, len);
739 return tmp;
742 char *
743 ruby_getcwd(void)
745 #ifdef HAVE_GETCWD
746 int size = 200;
747 char *buf = xmalloc(size);
749 while (!getcwd(buf, size)) {
750 if (errno != ERANGE) {
751 free(buf);
752 rb_sys_fail("getcwd");
754 size *= 2;
755 buf = xrealloc(buf, size);
757 #else
758 # ifndef PATH_MAX
759 # define PATH_MAX 8192
760 # endif
761 char *buf = xmalloc(PATH_MAX+1);
763 if (!getwd(buf)) {
764 free(buf);
765 rb_sys_fail("getwd");
767 #endif
768 return buf;
771 /****************************************************************
773 * The author of this software is David M. Gay.
775 * Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
777 * Permission to use, copy, modify, and distribute this software for any
778 * purpose without fee is hereby granted, provided that this entire notice
779 * is included in all copies of any software which is or includes a copy
780 * or modification of this software and in all copies of the supporting
781 * documentation for such software.
783 * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
784 * WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
785 * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
786 * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
788 ***************************************************************/
790 /* Please send bug reports to David M. Gay (dmg at acm dot org,
791 * with " at " changed at "@" and " dot " changed to "."). */
793 /* On a machine with IEEE extended-precision registers, it is
794 * necessary to specify double-precision (53-bit) rounding precision
795 * before invoking strtod or dtoa. If the machine uses (the equivalent
796 * of) Intel 80x87 arithmetic, the call
797 * _control87(PC_53, MCW_PC);
798 * does this with many compilers. Whether this or another call is
799 * appropriate depends on the compiler; for this to work, it may be
800 * necessary to #include "float.h" or another system-dependent header
801 * file.
804 /* strtod for IEEE-, VAX-, and IBM-arithmetic machines.
806 * This strtod returns a nearest machine number to the input decimal
807 * string (or sets errno to ERANGE). With IEEE arithmetic, ties are
808 * broken by the IEEE round-even rule. Otherwise ties are broken by
809 * biased rounding (add half and chop).
811 * Inspired loosely by William D. Clinger's paper "How to Read Floating
812 * Point Numbers Accurately" [Proc. ACM SIGPLAN '90, pp. 92-101].
814 * Modifications:
816 * 1. We only require IEEE, IBM, or VAX double-precision
817 * arithmetic (not IEEE double-extended).
818 * 2. We get by with floating-point arithmetic in a case that
819 * Clinger missed -- when we're computing d * 10^n
820 * for a small integer d and the integer n is not too
821 * much larger than 22 (the maximum integer k for which
822 * we can represent 10^k exactly), we may be able to
823 * compute (d*10^k) * 10^(e-k) with just one roundoff.
824 * 3. Rather than a bit-at-a-time adjustment of the binary
825 * result in the hard case, we use floating-point
826 * arithmetic to determine the adjustment to within
827 * one bit; only in really hard cases do we need to
828 * compute a second residual.
829 * 4. Because of 3., we don't need a large table of powers of 10
830 * for ten-to-e (just some small tables, e.g. of 10^k
831 * for 0 <= k <= 22).
835 * #define IEEE_LITTLE_ENDIAN for IEEE-arithmetic machines where the least
836 * significant byte has the lowest address.
837 * #define IEEE_BIG_ENDIAN for IEEE-arithmetic machines where the most
838 * significant byte has the lowest address.
839 * #define Long int on machines with 32-bit ints and 64-bit longs.
840 * #define IBM for IBM mainframe-style floating-point arithmetic.
841 * #define VAX for VAX-style floating-point arithmetic (D_floating).
842 * #define No_leftright to omit left-right logic in fast floating-point
843 * computation of dtoa.
844 * #define Honor_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3
845 * and strtod and dtoa should round accordingly.
846 * #define Check_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3
847 * and Honor_FLT_ROUNDS is not #defined.
848 * #define RND_PRODQUOT to use rnd_prod and rnd_quot (assembly routines
849 * that use extended-precision instructions to compute rounded
850 * products and quotients) with IBM.
851 * #define ROUND_BIASED for IEEE-format with biased rounding.
852 * #define Inaccurate_Divide for IEEE-format with correctly rounded
853 * products but inaccurate quotients, e.g., for Intel i860.
854 * #define NO_LONG_LONG on machines that do not have a "long long"
855 * integer type (of >= 64 bits). On such machines, you can
856 * #define Just_16 to store 16 bits per 32-bit Long when doing
857 * high-precision integer arithmetic. Whether this speeds things
858 * up or slows things down depends on the machine and the number
859 * being converted. If long long is available and the name is
860 * something other than "long long", #define Llong to be the name,
861 * and if "unsigned Llong" does not work as an unsigned version of
862 * Llong, #define #ULLong to be the corresponding unsigned type.
863 * #define KR_headers for old-style C function headers.
864 * #define Bad_float_h if your system lacks a float.h or if it does not
865 * define some or all of DBL_DIG, DBL_MAX_10_EXP, DBL_MAX_EXP,
866 * FLT_RADIX, FLT_ROUNDS, and DBL_MAX.
867 * #define MALLOC your_malloc, where your_malloc(n) acts like malloc(n)
868 * if memory is available and otherwise does something you deem
869 * appropriate. If MALLOC is undefined, malloc will be invoked
870 * directly -- and assumed always to succeed.
871 * #define Omit_Private_Memory to omit logic (added Jan. 1998) for making
872 * memory allocations from a private pool of memory when possible.
873 * When used, the private pool is PRIVATE_MEM bytes long: 2304 bytes,
874 * unless #defined to be a different length. This default length
875 * suffices to get rid of MALLOC calls except for unusual cases,
876 * such as decimal-to-binary conversion of a very long string of
877 * digits. The longest string dtoa can return is about 751 bytes
878 * long. For conversions by strtod of strings of 800 digits and
879 * all dtoa conversions in single-threaded executions with 8-byte
880 * pointers, PRIVATE_MEM >= 7400 appears to suffice; with 4-byte
881 * pointers, PRIVATE_MEM >= 7112 appears adequate.
882 * #define INFNAN_CHECK on IEEE systems to cause strtod to check for
883 * Infinity and NaN (case insensitively). On some systems (e.g.,
884 * some HP systems), it may be necessary to #define NAN_WORD0
885 * appropriately -- to the most significant word of a quiet NaN.
886 * (On HP Series 700/800 machines, -DNAN_WORD0=0x7ff40000 works.)
887 * When INFNAN_CHECK is #defined and No_Hex_NaN is not #defined,
888 * strtod also accepts (case insensitively) strings of the form
889 * NaN(x), where x is a string of hexadecimal digits and spaces;
890 * if there is only one string of hexadecimal digits, it is taken
891 * for the 52 fraction bits of the resulting NaN; if there are two
892 * or more strings of hex digits, the first is for the high 20 bits,
893 * the second and subsequent for the low 32 bits, with intervening
894 * white space ignored; but if this results in none of the 52
895 * fraction bits being on (an IEEE Infinity symbol), then NAN_WORD0
896 * and NAN_WORD1 are used instead.
897 * #define MULTIPLE_THREADS if the system offers preemptively scheduled
898 * multiple threads. In this case, you must provide (or suitably
899 * #define) two locks, acquired by ACQUIRE_DTOA_LOCK(n) and freed
900 * by FREE_DTOA_LOCK(n) for n = 0 or 1. (The second lock, accessed
901 * in pow5mult, ensures lazy evaluation of only one copy of high
902 * powers of 5; omitting this lock would introduce a small
903 * probability of wasting memory, but would otherwise be harmless.)
904 * You must also invoke freedtoa(s) to free the value s returned by
905 * dtoa. You may do so whether or not MULTIPLE_THREADS is #defined.
906 * #define NO_IEEE_Scale to disable new (Feb. 1997) logic in strtod that
907 * avoids underflows on inputs whose result does not underflow.
908 * If you #define NO_IEEE_Scale on a machine that uses IEEE-format
909 * floating-point numbers and flushes underflows to zero rather
910 * than implementing gradual underflow, then you must also #define
911 * Sudden_Underflow.
912 * #define YES_ALIAS to permit aliasing certain double values with
913 * arrays of ULongs. This leads to slightly better code with
914 * some compilers and was always used prior to 19990916, but it
915 * is not strictly legal and can cause trouble with aggressively
916 * optimizing compilers (e.g., gcc 2.95.1 under -O2).
917 * #define USE_LOCALE to use the current locale's decimal_point value.
918 * #define SET_INEXACT if IEEE arithmetic is being used and extra
919 * computation should be done to set the inexact flag when the
920 * result is inexact and avoid setting inexact when the result
921 * is exact. In this case, dtoa.c must be compiled in
922 * an environment, perhaps provided by #include "dtoa.c" in a
923 * suitable wrapper, that defines two functions,
924 * int get_inexact(void);
925 * void clear_inexact(void);
926 * such that get_inexact() returns a nonzero value if the
927 * inexact bit is already set, and clear_inexact() sets the
928 * inexact bit to 0. When SET_INEXACT is #defined, strtod
929 * also does extra computations to set the underflow and overflow
930 * flags when appropriate (i.e., when the result is tiny and
931 * inexact or when it is a numeric value rounded to +-infinity).
932 * #define NO_ERRNO if strtod should not assign errno = ERANGE when
933 * the result overflows to +-Infinity or underflows to 0.
936 #ifdef WORDS_BIGENDIAN
937 #define IEEE_BIG_ENDIAN
938 #else
939 #define IEEE_LITTLE_ENDIAN
940 #endif
942 #ifdef __vax__
943 #define VAX
944 #undef IEEE_BIG_ENDIAN
945 #undef IEEE_LITTLE_ENDIAN
946 #endif
948 #if defined(__arm__) && !defined(__VFP_FP__)
949 #define IEEE_BIG_ENDIAN
950 #undef IEEE_LITTLE_ENDIAN
951 #endif
953 #undef Long
954 #undef ULong
956 #if SIZEOF_INT == 4
957 #define Long int
958 #define ULong unsigned int
959 #elif SIZEOF_LONG == 4
960 #define Long long int
961 #define ULong unsigned long int
962 #endif
964 #if HAVE_LONG_LONG
965 #define Llong LONG_LONG
966 #endif
968 #ifdef DEBUG
969 #include "stdio.h"
970 #define Bug(x) {fprintf(stderr, "%s\n", x); exit(1);}
971 #endif
973 #include "stdlib.h"
974 #include "string.h"
976 #ifdef USE_LOCALE
977 #include "locale.h"
978 #endif
980 #ifdef MALLOC
981 extern void *MALLOC(size_t);
982 #else
983 #define MALLOC malloc
984 #endif
986 #ifndef Omit_Private_Memory
987 #ifndef PRIVATE_MEM
988 #define PRIVATE_MEM 2304
989 #endif
990 #define PRIVATE_mem ((PRIVATE_MEM+sizeof(double)-1)/sizeof(double))
991 static double private_mem[PRIVATE_mem], *pmem_next = private_mem;
992 #endif
994 #undef IEEE_Arith
995 #undef Avoid_Underflow
996 #ifdef IEEE_BIG_ENDIAN
997 #define IEEE_Arith
998 #endif
999 #ifdef IEEE_LITTLE_ENDIAN
1000 #define IEEE_Arith
1001 #endif
1003 #include "errno.h"
1005 #ifdef Bad_float_h
1007 #ifdef IEEE_Arith
1008 #define DBL_DIG 15
1009 #define DBL_MAX_10_EXP 308
1010 #define DBL_MAX_EXP 1024
1011 #define FLT_RADIX 2
1012 #endif /*IEEE_Arith*/
1014 #ifdef IBM
1015 #define DBL_DIG 16
1016 #define DBL_MAX_10_EXP 75
1017 #define DBL_MAX_EXP 63
1018 #define FLT_RADIX 16
1019 #define DBL_MAX 7.2370055773322621e+75
1020 #endif
1022 #ifdef VAX
1023 #define DBL_DIG 16
1024 #define DBL_MAX_10_EXP 38
1025 #define DBL_MAX_EXP 127
1026 #define FLT_RADIX 2
1027 #define DBL_MAX 1.7014118346046923e+38
1028 #endif
1030 #ifndef LONG_MAX
1031 #define LONG_MAX 2147483647
1032 #endif
1034 #else /* ifndef Bad_float_h */
1035 #include "float.h"
1036 #endif /* Bad_float_h */
1038 #ifndef __MATH_H__
1039 #include "math.h"
1040 #endif
1042 #ifdef __cplusplus
1043 extern "C" {
1044 #endif
1046 #if defined(IEEE_LITTLE_ENDIAN) + defined(IEEE_BIG_ENDIAN) + defined(VAX) + defined(IBM) != 1
1047 Exactly one of IEEE_LITTLE_ENDIAN, IEEE_BIG_ENDIAN, VAX, or IBM should be defined.
1048 #endif
1050 typedef union { double d; ULong L[2]; } U;
1052 #ifdef YES_ALIAS
1053 #define dval(x) x
1054 #ifdef IEEE_LITTLE_ENDIAN
1055 #define word0(x) ((ULong *)&x)[1]
1056 #define word1(x) ((ULong *)&x)[0]
1057 #else
1058 #define word0(x) ((ULong *)&x)[0]
1059 #define word1(x) ((ULong *)&x)[1]
1060 #endif
1061 #else
1062 #ifdef IEEE_LITTLE_ENDIAN
1063 #define word0(x) ((U*)&x)->L[1]
1064 #define word1(x) ((U*)&x)->L[0]
1065 #else
1066 #define word0(x) ((U*)&x)->L[0]
1067 #define word1(x) ((U*)&x)->L[1]
1068 #endif
1069 #define dval(x) ((U*)&x)->d
1070 #endif
1072 /* The following definition of Storeinc is appropriate for MIPS processors.
1073 * An alternative that might be better on some machines is
1074 * #define Storeinc(a,b,c) (*a++ = b << 16 | c & 0xffff)
1076 #if defined(IEEE_LITTLE_ENDIAN) + defined(VAX) + defined(__arm__)
1077 #define Storeinc(a,b,c) (((unsigned short *)a)[1] = (unsigned short)b, \
1078 ((unsigned short *)a)[0] = (unsigned short)c, a++)
1079 #else
1080 #define Storeinc(a,b,c) (((unsigned short *)a)[0] = (unsigned short)b, \
1081 ((unsigned short *)a)[1] = (unsigned short)c, a++)
1082 #endif
1084 /* #define P DBL_MANT_DIG */
1085 /* Ten_pmax = floor(P*log(2)/log(5)) */
1086 /* Bletch = (highest power of 2 < DBL_MAX_10_EXP) / 16 */
1087 /* Quick_max = floor((P-1)*log(FLT_RADIX)/log(10) - 1) */
1088 /* Int_max = floor(P*log(FLT_RADIX)/log(10) - 1) */
1090 #ifdef IEEE_Arith
1091 #define Exp_shift 20
1092 #define Exp_shift1 20
1093 #define Exp_msk1 0x100000
1094 #define Exp_msk11 0x100000
1095 #define Exp_mask 0x7ff00000
1096 #define P 53
1097 #define Bias 1023
1098 #define Emin (-1022)
1099 #define Exp_1 0x3ff00000
1100 #define Exp_11 0x3ff00000
1101 #define Ebits 11
1102 #define Frac_mask 0xfffff
1103 #define Frac_mask1 0xfffff
1104 #define Ten_pmax 22
1105 #define Bletch 0x10
1106 #define Bndry_mask 0xfffff
1107 #define Bndry_mask1 0xfffff
1108 #define LSB 1
1109 #define Sign_bit 0x80000000
1110 #define Log2P 1
1111 #define Tiny0 0
1112 #define Tiny1 1
1113 #define Quick_max 14
1114 #define Int_max 14
1115 #ifndef NO_IEEE_Scale
1116 #define Avoid_Underflow
1117 #ifdef Flush_Denorm /* debugging option */
1118 #undef Sudden_Underflow
1119 #endif
1120 #endif
1122 #ifndef Flt_Rounds
1123 #ifdef FLT_ROUNDS
1124 #define Flt_Rounds FLT_ROUNDS
1125 #else
1126 #define Flt_Rounds 1
1127 #endif
1128 #endif /*Flt_Rounds*/
1130 #ifdef Honor_FLT_ROUNDS
1131 #define Rounding rounding
1132 #undef Check_FLT_ROUNDS
1133 #define Check_FLT_ROUNDS
1134 #else
1135 #define Rounding Flt_Rounds
1136 #endif
1138 #else /* ifndef IEEE_Arith */
1139 #undef Check_FLT_ROUNDS
1140 #undef Honor_FLT_ROUNDS
1141 #undef SET_INEXACT
1142 #undef Sudden_Underflow
1143 #define Sudden_Underflow
1144 #ifdef IBM
1145 #undef Flt_Rounds
1146 #define Flt_Rounds 0
1147 #define Exp_shift 24
1148 #define Exp_shift1 24
1149 #define Exp_msk1 0x1000000
1150 #define Exp_msk11 0x1000000
1151 #define Exp_mask 0x7f000000
1152 #define P 14
1153 #define Bias 65
1154 #define Exp_1 0x41000000
1155 #define Exp_11 0x41000000
1156 #define Ebits 8 /* exponent has 7 bits, but 8 is the right value in b2d */
1157 #define Frac_mask 0xffffff
1158 #define Frac_mask1 0xffffff
1159 #define Bletch 4
1160 #define Ten_pmax 22
1161 #define Bndry_mask 0xefffff
1162 #define Bndry_mask1 0xffffff
1163 #define LSB 1
1164 #define Sign_bit 0x80000000
1165 #define Log2P 4
1166 #define Tiny0 0x100000
1167 #define Tiny1 0
1168 #define Quick_max 14
1169 #define Int_max 15
1170 #else /* VAX */
1171 #undef Flt_Rounds
1172 #define Flt_Rounds 1
1173 #define Exp_shift 23
1174 #define Exp_shift1 7
1175 #define Exp_msk1 0x80
1176 #define Exp_msk11 0x800000
1177 #define Exp_mask 0x7f80
1178 #define P 56
1179 #define Bias 129
1180 #define Exp_1 0x40800000
1181 #define Exp_11 0x4080
1182 #define Ebits 8
1183 #define Frac_mask 0x7fffff
1184 #define Frac_mask1 0xffff007f
1185 #define Ten_pmax 24
1186 #define Bletch 2
1187 #define Bndry_mask 0xffff007f
1188 #define Bndry_mask1 0xffff007f
1189 #define LSB 0x10000
1190 #define Sign_bit 0x8000
1191 #define Log2P 1
1192 #define Tiny0 0x80
1193 #define Tiny1 0
1194 #define Quick_max 15
1195 #define Int_max 15
1196 #endif /* IBM, VAX */
1197 #endif /* IEEE_Arith */
1199 #ifndef IEEE_Arith
1200 #define ROUND_BIASED
1201 #endif
1203 #ifdef RND_PRODQUOT
1204 #define rounded_product(a,b) a = rnd_prod(a, b)
1205 #define rounded_quotient(a,b) a = rnd_quot(a, b)
1206 extern double rnd_prod(double, double), rnd_quot(double, double);
1207 #else
1208 #define rounded_product(a,b) a *= b
1209 #define rounded_quotient(a,b) a /= b
1210 #endif
1212 #define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
1213 #define Big1 0xffffffff
1215 #ifndef Pack_32
1216 #define Pack_32
1217 #endif
1219 #define FFFFFFFF 0xffffffffUL
1221 #ifdef NO_LONG_LONG
1222 #undef ULLong
1223 #ifdef Just_16
1224 #undef Pack_32
1225 /* When Pack_32 is not defined, we store 16 bits per 32-bit Long.
1226 * This makes some inner loops simpler and sometimes saves work
1227 * during multiplications, but it often seems to make things slightly
1228 * slower. Hence the default is now to store 32 bits per Long.
1230 #endif
1231 #else /* long long available */
1232 #ifndef Llong
1233 #define Llong long long
1234 #endif
1235 #ifndef ULLong
1236 #define ULLong unsigned Llong
1237 #endif
1238 #endif /* NO_LONG_LONG */
1240 #ifndef MULTIPLE_THREADS
1241 #define ACQUIRE_DTOA_LOCK(n) /*nothing*/
1242 #define FREE_DTOA_LOCK(n) /*nothing*/
1243 #endif
1245 #define Kmax 15
1247 struct Bigint {
1248 struct Bigint *next;
1249 int k, maxwds, sign, wds;
1250 ULong x[1];
1253 typedef struct Bigint Bigint;
1255 static Bigint *freelist[Kmax+1];
1257 static Bigint *
1258 Balloc(int k)
1260 int x;
1261 Bigint *rv;
1262 #ifndef Omit_Private_Memory
1263 unsigned int len;
1264 #endif
1266 ACQUIRE_DTOA_LOCK(0);
1267 if ((rv = freelist[k]) != 0) {
1268 freelist[k] = rv->next;
1270 else {
1271 x = 1 << k;
1272 #ifdef Omit_Private_Memory
1273 rv = (Bigint *)MALLOC(sizeof(Bigint) + (x-1)*sizeof(ULong));
1274 #else
1275 len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)
1276 /sizeof(double);
1277 if (pmem_next - private_mem + len <= PRIVATE_mem) {
1278 rv = (Bigint*)pmem_next;
1279 pmem_next += len;
1281 else
1282 rv = (Bigint*)MALLOC(len*sizeof(double));
1283 #endif
1284 rv->k = k;
1285 rv->maxwds = x;
1287 FREE_DTOA_LOCK(0);
1288 rv->sign = rv->wds = 0;
1289 return rv;
1292 static void
1293 Bfree(Bigint *v)
1295 if (v) {
1296 ACQUIRE_DTOA_LOCK(0);
1297 v->next = freelist[v->k];
1298 freelist[v->k] = v;
1299 FREE_DTOA_LOCK(0);
1303 #define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign, \
1304 y->wds*sizeof(Long) + 2*sizeof(int))
1306 static Bigint *
1307 multadd(Bigint *b, int m, int a) /* multiply by m and add a */
1309 int i, wds;
1310 #ifdef ULLong
1311 ULong *x;
1312 ULLong carry, y;
1313 #else
1314 ULong carry, *x, y;
1315 #ifdef Pack_32
1316 ULong xi, z;
1317 #endif
1318 #endif
1319 Bigint *b1;
1321 wds = b->wds;
1322 x = b->x;
1323 i = 0;
1324 carry = a;
1325 do {
1326 #ifdef ULLong
1327 y = *x * (ULLong)m + carry;
1328 carry = y >> 32;
1329 *x++ = y & FFFFFFFF;
1330 #else
1331 #ifdef Pack_32
1332 xi = *x;
1333 y = (xi & 0xffff) * m + carry;
1334 z = (xi >> 16) * m + (y >> 16);
1335 carry = z >> 16;
1336 *x++ = (z << 16) + (y & 0xffff);
1337 #else
1338 y = *x * m + carry;
1339 carry = y >> 16;
1340 *x++ = y & 0xffff;
1341 #endif
1342 #endif
1343 } while (++i < wds);
1344 if (carry) {
1345 if (wds >= b->maxwds) {
1346 b1 = Balloc(b->k+1);
1347 Bcopy(b1, b);
1348 Bfree(b);
1349 b = b1;
1351 b->x[wds++] = carry;
1352 b->wds = wds;
1354 return b;
1357 static Bigint *
1358 s2b(const char *s, int nd0, int nd, ULong y9)
1360 Bigint *b;
1361 int i, k;
1362 Long x, y;
1364 x = (nd + 8) / 9;
1365 for (k = 0, y = 1; x > y; y <<= 1, k++) ;
1366 #ifdef Pack_32
1367 b = Balloc(k);
1368 b->x[0] = y9;
1369 b->wds = 1;
1370 #else
1371 b = Balloc(k+1);
1372 b->x[0] = y9 & 0xffff;
1373 b->wds = (b->x[1] = y9 >> 16) ? 2 : 1;
1374 #endif
1376 i = 9;
1377 if (9 < nd0) {
1378 s += 9;
1379 do {
1380 b = multadd(b, 10, *s++ - '0');
1381 } while (++i < nd0);
1382 s++;
1384 else
1385 s += 10;
1386 for (; i < nd; i++)
1387 b = multadd(b, 10, *s++ - '0');
1388 return b;
1391 static int
1392 hi0bits(register ULong x)
1394 register int k = 0;
1396 if (!(x & 0xffff0000)) {
1397 k = 16;
1398 x <<= 16;
1400 if (!(x & 0xff000000)) {
1401 k += 8;
1402 x <<= 8;
1404 if (!(x & 0xf0000000)) {
1405 k += 4;
1406 x <<= 4;
1408 if (!(x & 0xc0000000)) {
1409 k += 2;
1410 x <<= 2;
1412 if (!(x & 0x80000000)) {
1413 k++;
1414 if (!(x & 0x40000000))
1415 return 32;
1417 return k;
1420 static int
1421 lo0bits(ULong *y)
1423 register int k;
1424 register ULong x = *y;
1426 if (x & 7) {
1427 if (x & 1)
1428 return 0;
1429 if (x & 2) {
1430 *y = x >> 1;
1431 return 1;
1433 *y = x >> 2;
1434 return 2;
1436 k = 0;
1437 if (!(x & 0xffff)) {
1438 k = 16;
1439 x >>= 16;
1441 if (!(x & 0xff)) {
1442 k += 8;
1443 x >>= 8;
1445 if (!(x & 0xf)) {
1446 k += 4;
1447 x >>= 4;
1449 if (!(x & 0x3)) {
1450 k += 2;
1451 x >>= 2;
1453 if (!(x & 1)) {
1454 k++;
1455 x >>= 1;
1456 if (!x)
1457 return 32;
1459 *y = x;
1460 return k;
1463 static Bigint *
1464 i2b(int i)
1466 Bigint *b;
1468 b = Balloc(1);
1469 b->x[0] = i;
1470 b->wds = 1;
1471 return b;
1474 static Bigint *
1475 mult(Bigint *a, Bigint *b)
1477 Bigint *c;
1478 int k, wa, wb, wc;
1479 ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
1480 ULong y;
1481 #ifdef ULLong
1482 ULLong carry, z;
1483 #else
1484 ULong carry, z;
1485 #ifdef Pack_32
1486 ULong z2;
1487 #endif
1488 #endif
1490 if (a->wds < b->wds) {
1491 c = a;
1492 a = b;
1493 b = c;
1495 k = a->k;
1496 wa = a->wds;
1497 wb = b->wds;
1498 wc = wa + wb;
1499 if (wc > a->maxwds)
1500 k++;
1501 c = Balloc(k);
1502 for (x = c->x, xa = x + wc; x < xa; x++)
1503 *x = 0;
1504 xa = a->x;
1505 xae = xa + wa;
1506 xb = b->x;
1507 xbe = xb + wb;
1508 xc0 = c->x;
1509 #ifdef ULLong
1510 for (; xb < xbe; xc0++) {
1511 if ((y = *xb++) != 0) {
1512 x = xa;
1513 xc = xc0;
1514 carry = 0;
1515 do {
1516 z = *x++ * (ULLong)y + *xc + carry;
1517 carry = z >> 32;
1518 *xc++ = z & FFFFFFFF;
1519 } while (x < xae);
1520 *xc = carry;
1523 #else
1524 #ifdef Pack_32
1525 for (; xb < xbe; xb++, xc0++) {
1526 if (y = *xb & 0xffff) {
1527 x = xa;
1528 xc = xc0;
1529 carry = 0;
1530 do {
1531 z = (*x & 0xffff) * y + (*xc & 0xffff) + carry;
1532 carry = z >> 16;
1533 z2 = (*x++ >> 16) * y + (*xc >> 16) + carry;
1534 carry = z2 >> 16;
1535 Storeinc(xc, z2, z);
1536 } while (x < xae);
1537 *xc = carry;
1539 if (y = *xb >> 16) {
1540 x = xa;
1541 xc = xc0;
1542 carry = 0;
1543 z2 = *xc;
1544 do {
1545 z = (*x & 0xffff) * y + (*xc >> 16) + carry;
1546 carry = z >> 16;
1547 Storeinc(xc, z, z2);
1548 z2 = (*x++ >> 16) * y + (*xc & 0xffff) + carry;
1549 carry = z2 >> 16;
1550 } while (x < xae);
1551 *xc = z2;
1554 #else
1555 for (; xb < xbe; xc0++) {
1556 if (y = *xb++) {
1557 x = xa;
1558 xc = xc0;
1559 carry = 0;
1560 do {
1561 z = *x++ * y + *xc + carry;
1562 carry = z >> 16;
1563 *xc++ = z & 0xffff;
1564 } while (x < xae);
1565 *xc = carry;
1568 #endif
1569 #endif
1570 for (xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ;
1571 c->wds = wc;
1572 return c;
1575 static Bigint *p5s;
1577 static Bigint *
1578 pow5mult(Bigint *b, int k)
1580 Bigint *b1, *p5, *p51;
1581 int i;
1582 static int p05[3] = { 5, 25, 125 };
1584 if ((i = k & 3) != 0)
1585 b = multadd(b, p05[i-1], 0);
1587 if (!(k >>= 2))
1588 return b;
1589 if (!(p5 = p5s)) {
1590 /* first time */
1591 #ifdef MULTIPLE_THREADS
1592 ACQUIRE_DTOA_LOCK(1);
1593 if (!(p5 = p5s)) {
1594 p5 = p5s = i2b(625);
1595 p5->next = 0;
1597 FREE_DTOA_LOCK(1);
1598 #else
1599 p5 = p5s = i2b(625);
1600 p5->next = 0;
1601 #endif
1603 for (;;) {
1604 if (k & 1) {
1605 b1 = mult(b, p5);
1606 Bfree(b);
1607 b = b1;
1609 if (!(k >>= 1))
1610 break;
1611 if (!(p51 = p5->next)) {
1612 #ifdef MULTIPLE_THREADS
1613 ACQUIRE_DTOA_LOCK(1);
1614 if (!(p51 = p5->next)) {
1615 p51 = p5->next = mult(p5,p5);
1616 p51->next = 0;
1618 FREE_DTOA_LOCK(1);
1619 #else
1620 p51 = p5->next = mult(p5,p5);
1621 p51->next = 0;
1622 #endif
1624 p5 = p51;
1626 return b;
1629 static Bigint *
1630 lshift(Bigint *b, int k)
1632 int i, k1, n, n1;
1633 Bigint *b1;
1634 ULong *x, *x1, *xe, z;
1636 #ifdef Pack_32
1637 n = k >> 5;
1638 #else
1639 n = k >> 4;
1640 #endif
1641 k1 = b->k;
1642 n1 = n + b->wds + 1;
1643 for (i = b->maxwds; n1 > i; i <<= 1)
1644 k1++;
1645 b1 = Balloc(k1);
1646 x1 = b1->x;
1647 for (i = 0; i < n; i++)
1648 *x1++ = 0;
1649 x = b->x;
1650 xe = x + b->wds;
1651 #ifdef Pack_32
1652 if (k &= 0x1f) {
1653 k1 = 32 - k;
1654 z = 0;
1655 do {
1656 *x1++ = *x << k | z;
1657 z = *x++ >> k1;
1658 } while (x < xe);
1659 if ((*x1 = z) != 0)
1660 ++n1;
1662 #else
1663 if (k &= 0xf) {
1664 k1 = 16 - k;
1665 z = 0;
1666 do {
1667 *x1++ = *x << k & 0xffff | z;
1668 z = *x++ >> k1;
1669 } while (x < xe);
1670 if (*x1 = z)
1671 ++n1;
1673 #endif
1674 else
1675 do {
1676 *x1++ = *x++;
1677 } while (x < xe);
1678 b1->wds = n1 - 1;
1679 Bfree(b);
1680 return b1;
1683 static int
1684 cmp(Bigint *a, Bigint *b)
1686 ULong *xa, *xa0, *xb, *xb0;
1687 int i, j;
1689 i = a->wds;
1690 j = b->wds;
1691 #ifdef DEBUG
1692 if (i > 1 && !a->x[i-1])
1693 Bug("cmp called with a->x[a->wds-1] == 0");
1694 if (j > 1 && !b->x[j-1])
1695 Bug("cmp called with b->x[b->wds-1] == 0");
1696 #endif
1697 if (i -= j)
1698 return i;
1699 xa0 = a->x;
1700 xa = xa0 + j;
1701 xb0 = b->x;
1702 xb = xb0 + j;
1703 for (;;) {
1704 if (*--xa != *--xb)
1705 return *xa < *xb ? -1 : 1;
1706 if (xa <= xa0)
1707 break;
1709 return 0;
1712 static Bigint *
1713 diff(Bigint *a, Bigint *b)
1715 Bigint *c;
1716 int i, wa, wb;
1717 ULong *xa, *xae, *xb, *xbe, *xc;
1718 #ifdef ULLong
1719 ULLong borrow, y;
1720 #else
1721 ULong borrow, y;
1722 #ifdef Pack_32
1723 ULong z;
1724 #endif
1725 #endif
1727 i = cmp(a,b);
1728 if (!i) {
1729 c = Balloc(0);
1730 c->wds = 1;
1731 c->x[0] = 0;
1732 return c;
1734 if (i < 0) {
1735 c = a;
1736 a = b;
1737 b = c;
1738 i = 1;
1740 else
1741 i = 0;
1742 c = Balloc(a->k);
1743 c->sign = i;
1744 wa = a->wds;
1745 xa = a->x;
1746 xae = xa + wa;
1747 wb = b->wds;
1748 xb = b->x;
1749 xbe = xb + wb;
1750 xc = c->x;
1751 borrow = 0;
1752 #ifdef ULLong
1753 do {
1754 y = (ULLong)*xa++ - *xb++ - borrow;
1755 borrow = y >> 32 & (ULong)1;
1756 *xc++ = y & FFFFFFFF;
1757 } while (xb < xbe);
1758 while (xa < xae) {
1759 y = *xa++ - borrow;
1760 borrow = y >> 32 & (ULong)1;
1761 *xc++ = y & FFFFFFFF;
1763 #else
1764 #ifdef Pack_32
1765 do {
1766 y = (*xa & 0xffff) - (*xb & 0xffff) - borrow;
1767 borrow = (y & 0x10000) >> 16;
1768 z = (*xa++ >> 16) - (*xb++ >> 16) - borrow;
1769 borrow = (z & 0x10000) >> 16;
1770 Storeinc(xc, z, y);
1771 } while (xb < xbe);
1772 while (xa < xae) {
1773 y = (*xa & 0xffff) - borrow;
1774 borrow = (y & 0x10000) >> 16;
1775 z = (*xa++ >> 16) - borrow;
1776 borrow = (z & 0x10000) >> 16;
1777 Storeinc(xc, z, y);
1779 #else
1780 do {
1781 y = *xa++ - *xb++ - borrow;
1782 borrow = (y & 0x10000) >> 16;
1783 *xc++ = y & 0xffff;
1784 } while (xb < xbe);
1785 while (xa < xae) {
1786 y = *xa++ - borrow;
1787 borrow = (y & 0x10000) >> 16;
1788 *xc++ = y & 0xffff;
1790 #endif
1791 #endif
1792 while (!*--xc)
1793 wa--;
1794 c->wds = wa;
1795 return c;
1798 static double
1799 ulp(double x)
1801 register Long L;
1802 double a;
1804 L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1;
1805 #ifndef Avoid_Underflow
1806 #ifndef Sudden_Underflow
1807 if (L > 0) {
1808 #endif
1809 #endif
1810 #ifdef IBM
1811 L |= Exp_msk1 >> 4;
1812 #endif
1813 word0(a) = L;
1814 word1(a) = 0;
1815 #ifndef Avoid_Underflow
1816 #ifndef Sudden_Underflow
1818 else {
1819 L = -L >> Exp_shift;
1820 if (L < Exp_shift) {
1821 word0(a) = 0x80000 >> L;
1822 word1(a) = 0;
1824 else {
1825 word0(a) = 0;
1826 L -= Exp_shift;
1827 word1(a) = L >= 31 ? 1 : 1 << 31 - L;
1830 #endif
1831 #endif
1832 return dval(a);
1835 static double
1836 b2d(Bigint *a, int *e)
1838 ULong *xa, *xa0, w, y, z;
1839 int k;
1840 double d;
1841 #ifdef VAX
1842 ULong d0, d1;
1843 #else
1844 #define d0 word0(d)
1845 #define d1 word1(d)
1846 #endif
1848 xa0 = a->x;
1849 xa = xa0 + a->wds;
1850 y = *--xa;
1851 #ifdef DEBUG
1852 if (!y) Bug("zero y in b2d");
1853 #endif
1854 k = hi0bits(y);
1855 *e = 32 - k;
1856 #ifdef Pack_32
1857 if (k < Ebits) {
1858 d0 = Exp_1 | y >> (Ebits - k);
1859 w = xa > xa0 ? *--xa : 0;
1860 d1 = y << ((32-Ebits) + k) | w >> (Ebits - k);
1861 goto ret_d;
1863 z = xa > xa0 ? *--xa : 0;
1864 if (k -= Ebits) {
1865 d0 = Exp_1 | y << k | z >> (32 - k);
1866 y = xa > xa0 ? *--xa : 0;
1867 d1 = z << k | y >> (32 - k);
1869 else {
1870 d0 = Exp_1 | y;
1871 d1 = z;
1873 #else
1874 if (k < Ebits + 16) {
1875 z = xa > xa0 ? *--xa : 0;
1876 d0 = Exp_1 | y << k - Ebits | z >> Ebits + 16 - k;
1877 w = xa > xa0 ? *--xa : 0;
1878 y = xa > xa0 ? *--xa : 0;
1879 d1 = z << k + 16 - Ebits | w << k - Ebits | y >> 16 + Ebits - k;
1880 goto ret_d;
1882 z = xa > xa0 ? *--xa : 0;
1883 w = xa > xa0 ? *--xa : 0;
1884 k -= Ebits + 16;
1885 d0 = Exp_1 | y << k + 16 | z << k | w >> 16 - k;
1886 y = xa > xa0 ? *--xa : 0;
1887 d1 = w << k + 16 | y << k;
1888 #endif
1889 ret_d:
1890 #ifdef VAX
1891 word0(d) = d0 >> 16 | d0 << 16;
1892 word1(d) = d1 >> 16 | d1 << 16;
1893 #else
1894 #undef d0
1895 #undef d1
1896 #endif
1897 return dval(d);
1900 static Bigint *
1901 d2b(double d, int *e, int *bits)
1903 Bigint *b;
1904 int de, k;
1905 ULong *x, y, z;
1906 #ifndef Sudden_Underflow
1907 int i;
1908 #endif
1909 #ifdef VAX
1910 ULong d0, d1;
1911 d0 = word0(d) >> 16 | word0(d) << 16;
1912 d1 = word1(d) >> 16 | word1(d) << 16;
1913 #else
1914 #define d0 word0(d)
1915 #define d1 word1(d)
1916 #endif
1918 #ifdef Pack_32
1919 b = Balloc(1);
1920 #else
1921 b = Balloc(2);
1922 #endif
1923 x = b->x;
1925 z = d0 & Frac_mask;
1926 d0 &= 0x7fffffff; /* clear sign bit, which we ignore */
1927 #ifdef Sudden_Underflow
1928 de = (int)(d0 >> Exp_shift);
1929 #ifndef IBM
1930 z |= Exp_msk11;
1931 #endif
1932 #else
1933 if ((de = (int)(d0 >> Exp_shift)) != 0)
1934 z |= Exp_msk1;
1935 #endif
1936 #ifdef Pack_32
1937 if ((y = d1) != 0) {
1938 if ((k = lo0bits(&y)) != 0) {
1939 x[0] = y | z << (32 - k);
1940 z >>= k;
1942 else
1943 x[0] = y;
1944 #ifndef Sudden_Underflow
1946 #endif
1947 b->wds = (x[1] = z) ? 2 : 1;
1949 else {
1950 #ifdef DEBUG
1951 if (!z)
1952 Bug("Zero passed to d2b");
1953 #endif
1954 k = lo0bits(&z);
1955 x[0] = z;
1956 #ifndef Sudden_Underflow
1958 #endif
1959 b->wds = 1;
1960 k += 32;
1962 #else
1963 if (y = d1) {
1964 if (k = lo0bits(&y))
1965 if (k >= 16) {
1966 x[0] = y | z << 32 - k & 0xffff;
1967 x[1] = z >> k - 16 & 0xffff;
1968 x[2] = z >> k;
1969 i = 2;
1971 else {
1972 x[0] = y & 0xffff;
1973 x[1] = y >> 16 | z << 16 - k & 0xffff;
1974 x[2] = z >> k & 0xffff;
1975 x[3] = z >> k+16;
1976 i = 3;
1978 else {
1979 x[0] = y & 0xffff;
1980 x[1] = y >> 16;
1981 x[2] = z & 0xffff;
1982 x[3] = z >> 16;
1983 i = 3;
1986 else {
1987 #ifdef DEBUG
1988 if (!z)
1989 Bug("Zero passed to d2b");
1990 #endif
1991 k = lo0bits(&z);
1992 if (k >= 16) {
1993 x[0] = z;
1994 i = 0;
1996 else {
1997 x[0] = z & 0xffff;
1998 x[1] = z >> 16;
1999 i = 1;
2001 k += 32;
2003 while (!x[i])
2004 --i;
2005 b->wds = i + 1;
2006 #endif
2007 #ifndef Sudden_Underflow
2008 if (de) {
2009 #endif
2010 #ifdef IBM
2011 *e = (de - Bias - (P-1) << 2) + k;
2012 *bits = 4*P + 8 - k - hi0bits(word0(d) & Frac_mask);
2013 #else
2014 *e = de - Bias - (P-1) + k;
2015 *bits = P - k;
2016 #endif
2017 #ifndef Sudden_Underflow
2019 else {
2020 *e = de - Bias - (P-1) + 1 + k;
2021 #ifdef Pack_32
2022 *bits = 32*i - hi0bits(x[i-1]);
2023 #else
2024 *bits = (i+2)*16 - hi0bits(x[i]);
2025 #endif
2027 #endif
2028 return b;
2030 #undef d0
2031 #undef d1
2033 static double
2034 ratio(Bigint *a, Bigint *b)
2036 double da, db;
2037 int k, ka, kb;
2039 dval(da) = b2d(a, &ka);
2040 dval(db) = b2d(b, &kb);
2041 #ifdef Pack_32
2042 k = ka - kb + 32*(a->wds - b->wds);
2043 #else
2044 k = ka - kb + 16*(a->wds - b->wds);
2045 #endif
2046 #ifdef IBM
2047 if (k > 0) {
2048 word0(da) += (k >> 2)*Exp_msk1;
2049 if (k &= 3)
2050 dval(da) *= 1 << k;
2052 else {
2053 k = -k;
2054 word0(db) += (k >> 2)*Exp_msk1;
2055 if (k &= 3)
2056 dval(db) *= 1 << k;
2058 #else
2059 if (k > 0)
2060 word0(da) += k*Exp_msk1;
2061 else {
2062 k = -k;
2063 word0(db) += k*Exp_msk1;
2065 #endif
2066 return dval(da) / dval(db);
2069 static const double
2070 tens[] = {
2071 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
2072 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
2073 1e20, 1e21, 1e22
2074 #ifdef VAX
2075 , 1e23, 1e24
2076 #endif
2079 static const double
2080 #ifdef IEEE_Arith
2081 bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 };
2082 static const double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128,
2083 #ifdef Avoid_Underflow
2084 9007199254740992.*9007199254740992.e-256
2085 /* = 2^106 * 1e-53 */
2086 #else
2087 1e-256
2088 #endif
2090 /* The factor of 2^53 in tinytens[4] helps us avoid setting the underflow */
2091 /* flag unnecessarily. It leads to a song and dance at the end of strtod. */
2092 #define Scale_Bit 0x10
2093 #define n_bigtens 5
2094 #else
2095 #ifdef IBM
2096 bigtens[] = { 1e16, 1e32, 1e64 };
2097 static const double tinytens[] = { 1e-16, 1e-32, 1e-64 };
2098 #define n_bigtens 3
2099 #else
2100 bigtens[] = { 1e16, 1e32 };
2101 static const double tinytens[] = { 1e-16, 1e-32 };
2102 #define n_bigtens 2
2103 #endif
2104 #endif
2106 #ifndef IEEE_Arith
2107 #undef INFNAN_CHECK
2108 #endif
2110 #ifdef INFNAN_CHECK
2112 #ifndef NAN_WORD0
2113 #define NAN_WORD0 0x7ff80000
2114 #endif
2116 #ifndef NAN_WORD1
2117 #define NAN_WORD1 0
2118 #endif
2120 static int
2121 match(const char **sp, char *t)
2123 int c, d;
2124 const char *s = *sp;
2126 while (d = *t++) {
2127 if ((c = *++s) >= 'A' && c <= 'Z')
2128 c += 'a' - 'A';
2129 if (c != d)
2130 return 0;
2132 *sp = s + 1;
2133 return 1;
2136 #ifndef No_Hex_NaN
2137 static void
2138 hexnan(double *rvp, const char **sp)
2140 ULong c, x[2];
2141 const char *s;
2142 int havedig, udx0, xshift;
2144 x[0] = x[1] = 0;
2145 havedig = xshift = 0;
2146 udx0 = 1;
2147 s = *sp;
2148 while (c = *(const unsigned char*)++s) {
2149 if (c >= '0' && c <= '9')
2150 c -= '0';
2151 else if (c >= 'a' && c <= 'f')
2152 c += 10 - 'a';
2153 else if (c >= 'A' && c <= 'F')
2154 c += 10 - 'A';
2155 else if (c <= ' ') {
2156 if (udx0 && havedig) {
2157 udx0 = 0;
2158 xshift = 1;
2160 continue;
2162 else if (/*(*/ c == ')' && havedig) {
2163 *sp = s + 1;
2164 break;
2166 else
2167 return; /* invalid form: don't change *sp */
2168 havedig = 1;
2169 if (xshift) {
2170 xshift = 0;
2171 x[0] = x[1];
2172 x[1] = 0;
2174 if (udx0)
2175 x[0] = (x[0] << 4) | (x[1] >> 28);
2176 x[1] = (x[1] << 4) | c;
2178 if ((x[0] &= 0xfffff) || x[1]) {
2179 word0(*rvp) = Exp_mask | x[0];
2180 word1(*rvp) = x[1];
2183 #endif /*No_Hex_NaN*/
2184 #endif /* INFNAN_CHECK */
2186 double
2187 ruby_strtod(const char *s00, char **se)
2189 #ifdef Avoid_Underflow
2190 int scale;
2191 #endif
2192 int bb2, bb5, bbe, bd2, bd5, bbbits, bs2, c, dsign,
2193 e, e1, esign, i, j, k, nd, nd0, nf, nz, nz0, sign;
2194 const char *s, *s0, *s1;
2195 double aadj, aadj1, adj, rv, rv0;
2196 Long L;
2197 ULong y, z;
2198 Bigint *bb, *bb1, *bd, *bd0, *bs, *delta;
2199 #ifdef SET_INEXACT
2200 int inexact, oldinexact;
2201 #endif
2202 #ifdef Honor_FLT_ROUNDS
2203 int rounding;
2204 #endif
2205 #ifdef USE_LOCALE
2206 const char *s2;
2207 #endif
2209 sign = nz0 = nz = 0;
2210 dval(rv) = 0.;
2211 for (s = s00;;s++)
2212 switch (*s) {
2213 case '-':
2214 sign = 1;
2215 /* no break */
2216 case '+':
2217 if (*++s)
2218 goto break2;
2219 /* no break */
2220 case 0:
2221 goto ret0;
2222 case '\t':
2223 case '\n':
2224 case '\v':
2225 case '\f':
2226 case '\r':
2227 case ' ':
2228 continue;
2229 default:
2230 goto break2;
2232 break2:
2233 if (*s == '0') {
2234 nz0 = 1;
2235 while (*++s == '0') ;
2236 if (!*s)
2237 goto ret;
2239 s0 = s;
2240 y = z = 0;
2241 for (nd = nf = 0; (c = *s) >= '0' && c <= '9'; nd++, s++)
2242 if (nd < 9)
2243 y = 10*y + c - '0';
2244 else if (nd < 16)
2245 z = 10*z + c - '0';
2246 nd0 = nd;
2247 #ifdef USE_LOCALE
2248 s1 = localeconv()->decimal_point;
2249 if (c == *s1) {
2250 c = '.';
2251 if (*++s1) {
2252 s2 = s;
2253 for (;;) {
2254 if (*++s2 != *s1) {
2255 c = 0;
2256 break;
2258 if (!*++s1) {
2259 s = s2;
2260 break;
2265 #endif
2266 if (c == '.') {
2267 c = *++s;
2268 if (!nd) {
2269 for (; c == '0'; c = *++s)
2270 nz++;
2271 if (c > '0' && c <= '9') {
2272 s0 = s;
2273 nf += nz;
2274 nz = 0;
2275 goto have_dig;
2277 goto dig_done;
2279 for (; c >= '0' && c <= '9'; c = *++s) {
2280 have_dig:
2281 nz++;
2282 if (c -= '0') {
2283 nf += nz;
2284 for (i = 1; i < nz; i++)
2285 if (nd++ < 9)
2286 y *= 10;
2287 else if (nd <= DBL_DIG + 1)
2288 z *= 10;
2289 if (nd++ < 9)
2290 y = 10*y + c;
2291 else if (nd <= DBL_DIG + 1)
2292 z = 10*z + c;
2293 nz = 0;
2297 dig_done:
2298 e = 0;
2299 if (c == 'e' || c == 'E') {
2300 if (!nd && !nz && !nz0) {
2301 goto ret0;
2303 s00 = s;
2304 esign = 0;
2305 switch (c = *++s) {
2306 case '-':
2307 esign = 1;
2308 case '+':
2309 c = *++s;
2311 if (c >= '0' && c <= '9') {
2312 while (c == '0')
2313 c = *++s;
2314 if (c > '0' && c <= '9') {
2315 L = c - '0';
2316 s1 = s;
2317 while ((c = *++s) >= '0' && c <= '9')
2318 L = 10*L + c - '0';
2319 if (s - s1 > 8 || L > 19999)
2320 /* Avoid confusion from exponents
2321 * so large that e might overflow.
2323 e = 19999; /* safe for 16 bit ints */
2324 else
2325 e = (int)L;
2326 if (esign)
2327 e = -e;
2329 else
2330 e = 0;
2332 else
2333 s = s00;
2335 if (!nd) {
2336 if (!nz && !nz0) {
2337 #ifdef INFNAN_CHECK
2338 /* Check for Nan and Infinity */
2339 switch (c) {
2340 case 'i':
2341 case 'I':
2342 if (match(&s,"nf")) {
2343 --s;
2344 if (!match(&s,"inity"))
2345 ++s;
2346 word0(rv) = 0x7ff00000;
2347 word1(rv) = 0;
2348 goto ret;
2350 break;
2351 case 'n':
2352 case 'N':
2353 if (match(&s, "an")) {
2354 word0(rv) = NAN_WORD0;
2355 word1(rv) = NAN_WORD1;
2356 #ifndef No_Hex_NaN
2357 if (*s == '(') /*)*/
2358 hexnan(&rv, &s);
2359 #endif
2360 goto ret;
2363 #endif /* INFNAN_CHECK */
2364 ret0:
2365 s = s00;
2366 sign = 0;
2368 goto ret;
2370 e1 = e -= nf;
2372 /* Now we have nd0 digits, starting at s0, followed by a
2373 * decimal point, followed by nd-nd0 digits. The number we're
2374 * after is the integer represented by those digits times
2375 * 10**e */
2377 if (!nd0)
2378 nd0 = nd;
2379 k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;
2380 dval(rv) = y;
2381 if (k > 9) {
2382 #ifdef SET_INEXACT
2383 if (k > DBL_DIG)
2384 oldinexact = get_inexact();
2385 #endif
2386 dval(rv) = tens[k - 9] * dval(rv) + z;
2388 bd0 = 0;
2389 if (nd <= DBL_DIG
2390 #ifndef RND_PRODQUOT
2391 #ifndef Honor_FLT_ROUNDS
2392 && Flt_Rounds == 1
2393 #endif
2394 #endif
2396 if (!e)
2397 goto ret;
2398 if (e > 0) {
2399 if (e <= Ten_pmax) {
2400 #ifdef VAX
2401 goto vax_ovfl_check;
2402 #else
2403 #ifdef Honor_FLT_ROUNDS
2404 /* round correctly FLT_ROUNDS = 2 or 3 */
2405 if (sign) {
2406 rv = -rv;
2407 sign = 0;
2409 #endif
2410 /* rv = */ rounded_product(dval(rv), tens[e]);
2411 goto ret;
2412 #endif
2414 i = DBL_DIG - nd;
2415 if (e <= Ten_pmax + i) {
2416 /* A fancier test would sometimes let us do
2417 * this for larger i values.
2419 #ifdef Honor_FLT_ROUNDS
2420 /* round correctly FLT_ROUNDS = 2 or 3 */
2421 if (sign) {
2422 rv = -rv;
2423 sign = 0;
2425 #endif
2426 e -= i;
2427 dval(rv) *= tens[i];
2428 #ifdef VAX
2429 /* VAX exponent range is so narrow we must
2430 * worry about overflow here...
2432 vax_ovfl_check:
2433 word0(rv) -= P*Exp_msk1;
2434 /* rv = */ rounded_product(dval(rv), tens[e]);
2435 if ((word0(rv) & Exp_mask)
2436 > Exp_msk1*(DBL_MAX_EXP+Bias-1-P))
2437 goto ovfl;
2438 word0(rv) += P*Exp_msk1;
2439 #else
2440 /* rv = */ rounded_product(dval(rv), tens[e]);
2441 #endif
2442 goto ret;
2445 #ifndef Inaccurate_Divide
2446 else if (e >= -Ten_pmax) {
2447 #ifdef Honor_FLT_ROUNDS
2448 /* round correctly FLT_ROUNDS = 2 or 3 */
2449 if (sign) {
2450 rv = -rv;
2451 sign = 0;
2453 #endif
2454 /* rv = */ rounded_quotient(dval(rv), tens[-e]);
2455 goto ret;
2457 #endif
2459 e1 += nd - k;
2461 #ifdef IEEE_Arith
2462 #ifdef SET_INEXACT
2463 inexact = 1;
2464 if (k <= DBL_DIG)
2465 oldinexact = get_inexact();
2466 #endif
2467 #ifdef Avoid_Underflow
2468 scale = 0;
2469 #endif
2470 #ifdef Honor_FLT_ROUNDS
2471 if ((rounding = Flt_Rounds) >= 2) {
2472 if (sign)
2473 rounding = rounding == 2 ? 0 : 2;
2474 else
2475 if (rounding != 2)
2476 rounding = 0;
2478 #endif
2479 #endif /*IEEE_Arith*/
2481 /* Get starting approximation = rv * 10**e1 */
2483 if (e1 > 0) {
2484 if ((i = e1 & 15) != 0)
2485 dval(rv) *= tens[i];
2486 if (e1 &= ~15) {
2487 if (e1 > DBL_MAX_10_EXP) {
2488 ovfl:
2489 #ifndef NO_ERRNO
2490 errno = ERANGE;
2491 #endif
2492 /* Can't trust HUGE_VAL */
2493 #ifdef IEEE_Arith
2494 #ifdef Honor_FLT_ROUNDS
2495 switch (rounding) {
2496 case 0: /* toward 0 */
2497 case 3: /* toward -infinity */
2498 word0(rv) = Big0;
2499 word1(rv) = Big1;
2500 break;
2501 default:
2502 word0(rv) = Exp_mask;
2503 word1(rv) = 0;
2505 #else /*Honor_FLT_ROUNDS*/
2506 word0(rv) = Exp_mask;
2507 word1(rv) = 0;
2508 #endif /*Honor_FLT_ROUNDS*/
2509 #ifdef SET_INEXACT
2510 /* set overflow bit */
2511 dval(rv0) = 1e300;
2512 dval(rv0) *= dval(rv0);
2513 #endif
2514 #else /*IEEE_Arith*/
2515 word0(rv) = Big0;
2516 word1(rv) = Big1;
2517 #endif /*IEEE_Arith*/
2518 if (bd0)
2519 goto retfree;
2520 goto ret;
2522 e1 >>= 4;
2523 for (j = 0; e1 > 1; j++, e1 >>= 1)
2524 if (e1 & 1)
2525 dval(rv) *= bigtens[j];
2526 /* The last multiplication could overflow. */
2527 word0(rv) -= P*Exp_msk1;
2528 dval(rv) *= bigtens[j];
2529 if ((z = word0(rv) & Exp_mask)
2530 > Exp_msk1*(DBL_MAX_EXP+Bias-P))
2531 goto ovfl;
2532 if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) {
2533 /* set to largest number */
2534 /* (Can't trust DBL_MAX) */
2535 word0(rv) = Big0;
2536 word1(rv) = Big1;
2538 else
2539 word0(rv) += P*Exp_msk1;
2542 else if (e1 < 0) {
2543 e1 = -e1;
2544 if ((i = e1 & 15) != 0)
2545 dval(rv) /= tens[i];
2546 if (e1 >>= 4) {
2547 if (e1 >= 1 << n_bigtens)
2548 goto undfl;
2549 #ifdef Avoid_Underflow
2550 if (e1 & Scale_Bit)
2551 scale = 2*P;
2552 for (j = 0; e1 > 0; j++, e1 >>= 1)
2553 if (e1 & 1)
2554 dval(rv) *= tinytens[j];
2555 if (scale && (j = 2*P + 1 - ((word0(rv) & Exp_mask)
2556 >> Exp_shift)) > 0) {
2557 /* scaled rv is denormal; zap j low bits */
2558 if (j >= 32) {
2559 word1(rv) = 0;
2560 if (j >= 53)
2561 word0(rv) = (P+2)*Exp_msk1;
2562 else
2563 word0(rv) &= 0xffffffff << (j-32);
2565 else
2566 word1(rv) &= 0xffffffff << j;
2568 #else
2569 for (j = 0; e1 > 1; j++, e1 >>= 1)
2570 if (e1 & 1)
2571 dval(rv) *= tinytens[j];
2572 /* The last multiplication could underflow. */
2573 dval(rv0) = dval(rv);
2574 dval(rv) *= tinytens[j];
2575 if (!dval(rv)) {
2576 dval(rv) = 2.*dval(rv0);
2577 dval(rv) *= tinytens[j];
2578 #endif
2579 if (!dval(rv)) {
2580 undfl:
2581 dval(rv) = 0.;
2582 #ifndef NO_ERRNO
2583 errno = ERANGE;
2584 #endif
2585 if (bd0)
2586 goto retfree;
2587 goto ret;
2589 #ifndef Avoid_Underflow
2590 word0(rv) = Tiny0;
2591 word1(rv) = Tiny1;
2592 /* The refinement below will clean
2593 * this approximation up.
2596 #endif
2600 /* Now the hard part -- adjusting rv to the correct value.*/
2602 /* Put digits into bd: true value = bd * 10^e */
2604 bd0 = s2b(s0, nd0, nd, y);
2606 for (;;) {
2607 bd = Balloc(bd0->k);
2608 Bcopy(bd, bd0);
2609 bb = d2b(dval(rv), &bbe, &bbbits); /* rv = bb * 2^bbe */
2610 bs = i2b(1);
2612 if (e >= 0) {
2613 bb2 = bb5 = 0;
2614 bd2 = bd5 = e;
2616 else {
2617 bb2 = bb5 = -e;
2618 bd2 = bd5 = 0;
2620 if (bbe >= 0)
2621 bb2 += bbe;
2622 else
2623 bd2 -= bbe;
2624 bs2 = bb2;
2625 #ifdef Honor_FLT_ROUNDS
2626 if (rounding != 1)
2627 bs2++;
2628 #endif
2629 #ifdef Avoid_Underflow
2630 j = bbe - scale;
2631 i = j + bbbits - 1; /* logb(rv) */
2632 if (i < Emin) /* denormal */
2633 j += P - Emin;
2634 else
2635 j = P + 1 - bbbits;
2636 #else /*Avoid_Underflow*/
2637 #ifdef Sudden_Underflow
2638 #ifdef IBM
2639 j = 1 + 4*P - 3 - bbbits + ((bbe + bbbits - 1) & 3);
2640 #else
2641 j = P + 1 - bbbits;
2642 #endif
2643 #else /*Sudden_Underflow*/
2644 j = bbe;
2645 i = j + bbbits - 1; /* logb(rv) */
2646 if (i < Emin) /* denormal */
2647 j += P - Emin;
2648 else
2649 j = P + 1 - bbbits;
2650 #endif /*Sudden_Underflow*/
2651 #endif /*Avoid_Underflow*/
2652 bb2 += j;
2653 bd2 += j;
2654 #ifdef Avoid_Underflow
2655 bd2 += scale;
2656 #endif
2657 i = bb2 < bd2 ? bb2 : bd2;
2658 if (i > bs2)
2659 i = bs2;
2660 if (i > 0) {
2661 bb2 -= i;
2662 bd2 -= i;
2663 bs2 -= i;
2665 if (bb5 > 0) {
2666 bs = pow5mult(bs, bb5);
2667 bb1 = mult(bs, bb);
2668 Bfree(bb);
2669 bb = bb1;
2671 if (bb2 > 0)
2672 bb = lshift(bb, bb2);
2673 if (bd5 > 0)
2674 bd = pow5mult(bd, bd5);
2675 if (bd2 > 0)
2676 bd = lshift(bd, bd2);
2677 if (bs2 > 0)
2678 bs = lshift(bs, bs2);
2679 delta = diff(bb, bd);
2680 dsign = delta->sign;
2681 delta->sign = 0;
2682 i = cmp(delta, bs);
2683 #ifdef Honor_FLT_ROUNDS
2684 if (rounding != 1) {
2685 if (i < 0) {
2686 /* Error is less than an ulp */
2687 if (!delta->x[0] && delta->wds <= 1) {
2688 /* exact */
2689 #ifdef SET_INEXACT
2690 inexact = 0;
2691 #endif
2692 break;
2694 if (rounding) {
2695 if (dsign) {
2696 adj = 1.;
2697 goto apply_adj;
2700 else if (!dsign) {
2701 adj = -1.;
2702 if (!word1(rv)
2703 && !(word0(rv) & Frac_mask)) {
2704 y = word0(rv) & Exp_mask;
2705 #ifdef Avoid_Underflow
2706 if (!scale || y > 2*P*Exp_msk1)
2707 #else
2708 if (y)
2709 #endif
2711 delta = lshift(delta,Log2P);
2712 if (cmp(delta, bs) <= 0)
2713 adj = -0.5;
2716 apply_adj:
2717 #ifdef Avoid_Underflow
2718 if (scale && (y = word0(rv) & Exp_mask)
2719 <= 2*P*Exp_msk1)
2720 word0(adj) += (2*P+1)*Exp_msk1 - y;
2721 #else
2722 #ifdef Sudden_Underflow
2723 if ((word0(rv) & Exp_mask) <=
2724 P*Exp_msk1) {
2725 word0(rv) += P*Exp_msk1;
2726 dval(rv) += adj*ulp(dval(rv));
2727 word0(rv) -= P*Exp_msk1;
2729 else
2730 #endif /*Sudden_Underflow*/
2731 #endif /*Avoid_Underflow*/
2732 dval(rv) += adj*ulp(dval(rv));
2734 break;
2736 adj = ratio(delta, bs);
2737 if (adj < 1.)
2738 adj = 1.;
2739 if (adj <= 0x7ffffffe) {
2740 /* adj = rounding ? ceil(adj) : floor(adj); */
2741 y = adj;
2742 if (y != adj) {
2743 if (!((rounding>>1) ^ dsign))
2744 y++;
2745 adj = y;
2748 #ifdef Avoid_Underflow
2749 if (scale && (y = word0(rv) & Exp_mask) <= 2*P*Exp_msk1)
2750 word0(adj) += (2*P+1)*Exp_msk1 - y;
2751 #else
2752 #ifdef Sudden_Underflow
2753 if ((word0(rv) & Exp_mask) <= P*Exp_msk1) {
2754 word0(rv) += P*Exp_msk1;
2755 adj *= ulp(dval(rv));
2756 if (dsign)
2757 dval(rv) += adj;
2758 else
2759 dval(rv) -= adj;
2760 word0(rv) -= P*Exp_msk1;
2761 goto cont;
2763 #endif /*Sudden_Underflow*/
2764 #endif /*Avoid_Underflow*/
2765 adj *= ulp(dval(rv));
2766 if (dsign)
2767 dval(rv) += adj;
2768 else
2769 dval(rv) -= adj;
2770 goto cont;
2772 #endif /*Honor_FLT_ROUNDS*/
2774 if (i < 0) {
2775 /* Error is less than half an ulp -- check for
2776 * special case of mantissa a power of two.
2778 if (dsign || word1(rv) || word0(rv) & Bndry_mask
2779 #ifdef IEEE_Arith
2780 #ifdef Avoid_Underflow
2781 || (word0(rv) & Exp_mask) <= (2*P+1)*Exp_msk1
2782 #else
2783 || (word0(rv) & Exp_mask) <= Exp_msk1
2784 #endif
2785 #endif
2787 #ifdef SET_INEXACT
2788 if (!delta->x[0] && delta->wds <= 1)
2789 inexact = 0;
2790 #endif
2791 break;
2793 if (!delta->x[0] && delta->wds <= 1) {
2794 /* exact result */
2795 #ifdef SET_INEXACT
2796 inexact = 0;
2797 #endif
2798 break;
2800 delta = lshift(delta,Log2P);
2801 if (cmp(delta, bs) > 0)
2802 goto drop_down;
2803 break;
2805 if (i == 0) {
2806 /* exactly half-way between */
2807 if (dsign) {
2808 if ((word0(rv) & Bndry_mask1) == Bndry_mask1
2809 && word1(rv) == (
2810 #ifdef Avoid_Underflow
2811 (scale && (y = word0(rv) & Exp_mask) <= 2*P*Exp_msk1)
2812 ? (0xffffffff & (0xffffffff << (2*P+1-(y>>Exp_shift)))) :
2813 #endif
2814 0xffffffff)) {
2815 /*boundary case -- increment exponent*/
2816 word0(rv) = (word0(rv) & Exp_mask)
2817 + Exp_msk1
2818 #ifdef IBM
2819 | Exp_msk1 >> 4
2820 #endif
2822 word1(rv) = 0;
2823 #ifdef Avoid_Underflow
2824 dsign = 0;
2825 #endif
2826 break;
2829 else if (!(word0(rv) & Bndry_mask) && !word1(rv)) {
2830 drop_down:
2831 /* boundary case -- decrement exponent */
2832 #ifdef Sudden_Underflow /*{{*/
2833 L = word0(rv) & Exp_mask;
2834 #ifdef IBM
2835 if (L < Exp_msk1)
2836 #else
2837 #ifdef Avoid_Underflow
2838 if (L <= (scale ? (2*P+1)*Exp_msk1 : Exp_msk1))
2839 #else
2840 if (L <= Exp_msk1)
2841 #endif /*Avoid_Underflow*/
2842 #endif /*IBM*/
2843 goto undfl;
2844 L -= Exp_msk1;
2845 #else /*Sudden_Underflow}{*/
2846 #ifdef Avoid_Underflow
2847 if (scale) {
2848 L = word0(rv) & Exp_mask;
2849 if (L <= (2*P+1)*Exp_msk1) {
2850 if (L > (P+2)*Exp_msk1)
2851 /* round even ==> */
2852 /* accept rv */
2853 break;
2854 /* rv = smallest denormal */
2855 goto undfl;
2858 #endif /*Avoid_Underflow*/
2859 L = (word0(rv) & Exp_mask) - Exp_msk1;
2860 #endif /*Sudden_Underflow}}*/
2861 word0(rv) = L | Bndry_mask1;
2862 word1(rv) = 0xffffffff;
2863 #ifdef IBM
2864 goto cont;
2865 #else
2866 break;
2867 #endif
2869 #ifndef ROUND_BIASED
2870 if (!(word1(rv) & LSB))
2871 break;
2872 #endif
2873 if (dsign)
2874 dval(rv) += ulp(dval(rv));
2875 #ifndef ROUND_BIASED
2876 else {
2877 dval(rv) -= ulp(dval(rv));
2878 #ifndef Sudden_Underflow
2879 if (!dval(rv))
2880 goto undfl;
2881 #endif
2883 #ifdef Avoid_Underflow
2884 dsign = 1 - dsign;
2885 #endif
2886 #endif
2887 break;
2889 if ((aadj = ratio(delta, bs)) <= 2.) {
2890 if (dsign)
2891 aadj = aadj1 = 1.;
2892 else if (word1(rv) || word0(rv) & Bndry_mask) {
2893 #ifndef Sudden_Underflow
2894 if (word1(rv) == Tiny1 && !word0(rv))
2895 goto undfl;
2896 #endif
2897 aadj = 1.;
2898 aadj1 = -1.;
2900 else {
2901 /* special case -- power of FLT_RADIX to be */
2902 /* rounded down... */
2904 if (aadj < 2./FLT_RADIX)
2905 aadj = 1./FLT_RADIX;
2906 else
2907 aadj *= 0.5;
2908 aadj1 = -aadj;
2911 else {
2912 aadj *= 0.5;
2913 aadj1 = dsign ? aadj : -aadj;
2914 #ifdef Check_FLT_ROUNDS
2915 switch (Rounding) {
2916 case 2: /* towards +infinity */
2917 aadj1 -= 0.5;
2918 break;
2919 case 0: /* towards 0 */
2920 case 3: /* towards -infinity */
2921 aadj1 += 0.5;
2923 #else
2924 if (Flt_Rounds == 0)
2925 aadj1 += 0.5;
2926 #endif /*Check_FLT_ROUNDS*/
2928 y = word0(rv) & Exp_mask;
2930 /* Check for overflow */
2932 if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) {
2933 dval(rv0) = dval(rv);
2934 word0(rv) -= P*Exp_msk1;
2935 adj = aadj1 * ulp(dval(rv));
2936 dval(rv) += adj;
2937 if ((word0(rv) & Exp_mask) >=
2938 Exp_msk1*(DBL_MAX_EXP+Bias-P)) {
2939 if (word0(rv0) == Big0 && word1(rv0) == Big1)
2940 goto ovfl;
2941 word0(rv) = Big0;
2942 word1(rv) = Big1;
2943 goto cont;
2945 else
2946 word0(rv) += P*Exp_msk1;
2948 else {
2949 #ifdef Avoid_Underflow
2950 if (scale && y <= 2*P*Exp_msk1) {
2951 if (aadj <= 0x7fffffff) {
2952 if ((z = aadj) <= 0)
2953 z = 1;
2954 aadj = z;
2955 aadj1 = dsign ? aadj : -aadj;
2957 word0(aadj1) += (2*P+1)*Exp_msk1 - y;
2959 adj = aadj1 * ulp(dval(rv));
2960 dval(rv) += adj;
2961 #else
2962 #ifdef Sudden_Underflow
2963 if ((word0(rv) & Exp_mask) <= P*Exp_msk1) {
2964 dval(rv0) = dval(rv);
2965 word0(rv) += P*Exp_msk1;
2966 adj = aadj1 * ulp(dval(rv));
2967 dval(rv) += adj;
2968 #ifdef IBM
2969 if ((word0(rv) & Exp_mask) < P*Exp_msk1)
2970 #else
2971 if ((word0(rv) & Exp_mask) <= P*Exp_msk1)
2972 #endif
2974 if (word0(rv0) == Tiny0 && word1(rv0) == Tiny1)
2975 goto undfl;
2976 word0(rv) = Tiny0;
2977 word1(rv) = Tiny1;
2978 goto cont;
2980 else
2981 word0(rv) -= P*Exp_msk1;
2983 else {
2984 adj = aadj1 * ulp(dval(rv));
2985 dval(rv) += adj;
2987 #else /*Sudden_Underflow*/
2988 /* Compute adj so that the IEEE rounding rules will
2989 * correctly round rv + adj in some half-way cases.
2990 * If rv * ulp(rv) is denormalized (i.e.,
2991 * y <= (P-1)*Exp_msk1), we must adjust aadj to avoid
2992 * trouble from bits lost to denormalization;
2993 * example: 1.2e-307 .
2995 if (y <= (P-1)*Exp_msk1 && aadj > 1.) {
2996 aadj1 = (double)(int)(aadj + 0.5);
2997 if (!dsign)
2998 aadj1 = -aadj1;
3000 adj = aadj1 * ulp(dval(rv));
3001 dval(rv) += adj;
3002 #endif /*Sudden_Underflow*/
3003 #endif /*Avoid_Underflow*/
3005 z = word0(rv) & Exp_mask;
3006 #ifndef SET_INEXACT
3007 #ifdef Avoid_Underflow
3008 if (!scale)
3009 #endif
3010 if (y == z) {
3011 /* Can we stop now? */
3012 L = (Long)aadj;
3013 aadj -= L;
3014 /* The tolerances below are conservative. */
3015 if (dsign || word1(rv) || word0(rv) & Bndry_mask) {
3016 if (aadj < .4999999 || aadj > .5000001)
3017 break;
3019 else if (aadj < .4999999/FLT_RADIX)
3020 break;
3022 #endif
3023 cont:
3024 Bfree(bb);
3025 Bfree(bd);
3026 Bfree(bs);
3027 Bfree(delta);
3029 #ifdef SET_INEXACT
3030 if (inexact) {
3031 if (!oldinexact) {
3032 word0(rv0) = Exp_1 + (70 << Exp_shift);
3033 word1(rv0) = 0;
3034 dval(rv0) += 1.;
3037 else if (!oldinexact)
3038 clear_inexact();
3039 #endif
3040 #ifdef Avoid_Underflow
3041 if (scale) {
3042 word0(rv0) = Exp_1 - 2*P*Exp_msk1;
3043 word1(rv0) = 0;
3044 dval(rv) *= dval(rv0);
3045 #ifndef NO_ERRNO
3046 /* try to avoid the bug of testing an 8087 register value */
3047 if (word0(rv) == 0 && word1(rv) == 0)
3048 errno = ERANGE;
3049 #endif
3051 #endif /* Avoid_Underflow */
3052 #ifdef SET_INEXACT
3053 if (inexact && !(word0(rv) & Exp_mask)) {
3054 /* set underflow bit */
3055 dval(rv0) = 1e-300;
3056 dval(rv0) *= dval(rv0);
3058 #endif
3059 retfree:
3060 Bfree(bb);
3061 Bfree(bd);
3062 Bfree(bs);
3063 Bfree(bd0);
3064 Bfree(delta);
3065 ret:
3066 if (se)
3067 *se = (char *)s;
3068 return sign ? -dval(rv) : dval(rv);
3071 static int
3072 quorem(Bigint *b, Bigint *S)
3074 int n;
3075 ULong *bx, *bxe, q, *sx, *sxe;
3076 #ifdef ULLong
3077 ULLong borrow, carry, y, ys;
3078 #else
3079 ULong borrow, carry, y, ys;
3080 #ifdef Pack_32
3081 ULong si, z, zs;
3082 #endif
3083 #endif
3085 n = S->wds;
3086 #ifdef DEBUG
3087 /*debug*/ if (b->wds > n)
3088 /*debug*/ Bug("oversize b in quorem");
3089 #endif
3090 if (b->wds < n)
3091 return 0;
3092 sx = S->x;
3093 sxe = sx + --n;
3094 bx = b->x;
3095 bxe = bx + n;
3096 q = *bxe / (*sxe + 1); /* ensure q <= true quotient */
3097 #ifdef DEBUG
3098 /*debug*/ if (q > 9)
3099 /*debug*/ Bug("oversized quotient in quorem");
3100 #endif
3101 if (q) {
3102 borrow = 0;
3103 carry = 0;
3104 do {
3105 #ifdef ULLong
3106 ys = *sx++ * (ULLong)q + carry;
3107 carry = ys >> 32;
3108 y = *bx - (ys & FFFFFFFF) - borrow;
3109 borrow = y >> 32 & (ULong)1;
3110 *bx++ = y & FFFFFFFF;
3111 #else
3112 #ifdef Pack_32
3113 si = *sx++;
3114 ys = (si & 0xffff) * q + carry;
3115 zs = (si >> 16) * q + (ys >> 16);
3116 carry = zs >> 16;
3117 y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
3118 borrow = (y & 0x10000) >> 16;
3119 z = (*bx >> 16) - (zs & 0xffff) - borrow;
3120 borrow = (z & 0x10000) >> 16;
3121 Storeinc(bx, z, y);
3122 #else
3123 ys = *sx++ * q + carry;
3124 carry = ys >> 16;
3125 y = *bx - (ys & 0xffff) - borrow;
3126 borrow = (y & 0x10000) >> 16;
3127 *bx++ = y & 0xffff;
3128 #endif
3129 #endif
3130 } while (sx <= sxe);
3131 if (!*bxe) {
3132 bx = b->x;
3133 while (--bxe > bx && !*bxe)
3134 --n;
3135 b->wds = n;
3138 if (cmp(b, S) >= 0) {
3139 q++;
3140 borrow = 0;
3141 carry = 0;
3142 bx = b->x;
3143 sx = S->x;
3144 do {
3145 #ifdef ULLong
3146 ys = *sx++ + carry;
3147 carry = ys >> 32;
3148 y = *bx - (ys & FFFFFFFF) - borrow;
3149 borrow = y >> 32 & (ULong)1;
3150 *bx++ = y & FFFFFFFF;
3151 #else
3152 #ifdef Pack_32
3153 si = *sx++;
3154 ys = (si & 0xffff) + carry;
3155 zs = (si >> 16) + (ys >> 16);
3156 carry = zs >> 16;
3157 y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
3158 borrow = (y & 0x10000) >> 16;
3159 z = (*bx >> 16) - (zs & 0xffff) - borrow;
3160 borrow = (z & 0x10000) >> 16;
3161 Storeinc(bx, z, y);
3162 #else
3163 ys = *sx++ + carry;
3164 carry = ys >> 16;
3165 y = *bx - (ys & 0xffff) - borrow;
3166 borrow = (y & 0x10000) >> 16;
3167 *bx++ = y & 0xffff;
3168 #endif
3169 #endif
3170 } while (sx <= sxe);
3171 bx = b->x;
3172 bxe = bx + n;
3173 if (!*bxe) {
3174 while (--bxe > bx && !*bxe)
3175 --n;
3176 b->wds = n;
3179 return q;
3182 #ifndef MULTIPLE_THREADS
3183 static char *dtoa_result;
3184 #endif
3186 static char *
3187 rv_alloc(int i)
3189 int j, k, *r;
3191 j = sizeof(ULong);
3192 for (k = 0;
3193 sizeof(Bigint) - sizeof(ULong) - sizeof(int) + j <= i;
3194 j <<= 1)
3195 k++;
3196 r = (int*)Balloc(k);
3197 *r = k;
3198 return
3199 #ifndef MULTIPLE_THREADS
3200 dtoa_result =
3201 #endif
3202 (char *)(r+1);
3205 static char *
3206 nrv_alloc(char *s, char **rve, int n)
3208 char *rv, *t;
3210 t = rv = rv_alloc(n);
3211 while ((*t = *s++) != 0) t++;
3212 if (rve)
3213 *rve = t;
3214 return rv;
3217 /* freedtoa(s) must be used to free values s returned by dtoa
3218 * when MULTIPLE_THREADS is #defined. It should be used in all cases,
3219 * but for consistency with earlier versions of dtoa, it is optional
3220 * when MULTIPLE_THREADS is not defined.
3223 void
3224 freedtoa(char *s)
3226 Bigint *b = (Bigint *)((int *)s - 1);
3227 b->maxwds = 1 << (b->k = *(int*)b);
3228 Bfree(b);
3229 #ifndef MULTIPLE_THREADS
3230 if (s == dtoa_result)
3231 dtoa_result = 0;
3232 #endif
3235 /* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
3237 * Inspired by "How to Print Floating-Point Numbers Accurately" by
3238 * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 112-126].
3240 * Modifications:
3241 * 1. Rather than iterating, we use a simple numeric overestimate
3242 * to determine k = floor(log10(d)). We scale relevant
3243 * quantities using O(log2(k)) rather than O(k) multiplications.
3244 * 2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
3245 * try to generate digits strictly left to right. Instead, we
3246 * compute with fewer bits and propagate the carry if necessary
3247 * when rounding the final digit up. This is often faster.
3248 * 3. Under the assumption that input will be rounded nearest,
3249 * mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
3250 * That is, we allow equality in stopping tests when the
3251 * round-nearest rule will give the same floating-point value
3252 * as would satisfaction of the stopping test with strict
3253 * inequality.
3254 * 4. We remove common factors of powers of 2 from relevant
3255 * quantities.
3256 * 5. When converting floating-point integers less than 1e16,
3257 * we use floating-point arithmetic rather than resorting
3258 * to multiple-precision integers.
3259 * 6. When asked to produce fewer than 15 digits, we first try
3260 * to get by with floating-point arithmetic; we resort to
3261 * multiple-precision integer arithmetic only if we cannot
3262 * guarantee that the floating-point calculation has given
3263 * the correctly rounded result. For k requested digits and
3264 * "uniformly" distributed input, the probability is
3265 * something like 10^(k-15) that we must resort to the Long
3266 * calculation.
3269 char *
3270 dtoa(double d, int mode, int ndigits, int *decpt, int *sign, char **rve)
3272 /* Arguments ndigits, decpt, sign are similar to those
3273 of ecvt and fcvt; trailing zeros are suppressed from
3274 the returned string. If not null, *rve is set to point
3275 to the end of the return value. If d is +-Infinity or NaN,
3276 then *decpt is set to 9999.
3278 mode:
3279 0 ==> shortest string that yields d when read in
3280 and rounded to nearest.
3281 1 ==> like 0, but with Steele & White stopping rule;
3282 e.g. with IEEE P754 arithmetic , mode 0 gives
3283 1e23 whereas mode 1 gives 9.999999999999999e22.
3284 2 ==> max(1,ndigits) significant digits. This gives a
3285 return value similar to that of ecvt, except
3286 that trailing zeros are suppressed.
3287 3 ==> through ndigits past the decimal point. This
3288 gives a return value similar to that from fcvt,
3289 except that trailing zeros are suppressed, and
3290 ndigits can be negative.
3291 4,5 ==> similar to 2 and 3, respectively, but (in
3292 round-nearest mode) with the tests of mode 0 to
3293 possibly return a shorter string that rounds to d.
3294 With IEEE arithmetic and compilation with
3295 -DHonor_FLT_ROUNDS, modes 4 and 5 behave the same
3296 as modes 2 and 3 when FLT_ROUNDS != 1.
3297 6-9 ==> Debugging modes similar to mode - 4: don't try
3298 fast floating-point estimate (if applicable).
3300 Values of mode other than 0-9 are treated as mode 0.
3302 Sufficient space is allocated to the return value
3303 to hold the suppressed trailing zeros.
3306 int bbits, b2, b5, be, dig, i, ieps, ilim, ilim0, ilim1,
3307 j, j1, k, k0, k_check, leftright, m2, m5, s2, s5,
3308 spec_case, try_quick;
3309 Long L;
3310 #ifndef Sudden_Underflow
3311 int denorm;
3312 ULong x;
3313 #endif
3314 Bigint *b, *b1, *delta, *mlo, *mhi, *S;
3315 double d2, ds, eps;
3316 char *s, *s0;
3317 #ifdef Honor_FLT_ROUNDS
3318 int rounding;
3319 #endif
3320 #ifdef SET_INEXACT
3321 int inexact, oldinexact;
3322 #endif
3324 #ifndef MULTIPLE_THREADS
3325 if (dtoa_result) {
3326 freedtoa(dtoa_result);
3327 dtoa_result = 0;
3329 #endif
3331 if (word0(d) & Sign_bit) {
3332 /* set sign for everything, including 0's and NaNs */
3333 *sign = 1;
3334 word0(d) &= ~Sign_bit; /* clear sign bit */
3336 else
3337 *sign = 0;
3339 #if defined(IEEE_Arith) + defined(VAX)
3340 #ifdef IEEE_Arith
3341 if ((word0(d) & Exp_mask) == Exp_mask)
3342 #else
3343 if (word0(d) == 0x8000)
3344 #endif
3346 /* Infinity or NaN */
3347 *decpt = 9999;
3348 #ifdef IEEE_Arith
3349 if (!word1(d) && !(word0(d) & 0xfffff))
3350 return nrv_alloc("Infinity", rve, 8);
3351 #endif
3352 return nrv_alloc("NaN", rve, 3);
3354 #endif
3355 #ifdef IBM
3356 dval(d) += 0; /* normalize */
3357 #endif
3358 if (!dval(d)) {
3359 *decpt = 1;
3360 return nrv_alloc("0", rve, 1);
3363 #ifdef SET_INEXACT
3364 try_quick = oldinexact = get_inexact();
3365 inexact = 1;
3366 #endif
3367 #ifdef Honor_FLT_ROUNDS
3368 if ((rounding = Flt_Rounds) >= 2) {
3369 if (*sign)
3370 rounding = rounding == 2 ? 0 : 2;
3371 else
3372 if (rounding != 2)
3373 rounding = 0;
3375 #endif
3377 b = d2b(dval(d), &be, &bbits);
3378 #ifdef Sudden_Underflow
3379 i = (int)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1));
3380 #else
3381 if ((i = (int)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1))) != 0) {
3382 #endif
3383 dval(d2) = dval(d);
3384 word0(d2) &= Frac_mask1;
3385 word0(d2) |= Exp_11;
3386 #ifdef IBM
3387 if (j = 11 - hi0bits(word0(d2) & Frac_mask))
3388 dval(d2) /= 1 << j;
3389 #endif
3391 /* log(x) ~=~ log(1.5) + (x-1.5)/1.5
3392 * log10(x) = log(x) / log(10)
3393 * ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
3394 * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2)
3396 * This suggests computing an approximation k to log10(d) by
3398 * k = (i - Bias)*0.301029995663981
3399 * + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
3401 * We want k to be too large rather than too small.
3402 * The error in the first-order Taylor series approximation
3403 * is in our favor, so we just round up the constant enough
3404 * to compensate for any error in the multiplication of
3405 * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
3406 * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
3407 * adding 1e-13 to the constant term more than suffices.
3408 * Hence we adjust the constant term to 0.1760912590558.
3409 * (We could get a more accurate k by invoking log10,
3410 * but this is probably not worthwhile.)
3413 i -= Bias;
3414 #ifdef IBM
3415 i <<= 2;
3416 i += j;
3417 #endif
3418 #ifndef Sudden_Underflow
3419 denorm = 0;
3421 else {
3422 /* d is denormalized */
3424 i = bbits + be + (Bias + (P-1) - 1);
3425 x = i > 32 ? word0(d) << (64 - i) | word1(d) >> (i - 32)
3426 : word1(d) << (32 - i);
3427 dval(d2) = x;
3428 word0(d2) -= 31*Exp_msk1; /* adjust exponent */
3429 i -= (Bias + (P-1) - 1) + 1;
3430 denorm = 1;
3432 #endif
3433 ds = (dval(d2)-1.5)*0.289529654602168 + 0.1760912590558 + i*0.301029995663981;
3434 k = (int)ds;
3435 if (ds < 0. && ds != k)
3436 k--; /* want k = floor(ds) */
3437 k_check = 1;
3438 if (k >= 0 && k <= Ten_pmax) {
3439 if (dval(d) < tens[k])
3440 k--;
3441 k_check = 0;
3443 j = bbits - i - 1;
3444 if (j >= 0) {
3445 b2 = 0;
3446 s2 = j;
3448 else {
3449 b2 = -j;
3450 s2 = 0;
3452 if (k >= 0) {
3453 b5 = 0;
3454 s5 = k;
3455 s2 += k;
3457 else {
3458 b2 -= k;
3459 b5 = -k;
3460 s5 = 0;
3462 if (mode < 0 || mode > 9)
3463 mode = 0;
3465 #ifndef SET_INEXACT
3466 #ifdef Check_FLT_ROUNDS
3467 try_quick = Rounding == 1;
3468 #else
3469 try_quick = 1;
3470 #endif
3471 #endif /*SET_INEXACT*/
3473 if (mode > 5) {
3474 mode -= 4;
3475 try_quick = 0;
3477 leftright = 1;
3478 ilim = ilim1 = -1;
3479 switch (mode) {
3480 case 0:
3481 case 1:
3482 i = 18;
3483 ndigits = 0;
3484 break;
3485 case 2:
3486 leftright = 0;
3487 /* no break */
3488 case 4:
3489 if (ndigits <= 0)
3490 ndigits = 1;
3491 ilim = ilim1 = i = ndigits;
3492 break;
3493 case 3:
3494 leftright = 0;
3495 /* no break */
3496 case 5:
3497 i = ndigits + k + 1;
3498 ilim = i;
3499 ilim1 = i - 1;
3500 if (i <= 0)
3501 i = 1;
3503 s = s0 = rv_alloc(i);
3505 #ifdef Honor_FLT_ROUNDS
3506 if (mode > 1 && rounding != 1)
3507 leftright = 0;
3508 #endif
3510 if (ilim >= 0 && ilim <= Quick_max && try_quick) {
3512 /* Try to get by with floating-point arithmetic. */
3514 i = 0;
3515 dval(d2) = dval(d);
3516 k0 = k;
3517 ilim0 = ilim;
3518 ieps = 2; /* conservative */
3519 if (k > 0) {
3520 ds = tens[k&0xf];
3521 j = k >> 4;
3522 if (j & Bletch) {
3523 /* prevent overflows */
3524 j &= Bletch - 1;
3525 dval(d) /= bigtens[n_bigtens-1];
3526 ieps++;
3528 for (; j; j >>= 1, i++)
3529 if (j & 1) {
3530 ieps++;
3531 ds *= bigtens[i];
3533 dval(d) /= ds;
3535 else if ((j1 = -k) != 0) {
3536 dval(d) *= tens[j1 & 0xf];
3537 for (j = j1 >> 4; j; j >>= 1, i++)
3538 if (j & 1) {
3539 ieps++;
3540 dval(d) *= bigtens[i];
3543 if (k_check && dval(d) < 1. && ilim > 0) {
3544 if (ilim1 <= 0)
3545 goto fast_failed;
3546 ilim = ilim1;
3547 k--;
3548 dval(d) *= 10.;
3549 ieps++;
3551 dval(eps) = ieps*dval(d) + 7.;
3552 word0(eps) -= (P-1)*Exp_msk1;
3553 if (ilim == 0) {
3554 S = mhi = 0;
3555 dval(d) -= 5.;
3556 if (dval(d) > dval(eps))
3557 goto one_digit;
3558 if (dval(d) < -dval(eps))
3559 goto no_digits;
3560 goto fast_failed;
3562 #ifndef No_leftright
3563 if (leftright) {
3564 /* Use Steele & White method of only
3565 * generating digits needed.
3567 dval(eps) = 0.5/tens[ilim-1] - dval(eps);
3568 for (i = 0;;) {
3569 L = dval(d);
3570 dval(d) -= L;
3571 *s++ = '0' + (int)L;
3572 if (dval(d) < dval(eps))
3573 goto ret1;
3574 if (1. - dval(d) < dval(eps))
3575 goto bump_up;
3576 if (++i >= ilim)
3577 break;
3578 dval(eps) *= 10.;
3579 dval(d) *= 10.;
3582 else {
3583 #endif
3584 /* Generate ilim digits, then fix them up. */
3585 dval(eps) *= tens[ilim-1];
3586 for (i = 1;; i++, dval(d) *= 10.) {
3587 L = (Long)(dval(d));
3588 if (!(dval(d) -= L))
3589 ilim = i;
3590 *s++ = '0' + (int)L;
3591 if (i == ilim) {
3592 if (dval(d) > 0.5 + dval(eps))
3593 goto bump_up;
3594 else if (dval(d) < 0.5 - dval(eps)) {
3595 while (*--s == '0') ;
3596 s++;
3597 goto ret1;
3599 break;
3602 #ifndef No_leftright
3604 #endif
3605 fast_failed:
3606 s = s0;
3607 dval(d) = dval(d2);
3608 k = k0;
3609 ilim = ilim0;
3612 /* Do we have a "small" integer? */
3614 if (be >= 0 && k <= Int_max) {
3615 /* Yes. */
3616 ds = tens[k];
3617 if (ndigits < 0 && ilim <= 0) {
3618 S = mhi = 0;
3619 if (ilim < 0 || dval(d) <= 5*ds)
3620 goto no_digits;
3621 goto one_digit;
3623 for (i = 1;; i++, dval(d) *= 10.) {
3624 L = (Long)(dval(d) / ds);
3625 dval(d) -= L*ds;
3626 #ifdef Check_FLT_ROUNDS
3627 /* If FLT_ROUNDS == 2, L will usually be high by 1 */
3628 if (dval(d) < 0) {
3629 L--;
3630 dval(d) += ds;
3632 #endif
3633 *s++ = '0' + (int)L;
3634 if (!dval(d)) {
3635 #ifdef SET_INEXACT
3636 inexact = 0;
3637 #endif
3638 break;
3640 if (i == ilim) {
3641 #ifdef Honor_FLT_ROUNDS
3642 if (mode > 1)
3643 switch (rounding) {
3644 case 0: goto ret1;
3645 case 2: goto bump_up;
3647 #endif
3648 dval(d) += dval(d);
3649 if (dval(d) > ds || (dval(d) == ds && (L & 1))) {
3650 bump_up:
3651 while (*--s == '9')
3652 if (s == s0) {
3653 k++;
3654 *s = '0';
3655 break;
3657 ++*s++;
3659 break;
3662 goto ret1;
3665 m2 = b2;
3666 m5 = b5;
3667 mhi = mlo = 0;
3668 if (leftright) {
3670 #ifndef Sudden_Underflow
3671 denorm ? be + (Bias + (P-1) - 1 + 1) :
3672 #endif
3673 #ifdef IBM
3674 1 + 4*P - 3 - bbits + ((bbits + be - 1) & 3);
3675 #else
3676 1 + P - bbits;
3677 #endif
3678 b2 += i;
3679 s2 += i;
3680 mhi = i2b(1);
3682 if (m2 > 0 && s2 > 0) {
3683 i = m2 < s2 ? m2 : s2;
3684 b2 -= i;
3685 m2 -= i;
3686 s2 -= i;
3688 if (b5 > 0) {
3689 if (leftright) {
3690 if (m5 > 0) {
3691 mhi = pow5mult(mhi, m5);
3692 b1 = mult(mhi, b);
3693 Bfree(b);
3694 b = b1;
3696 if ((j = b5 - m5) != 0)
3697 b = pow5mult(b, j);
3699 else
3700 b = pow5mult(b, b5);
3702 S = i2b(1);
3703 if (s5 > 0)
3704 S = pow5mult(S, s5);
3706 /* Check for special case that d is a normalized power of 2. */
3708 spec_case = 0;
3709 if ((mode < 2 || leftright)
3710 #ifdef Honor_FLT_ROUNDS
3711 && rounding == 1
3712 #endif
3714 if (!word1(d) && !(word0(d) & Bndry_mask)
3715 #ifndef Sudden_Underflow
3716 && word0(d) & (Exp_mask & ~Exp_msk1)
3717 #endif
3719 /* The special case */
3720 b2 += Log2P;
3721 s2 += Log2P;
3722 spec_case = 1;
3726 /* Arrange for convenient computation of quotients:
3727 * shift left if necessary so divisor has 4 leading 0 bits.
3729 * Perhaps we should just compute leading 28 bits of S once
3730 * and for all and pass them and a shift to quorem, so it
3731 * can do shifts and ors to compute the numerator for q.
3733 #ifdef Pack_32
3734 if ((i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0x1f) != 0)
3735 i = 32 - i;
3736 #else
3737 if ((i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0xf) != 0)
3738 i = 16 - i;
3739 #endif
3740 if (i > 4) {
3741 i -= 4;
3742 b2 += i;
3743 m2 += i;
3744 s2 += i;
3746 else if (i < 4) {
3747 i += 28;
3748 b2 += i;
3749 m2 += i;
3750 s2 += i;
3752 if (b2 > 0)
3753 b = lshift(b, b2);
3754 if (s2 > 0)
3755 S = lshift(S, s2);
3756 if (k_check) {
3757 if (cmp(b,S) < 0) {
3758 k--;
3759 b = multadd(b, 10, 0); /* we botched the k estimate */
3760 if (leftright)
3761 mhi = multadd(mhi, 10, 0);
3762 ilim = ilim1;
3765 if (ilim <= 0 && (mode == 3 || mode == 5)) {
3766 if (ilim < 0 || cmp(b,S = multadd(S,5,0)) <= 0) {
3767 /* no digits, fcvt style */
3768 no_digits:
3769 k = -1 - ndigits;
3770 goto ret;
3772 one_digit:
3773 *s++ = '1';
3774 k++;
3775 goto ret;
3777 if (leftright) {
3778 if (m2 > 0)
3779 mhi = lshift(mhi, m2);
3781 /* Compute mlo -- check for special case
3782 * that d is a normalized power of 2.
3785 mlo = mhi;
3786 if (spec_case) {
3787 mhi = Balloc(mhi->k);
3788 Bcopy(mhi, mlo);
3789 mhi = lshift(mhi, Log2P);
3792 for (i = 1;;i++) {
3793 dig = quorem(b,S) + '0';
3794 /* Do we yet have the shortest decimal string
3795 * that will round to d?
3797 j = cmp(b, mlo);
3798 delta = diff(S, mhi);
3799 j1 = delta->sign ? 1 : cmp(b, delta);
3800 Bfree(delta);
3801 #ifndef ROUND_BIASED
3802 if (j1 == 0 && mode != 1 && !(word1(d) & 1)
3803 #ifdef Honor_FLT_ROUNDS
3804 && rounding >= 1
3805 #endif
3807 if (dig == '9')
3808 goto round_9_up;
3809 if (j > 0)
3810 dig++;
3811 #ifdef SET_INEXACT
3812 else if (!b->x[0] && b->wds <= 1)
3813 inexact = 0;
3814 #endif
3815 *s++ = dig;
3816 goto ret;
3818 #endif
3819 if (j < 0 || (j == 0 && mode != 1
3820 #ifndef ROUND_BIASED
3821 && !(word1(d) & 1)
3822 #endif
3823 )) {
3824 if (!b->x[0] && b->wds <= 1) {
3825 #ifdef SET_INEXACT
3826 inexact = 0;
3827 #endif
3828 goto accept_dig;
3830 #ifdef Honor_FLT_ROUNDS
3831 if (mode > 1)
3832 switch (rounding) {
3833 case 0: goto accept_dig;
3834 case 2: goto keep_dig;
3836 #endif /*Honor_FLT_ROUNDS*/
3837 if (j1 > 0) {
3838 b = lshift(b, 1);
3839 j1 = cmp(b, S);
3840 if ((j1 > 0 || (j1 == 0 && (dig & 1))) && dig++ == '9')
3841 goto round_9_up;
3843 accept_dig:
3844 *s++ = dig;
3845 goto ret;
3847 if (j1 > 0) {
3848 #ifdef Honor_FLT_ROUNDS
3849 if (!rounding)
3850 goto accept_dig;
3851 #endif
3852 if (dig == '9') { /* possible if i == 1 */
3853 round_9_up:
3854 *s++ = '9';
3855 goto roundoff;
3857 *s++ = dig + 1;
3858 goto ret;
3860 #ifdef Honor_FLT_ROUNDS
3861 keep_dig:
3862 #endif
3863 *s++ = dig;
3864 if (i == ilim)
3865 break;
3866 b = multadd(b, 10, 0);
3867 if (mlo == mhi)
3868 mlo = mhi = multadd(mhi, 10, 0);
3869 else {
3870 mlo = multadd(mlo, 10, 0);
3871 mhi = multadd(mhi, 10, 0);
3875 else
3876 for (i = 1;; i++) {
3877 *s++ = dig = quorem(b,S) + '0';
3878 if (!b->x[0] && b->wds <= 1) {
3879 #ifdef SET_INEXACT
3880 inexact = 0;
3881 #endif
3882 goto ret;
3884 if (i >= ilim)
3885 break;
3886 b = multadd(b, 10, 0);
3889 /* Round off last digit */
3891 #ifdef Honor_FLT_ROUNDS
3892 switch (rounding) {
3893 case 0: goto trimzeros;
3894 case 2: goto roundoff;
3896 #endif
3897 b = lshift(b, 1);
3898 j = cmp(b, S);
3899 if (j > 0 || (j == 0 && (dig & 1))) {
3900 roundoff:
3901 while (*--s == '9')
3902 if (s == s0) {
3903 k++;
3904 *s++ = '1';
3905 goto ret;
3907 ++*s++;
3909 else {
3910 while (*--s == '0') ;
3911 s++;
3913 ret:
3914 Bfree(S);
3915 if (mhi) {
3916 if (mlo && mlo != mhi)
3917 Bfree(mlo);
3918 Bfree(mhi);
3920 ret1:
3921 #ifdef SET_INEXACT
3922 if (inexact) {
3923 if (!oldinexact) {
3924 word0(d) = Exp_1 + (70 << Exp_shift);
3925 word1(d) = 0;
3926 dval(d) += 1.;
3929 else if (!oldinexact)
3930 clear_inexact();
3931 #endif
3932 Bfree(b);
3933 *s = 0;
3934 *decpt = k + 1;
3935 if (rve)
3936 *rve = s;
3937 return s0;
3940 void
3941 ruby_each_words(const char *str, void (*func)(const char*, int, void*), void *arg)
3943 const char *end;
3944 int len;
3946 if (!str) return;
3947 for (; *str; str = end) {
3948 while (ISSPACE(*str) || *str == ',') str++;
3949 if (!*str) break;
3950 end = str;
3951 while (*end && !ISSPACE(*end) && *end != ',') end++;
3952 len = end - str;
3953 (*func)(str, len, arg);
3957 #ifdef __cplusplus
3959 #endif