* encoding.c (rb_filesystem_encoding): use default external encoding
[ruby-svn.git] / util.c
blob24841d6bef1e8fbaa7dd2903f2b433e4900aeb81
1 /**********************************************************************
3 util.c -
5 $Author$
6 created at: Fri Mar 10 17:22:34 JST 1995
8 Copyright (C) 1993-2008 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 const 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 xfree(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 xfree(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 #ifdef Bad_float_h
1005 #ifdef IEEE_Arith
1006 #define DBL_DIG 15
1007 #define DBL_MAX_10_EXP 308
1008 #define DBL_MAX_EXP 1024
1009 #define FLT_RADIX 2
1010 #endif /*IEEE_Arith*/
1012 #ifdef IBM
1013 #define DBL_DIG 16
1014 #define DBL_MAX_10_EXP 75
1015 #define DBL_MAX_EXP 63
1016 #define FLT_RADIX 16
1017 #define DBL_MAX 7.2370055773322621e+75
1018 #endif
1020 #ifdef VAX
1021 #define DBL_DIG 16
1022 #define DBL_MAX_10_EXP 38
1023 #define DBL_MAX_EXP 127
1024 #define FLT_RADIX 2
1025 #define DBL_MAX 1.7014118346046923e+38
1026 #endif
1028 #ifndef LONG_MAX
1029 #define LONG_MAX 2147483647
1030 #endif
1032 #else /* ifndef Bad_float_h */
1033 #include "float.h"
1034 #endif /* Bad_float_h */
1036 #ifndef __MATH_H__
1037 #include "math.h"
1038 #endif
1040 #ifdef __cplusplus
1041 extern "C" {
1042 #endif
1044 #if defined(IEEE_LITTLE_ENDIAN) + defined(IEEE_BIG_ENDIAN) + defined(VAX) + defined(IBM) != 1
1045 Exactly one of IEEE_LITTLE_ENDIAN, IEEE_BIG_ENDIAN, VAX, or IBM should be defined.
1046 #endif
1048 typedef union { double d; ULong L[2]; } U;
1050 #ifdef YES_ALIAS
1051 #define dval(x) x
1052 #ifdef IEEE_LITTLE_ENDIAN
1053 #define word0(x) ((ULong *)&x)[1]
1054 #define word1(x) ((ULong *)&x)[0]
1055 #else
1056 #define word0(x) ((ULong *)&x)[0]
1057 #define word1(x) ((ULong *)&x)[1]
1058 #endif
1059 #else
1060 #ifdef IEEE_LITTLE_ENDIAN
1061 #define word0(x) ((U*)&x)->L[1]
1062 #define word1(x) ((U*)&x)->L[0]
1063 #else
1064 #define word0(x) ((U*)&x)->L[0]
1065 #define word1(x) ((U*)&x)->L[1]
1066 #endif
1067 #define dval(x) ((U*)&x)->d
1068 #endif
1070 /* The following definition of Storeinc is appropriate for MIPS processors.
1071 * An alternative that might be better on some machines is
1072 * #define Storeinc(a,b,c) (*a++ = b << 16 | c & 0xffff)
1074 #if defined(IEEE_LITTLE_ENDIAN) + defined(VAX) + defined(__arm__)
1075 #define Storeinc(a,b,c) (((unsigned short *)a)[1] = (unsigned short)b, \
1076 ((unsigned short *)a)[0] = (unsigned short)c, a++)
1077 #else
1078 #define Storeinc(a,b,c) (((unsigned short *)a)[0] = (unsigned short)b, \
1079 ((unsigned short *)a)[1] = (unsigned short)c, a++)
1080 #endif
1082 /* #define P DBL_MANT_DIG */
1083 /* Ten_pmax = floor(P*log(2)/log(5)) */
1084 /* Bletch = (highest power of 2 < DBL_MAX_10_EXP) / 16 */
1085 /* Quick_max = floor((P-1)*log(FLT_RADIX)/log(10) - 1) */
1086 /* Int_max = floor(P*log(FLT_RADIX)/log(10) - 1) */
1088 #ifdef IEEE_Arith
1089 #define Exp_shift 20
1090 #define Exp_shift1 20
1091 #define Exp_msk1 0x100000
1092 #define Exp_msk11 0x100000
1093 #define Exp_mask 0x7ff00000
1094 #define P 53
1095 #define Bias 1023
1096 #define Emin (-1022)
1097 #define Exp_1 0x3ff00000
1098 #define Exp_11 0x3ff00000
1099 #define Ebits 11
1100 #define Frac_mask 0xfffff
1101 #define Frac_mask1 0xfffff
1102 #define Ten_pmax 22
1103 #define Bletch 0x10
1104 #define Bndry_mask 0xfffff
1105 #define Bndry_mask1 0xfffff
1106 #define LSB 1
1107 #define Sign_bit 0x80000000
1108 #define Log2P 1
1109 #define Tiny0 0
1110 #define Tiny1 1
1111 #define Quick_max 14
1112 #define Int_max 14
1113 #ifndef NO_IEEE_Scale
1114 #define Avoid_Underflow
1115 #ifdef Flush_Denorm /* debugging option */
1116 #undef Sudden_Underflow
1117 #endif
1118 #endif
1120 #ifndef Flt_Rounds
1121 #ifdef FLT_ROUNDS
1122 #define Flt_Rounds FLT_ROUNDS
1123 #else
1124 #define Flt_Rounds 1
1125 #endif
1126 #endif /*Flt_Rounds*/
1128 #ifdef Honor_FLT_ROUNDS
1129 #define Rounding rounding
1130 #undef Check_FLT_ROUNDS
1131 #define Check_FLT_ROUNDS
1132 #else
1133 #define Rounding Flt_Rounds
1134 #endif
1136 #else /* ifndef IEEE_Arith */
1137 #undef Check_FLT_ROUNDS
1138 #undef Honor_FLT_ROUNDS
1139 #undef SET_INEXACT
1140 #undef Sudden_Underflow
1141 #define Sudden_Underflow
1142 #ifdef IBM
1143 #undef Flt_Rounds
1144 #define Flt_Rounds 0
1145 #define Exp_shift 24
1146 #define Exp_shift1 24
1147 #define Exp_msk1 0x1000000
1148 #define Exp_msk11 0x1000000
1149 #define Exp_mask 0x7f000000
1150 #define P 14
1151 #define Bias 65
1152 #define Exp_1 0x41000000
1153 #define Exp_11 0x41000000
1154 #define Ebits 8 /* exponent has 7 bits, but 8 is the right value in b2d */
1155 #define Frac_mask 0xffffff
1156 #define Frac_mask1 0xffffff
1157 #define Bletch 4
1158 #define Ten_pmax 22
1159 #define Bndry_mask 0xefffff
1160 #define Bndry_mask1 0xffffff
1161 #define LSB 1
1162 #define Sign_bit 0x80000000
1163 #define Log2P 4
1164 #define Tiny0 0x100000
1165 #define Tiny1 0
1166 #define Quick_max 14
1167 #define Int_max 15
1168 #else /* VAX */
1169 #undef Flt_Rounds
1170 #define Flt_Rounds 1
1171 #define Exp_shift 23
1172 #define Exp_shift1 7
1173 #define Exp_msk1 0x80
1174 #define Exp_msk11 0x800000
1175 #define Exp_mask 0x7f80
1176 #define P 56
1177 #define Bias 129
1178 #define Exp_1 0x40800000
1179 #define Exp_11 0x4080
1180 #define Ebits 8
1181 #define Frac_mask 0x7fffff
1182 #define Frac_mask1 0xffff007f
1183 #define Ten_pmax 24
1184 #define Bletch 2
1185 #define Bndry_mask 0xffff007f
1186 #define Bndry_mask1 0xffff007f
1187 #define LSB 0x10000
1188 #define Sign_bit 0x8000
1189 #define Log2P 1
1190 #define Tiny0 0x80
1191 #define Tiny1 0
1192 #define Quick_max 15
1193 #define Int_max 15
1194 #endif /* IBM, VAX */
1195 #endif /* IEEE_Arith */
1197 #ifndef IEEE_Arith
1198 #define ROUND_BIASED
1199 #endif
1201 #ifdef RND_PRODQUOT
1202 #define rounded_product(a,b) a = rnd_prod(a, b)
1203 #define rounded_quotient(a,b) a = rnd_quot(a, b)
1204 extern double rnd_prod(double, double), rnd_quot(double, double);
1205 #else
1206 #define rounded_product(a,b) a *= b
1207 #define rounded_quotient(a,b) a /= b
1208 #endif
1210 #define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
1211 #define Big1 0xffffffff
1213 #ifndef Pack_32
1214 #define Pack_32
1215 #endif
1217 #define FFFFFFFF 0xffffffffUL
1219 #ifdef NO_LONG_LONG
1220 #undef ULLong
1221 #ifdef Just_16
1222 #undef Pack_32
1223 /* When Pack_32 is not defined, we store 16 bits per 32-bit Long.
1224 * This makes some inner loops simpler and sometimes saves work
1225 * during multiplications, but it often seems to make things slightly
1226 * slower. Hence the default is now to store 32 bits per Long.
1228 #endif
1229 #else /* long long available */
1230 #ifndef Llong
1231 #define Llong long long
1232 #endif
1233 #ifndef ULLong
1234 #define ULLong unsigned Llong
1235 #endif
1236 #endif /* NO_LONG_LONG */
1238 #define MULTIPLE_THREADS 1
1240 #ifndef MULTIPLE_THREADS
1241 #define ACQUIRE_DTOA_LOCK(n) /*nothing*/
1242 #define FREE_DTOA_LOCK(n) /*nothing*/
1243 #else
1244 #define ACQUIRE_DTOA_LOCK(n) /*unused right now*/
1245 #define FREE_DTOA_LOCK(n) /*unused right now*/
1246 #endif
1248 #define Kmax 15
1250 struct Bigint {
1251 struct Bigint *next;
1252 int k, maxwds, sign, wds;
1253 ULong x[1];
1256 typedef struct Bigint Bigint;
1258 static Bigint *freelist[Kmax+1];
1260 static Bigint *
1261 Balloc(int k)
1263 int x;
1264 Bigint *rv;
1265 #ifndef Omit_Private_Memory
1266 unsigned int len;
1267 #endif
1269 ACQUIRE_DTOA_LOCK(0);
1270 if ((rv = freelist[k]) != 0) {
1271 freelist[k] = rv->next;
1273 else {
1274 x = 1 << k;
1275 #ifdef Omit_Private_Memory
1276 rv = (Bigint *)MALLOC(sizeof(Bigint) + (x-1)*sizeof(ULong));
1277 #else
1278 len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)
1279 /sizeof(double);
1280 if (pmem_next - private_mem + len <= PRIVATE_mem) {
1281 rv = (Bigint*)pmem_next;
1282 pmem_next += len;
1284 else
1285 rv = (Bigint*)MALLOC(len*sizeof(double));
1286 #endif
1287 rv->k = k;
1288 rv->maxwds = x;
1290 FREE_DTOA_LOCK(0);
1291 rv->sign = rv->wds = 0;
1292 return rv;
1295 static void
1296 Bfree(Bigint *v)
1298 if (v) {
1299 ACQUIRE_DTOA_LOCK(0);
1300 v->next = freelist[v->k];
1301 freelist[v->k] = v;
1302 FREE_DTOA_LOCK(0);
1306 #define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign, \
1307 y->wds*sizeof(Long) + 2*sizeof(int))
1309 static Bigint *
1310 multadd(Bigint *b, int m, int a) /* multiply by m and add a */
1312 int i, wds;
1313 #ifdef ULLong
1314 ULong *x;
1315 ULLong carry, y;
1316 #else
1317 ULong carry, *x, y;
1318 #ifdef Pack_32
1319 ULong xi, z;
1320 #endif
1321 #endif
1322 Bigint *b1;
1324 wds = b->wds;
1325 x = b->x;
1326 i = 0;
1327 carry = a;
1328 do {
1329 #ifdef ULLong
1330 y = *x * (ULLong)m + carry;
1331 carry = y >> 32;
1332 *x++ = y & FFFFFFFF;
1333 #else
1334 #ifdef Pack_32
1335 xi = *x;
1336 y = (xi & 0xffff) * m + carry;
1337 z = (xi >> 16) * m + (y >> 16);
1338 carry = z >> 16;
1339 *x++ = (z << 16) + (y & 0xffff);
1340 #else
1341 y = *x * m + carry;
1342 carry = y >> 16;
1343 *x++ = y & 0xffff;
1344 #endif
1345 #endif
1346 } while (++i < wds);
1347 if (carry) {
1348 if (wds >= b->maxwds) {
1349 b1 = Balloc(b->k+1);
1350 Bcopy(b1, b);
1351 Bfree(b);
1352 b = b1;
1354 b->x[wds++] = carry;
1355 b->wds = wds;
1357 return b;
1360 static Bigint *
1361 s2b(const char *s, int nd0, int nd, ULong y9)
1363 Bigint *b;
1364 int i, k;
1365 Long x, y;
1367 x = (nd + 8) / 9;
1368 for (k = 0, y = 1; x > y; y <<= 1, k++) ;
1369 #ifdef Pack_32
1370 b = Balloc(k);
1371 b->x[0] = y9;
1372 b->wds = 1;
1373 #else
1374 b = Balloc(k+1);
1375 b->x[0] = y9 & 0xffff;
1376 b->wds = (b->x[1] = y9 >> 16) ? 2 : 1;
1377 #endif
1379 i = 9;
1380 if (9 < nd0) {
1381 s += 9;
1382 do {
1383 b = multadd(b, 10, *s++ - '0');
1384 } while (++i < nd0);
1385 s++;
1387 else
1388 s += 10;
1389 for (; i < nd; i++)
1390 b = multadd(b, 10, *s++ - '0');
1391 return b;
1394 static int
1395 hi0bits(register ULong x)
1397 register int k = 0;
1399 if (!(x & 0xffff0000)) {
1400 k = 16;
1401 x <<= 16;
1403 if (!(x & 0xff000000)) {
1404 k += 8;
1405 x <<= 8;
1407 if (!(x & 0xf0000000)) {
1408 k += 4;
1409 x <<= 4;
1411 if (!(x & 0xc0000000)) {
1412 k += 2;
1413 x <<= 2;
1415 if (!(x & 0x80000000)) {
1416 k++;
1417 if (!(x & 0x40000000))
1418 return 32;
1420 return k;
1423 static int
1424 lo0bits(ULong *y)
1426 register int k;
1427 register ULong x = *y;
1429 if (x & 7) {
1430 if (x & 1)
1431 return 0;
1432 if (x & 2) {
1433 *y = x >> 1;
1434 return 1;
1436 *y = x >> 2;
1437 return 2;
1439 k = 0;
1440 if (!(x & 0xffff)) {
1441 k = 16;
1442 x >>= 16;
1444 if (!(x & 0xff)) {
1445 k += 8;
1446 x >>= 8;
1448 if (!(x & 0xf)) {
1449 k += 4;
1450 x >>= 4;
1452 if (!(x & 0x3)) {
1453 k += 2;
1454 x >>= 2;
1456 if (!(x & 1)) {
1457 k++;
1458 x >>= 1;
1459 if (!x)
1460 return 32;
1462 *y = x;
1463 return k;
1466 static Bigint *
1467 i2b(int i)
1469 Bigint *b;
1471 b = Balloc(1);
1472 b->x[0] = i;
1473 b->wds = 1;
1474 return b;
1477 static Bigint *
1478 mult(Bigint *a, Bigint *b)
1480 Bigint *c;
1481 int k, wa, wb, wc;
1482 ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
1483 ULong y;
1484 #ifdef ULLong
1485 ULLong carry, z;
1486 #else
1487 ULong carry, z;
1488 #ifdef Pack_32
1489 ULong z2;
1490 #endif
1491 #endif
1493 if (a->wds < b->wds) {
1494 c = a;
1495 a = b;
1496 b = c;
1498 k = a->k;
1499 wa = a->wds;
1500 wb = b->wds;
1501 wc = wa + wb;
1502 if (wc > a->maxwds)
1503 k++;
1504 c = Balloc(k);
1505 for (x = c->x, xa = x + wc; x < xa; x++)
1506 *x = 0;
1507 xa = a->x;
1508 xae = xa + wa;
1509 xb = b->x;
1510 xbe = xb + wb;
1511 xc0 = c->x;
1512 #ifdef ULLong
1513 for (; xb < xbe; xc0++) {
1514 if ((y = *xb++) != 0) {
1515 x = xa;
1516 xc = xc0;
1517 carry = 0;
1518 do {
1519 z = *x++ * (ULLong)y + *xc + carry;
1520 carry = z >> 32;
1521 *xc++ = z & FFFFFFFF;
1522 } while (x < xae);
1523 *xc = carry;
1526 #else
1527 #ifdef Pack_32
1528 for (; xb < xbe; xb++, xc0++) {
1529 if (y = *xb & 0xffff) {
1530 x = xa;
1531 xc = xc0;
1532 carry = 0;
1533 do {
1534 z = (*x & 0xffff) * y + (*xc & 0xffff) + carry;
1535 carry = z >> 16;
1536 z2 = (*x++ >> 16) * y + (*xc >> 16) + carry;
1537 carry = z2 >> 16;
1538 Storeinc(xc, z2, z);
1539 } while (x < xae);
1540 *xc = carry;
1542 if (y = *xb >> 16) {
1543 x = xa;
1544 xc = xc0;
1545 carry = 0;
1546 z2 = *xc;
1547 do {
1548 z = (*x & 0xffff) * y + (*xc >> 16) + carry;
1549 carry = z >> 16;
1550 Storeinc(xc, z, z2);
1551 z2 = (*x++ >> 16) * y + (*xc & 0xffff) + carry;
1552 carry = z2 >> 16;
1553 } while (x < xae);
1554 *xc = z2;
1557 #else
1558 for (; xb < xbe; xc0++) {
1559 if (y = *xb++) {
1560 x = xa;
1561 xc = xc0;
1562 carry = 0;
1563 do {
1564 z = *x++ * y + *xc + carry;
1565 carry = z >> 16;
1566 *xc++ = z & 0xffff;
1567 } while (x < xae);
1568 *xc = carry;
1571 #endif
1572 #endif
1573 for (xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ;
1574 c->wds = wc;
1575 return c;
1578 static Bigint *p5s;
1580 static Bigint *
1581 pow5mult(Bigint *b, int k)
1583 Bigint *b1, *p5, *p51;
1584 int i;
1585 static int p05[3] = { 5, 25, 125 };
1587 if ((i = k & 3) != 0)
1588 b = multadd(b, p05[i-1], 0);
1590 if (!(k >>= 2))
1591 return b;
1592 if (!(p5 = p5s)) {
1593 /* first time */
1594 #ifdef MULTIPLE_THREADS
1595 ACQUIRE_DTOA_LOCK(1);
1596 if (!(p5 = p5s)) {
1597 p5 = p5s = i2b(625);
1598 p5->next = 0;
1600 FREE_DTOA_LOCK(1);
1601 #else
1602 p5 = p5s = i2b(625);
1603 p5->next = 0;
1604 #endif
1606 for (;;) {
1607 if (k & 1) {
1608 b1 = mult(b, p5);
1609 Bfree(b);
1610 b = b1;
1612 if (!(k >>= 1))
1613 break;
1614 if (!(p51 = p5->next)) {
1615 #ifdef MULTIPLE_THREADS
1616 ACQUIRE_DTOA_LOCK(1);
1617 if (!(p51 = p5->next)) {
1618 p51 = p5->next = mult(p5,p5);
1619 p51->next = 0;
1621 FREE_DTOA_LOCK(1);
1622 #else
1623 p51 = p5->next = mult(p5,p5);
1624 p51->next = 0;
1625 #endif
1627 p5 = p51;
1629 return b;
1632 static Bigint *
1633 lshift(Bigint *b, int k)
1635 int i, k1, n, n1;
1636 Bigint *b1;
1637 ULong *x, *x1, *xe, z;
1639 #ifdef Pack_32
1640 n = k >> 5;
1641 #else
1642 n = k >> 4;
1643 #endif
1644 k1 = b->k;
1645 n1 = n + b->wds + 1;
1646 for (i = b->maxwds; n1 > i; i <<= 1)
1647 k1++;
1648 b1 = Balloc(k1);
1649 x1 = b1->x;
1650 for (i = 0; i < n; i++)
1651 *x1++ = 0;
1652 x = b->x;
1653 xe = x + b->wds;
1654 #ifdef Pack_32
1655 if (k &= 0x1f) {
1656 k1 = 32 - k;
1657 z = 0;
1658 do {
1659 *x1++ = *x << k | z;
1660 z = *x++ >> k1;
1661 } while (x < xe);
1662 if ((*x1 = z) != 0)
1663 ++n1;
1665 #else
1666 if (k &= 0xf) {
1667 k1 = 16 - k;
1668 z = 0;
1669 do {
1670 *x1++ = *x << k & 0xffff | z;
1671 z = *x++ >> k1;
1672 } while (x < xe);
1673 if (*x1 = z)
1674 ++n1;
1676 #endif
1677 else
1678 do {
1679 *x1++ = *x++;
1680 } while (x < xe);
1681 b1->wds = n1 - 1;
1682 Bfree(b);
1683 return b1;
1686 static int
1687 cmp(Bigint *a, Bigint *b)
1689 ULong *xa, *xa0, *xb, *xb0;
1690 int i, j;
1692 i = a->wds;
1693 j = b->wds;
1694 #ifdef DEBUG
1695 if (i > 1 && !a->x[i-1])
1696 Bug("cmp called with a->x[a->wds-1] == 0");
1697 if (j > 1 && !b->x[j-1])
1698 Bug("cmp called with b->x[b->wds-1] == 0");
1699 #endif
1700 if (i -= j)
1701 return i;
1702 xa0 = a->x;
1703 xa = xa0 + j;
1704 xb0 = b->x;
1705 xb = xb0 + j;
1706 for (;;) {
1707 if (*--xa != *--xb)
1708 return *xa < *xb ? -1 : 1;
1709 if (xa <= xa0)
1710 break;
1712 return 0;
1715 static Bigint *
1716 diff(Bigint *a, Bigint *b)
1718 Bigint *c;
1719 int i, wa, wb;
1720 ULong *xa, *xae, *xb, *xbe, *xc;
1721 #ifdef ULLong
1722 ULLong borrow, y;
1723 #else
1724 ULong borrow, y;
1725 #ifdef Pack_32
1726 ULong z;
1727 #endif
1728 #endif
1730 i = cmp(a,b);
1731 if (!i) {
1732 c = Balloc(0);
1733 c->wds = 1;
1734 c->x[0] = 0;
1735 return c;
1737 if (i < 0) {
1738 c = a;
1739 a = b;
1740 b = c;
1741 i = 1;
1743 else
1744 i = 0;
1745 c = Balloc(a->k);
1746 c->sign = i;
1747 wa = a->wds;
1748 xa = a->x;
1749 xae = xa + wa;
1750 wb = b->wds;
1751 xb = b->x;
1752 xbe = xb + wb;
1753 xc = c->x;
1754 borrow = 0;
1755 #ifdef ULLong
1756 do {
1757 y = (ULLong)*xa++ - *xb++ - borrow;
1758 borrow = y >> 32 & (ULong)1;
1759 *xc++ = y & FFFFFFFF;
1760 } while (xb < xbe);
1761 while (xa < xae) {
1762 y = *xa++ - borrow;
1763 borrow = y >> 32 & (ULong)1;
1764 *xc++ = y & FFFFFFFF;
1766 #else
1767 #ifdef Pack_32
1768 do {
1769 y = (*xa & 0xffff) - (*xb & 0xffff) - borrow;
1770 borrow = (y & 0x10000) >> 16;
1771 z = (*xa++ >> 16) - (*xb++ >> 16) - borrow;
1772 borrow = (z & 0x10000) >> 16;
1773 Storeinc(xc, z, y);
1774 } while (xb < xbe);
1775 while (xa < xae) {
1776 y = (*xa & 0xffff) - borrow;
1777 borrow = (y & 0x10000) >> 16;
1778 z = (*xa++ >> 16) - borrow;
1779 borrow = (z & 0x10000) >> 16;
1780 Storeinc(xc, z, y);
1782 #else
1783 do {
1784 y = *xa++ - *xb++ - borrow;
1785 borrow = (y & 0x10000) >> 16;
1786 *xc++ = y & 0xffff;
1787 } while (xb < xbe);
1788 while (xa < xae) {
1789 y = *xa++ - borrow;
1790 borrow = (y & 0x10000) >> 16;
1791 *xc++ = y & 0xffff;
1793 #endif
1794 #endif
1795 while (!*--xc)
1796 wa--;
1797 c->wds = wa;
1798 return c;
1801 static double
1802 ulp(double x)
1804 register Long L;
1805 double a;
1807 L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1;
1808 #ifndef Avoid_Underflow
1809 #ifndef Sudden_Underflow
1810 if (L > 0) {
1811 #endif
1812 #endif
1813 #ifdef IBM
1814 L |= Exp_msk1 >> 4;
1815 #endif
1816 word0(a) = L;
1817 word1(a) = 0;
1818 #ifndef Avoid_Underflow
1819 #ifndef Sudden_Underflow
1821 else {
1822 L = -L >> Exp_shift;
1823 if (L < Exp_shift) {
1824 word0(a) = 0x80000 >> L;
1825 word1(a) = 0;
1827 else {
1828 word0(a) = 0;
1829 L -= Exp_shift;
1830 word1(a) = L >= 31 ? 1 : 1 << 31 - L;
1833 #endif
1834 #endif
1835 return dval(a);
1838 static double
1839 b2d(Bigint *a, int *e)
1841 ULong *xa, *xa0, w, y, z;
1842 int k;
1843 double d;
1844 #ifdef VAX
1845 ULong d0, d1;
1846 #else
1847 #define d0 word0(d)
1848 #define d1 word1(d)
1849 #endif
1851 xa0 = a->x;
1852 xa = xa0 + a->wds;
1853 y = *--xa;
1854 #ifdef DEBUG
1855 if (!y) Bug("zero y in b2d");
1856 #endif
1857 k = hi0bits(y);
1858 *e = 32 - k;
1859 #ifdef Pack_32
1860 if (k < Ebits) {
1861 d0 = Exp_1 | y >> (Ebits - k);
1862 w = xa > xa0 ? *--xa : 0;
1863 d1 = y << ((32-Ebits) + k) | w >> (Ebits - k);
1864 goto ret_d;
1866 z = xa > xa0 ? *--xa : 0;
1867 if (k -= Ebits) {
1868 d0 = Exp_1 | y << k | z >> (32 - k);
1869 y = xa > xa0 ? *--xa : 0;
1870 d1 = z << k | y >> (32 - k);
1872 else {
1873 d0 = Exp_1 | y;
1874 d1 = z;
1876 #else
1877 if (k < Ebits + 16) {
1878 z = xa > xa0 ? *--xa : 0;
1879 d0 = Exp_1 | y << k - Ebits | z >> Ebits + 16 - k;
1880 w = xa > xa0 ? *--xa : 0;
1881 y = xa > xa0 ? *--xa : 0;
1882 d1 = z << k + 16 - Ebits | w << k - Ebits | y >> 16 + Ebits - k;
1883 goto ret_d;
1885 z = xa > xa0 ? *--xa : 0;
1886 w = xa > xa0 ? *--xa : 0;
1887 k -= Ebits + 16;
1888 d0 = Exp_1 | y << k + 16 | z << k | w >> 16 - k;
1889 y = xa > xa0 ? *--xa : 0;
1890 d1 = w << k + 16 | y << k;
1891 #endif
1892 ret_d:
1893 #ifdef VAX
1894 word0(d) = d0 >> 16 | d0 << 16;
1895 word1(d) = d1 >> 16 | d1 << 16;
1896 #else
1897 #undef d0
1898 #undef d1
1899 #endif
1900 return dval(d);
1903 static Bigint *
1904 d2b(double d, int *e, int *bits)
1906 Bigint *b;
1907 int de, k;
1908 ULong *x, y, z;
1909 #ifndef Sudden_Underflow
1910 int i;
1911 #endif
1912 #ifdef VAX
1913 ULong d0, d1;
1914 d0 = word0(d) >> 16 | word0(d) << 16;
1915 d1 = word1(d) >> 16 | word1(d) << 16;
1916 #else
1917 #define d0 word0(d)
1918 #define d1 word1(d)
1919 #endif
1921 #ifdef Pack_32
1922 b = Balloc(1);
1923 #else
1924 b = Balloc(2);
1925 #endif
1926 x = b->x;
1928 z = d0 & Frac_mask;
1929 d0 &= 0x7fffffff; /* clear sign bit, which we ignore */
1930 #ifdef Sudden_Underflow
1931 de = (int)(d0 >> Exp_shift);
1932 #ifndef IBM
1933 z |= Exp_msk11;
1934 #endif
1935 #else
1936 if ((de = (int)(d0 >> Exp_shift)) != 0)
1937 z |= Exp_msk1;
1938 #endif
1939 #ifdef Pack_32
1940 if ((y = d1) != 0) {
1941 if ((k = lo0bits(&y)) != 0) {
1942 x[0] = y | z << (32 - k);
1943 z >>= k;
1945 else
1946 x[0] = y;
1947 #ifndef Sudden_Underflow
1949 #endif
1950 b->wds = (x[1] = z) ? 2 : 1;
1952 else {
1953 #ifdef DEBUG
1954 if (!z)
1955 Bug("Zero passed to d2b");
1956 #endif
1957 k = lo0bits(&z);
1958 x[0] = z;
1959 #ifndef Sudden_Underflow
1961 #endif
1962 b->wds = 1;
1963 k += 32;
1965 #else
1966 if (y = d1) {
1967 if (k = lo0bits(&y))
1968 if (k >= 16) {
1969 x[0] = y | z << 32 - k & 0xffff;
1970 x[1] = z >> k - 16 & 0xffff;
1971 x[2] = z >> k;
1972 i = 2;
1974 else {
1975 x[0] = y & 0xffff;
1976 x[1] = y >> 16 | z << 16 - k & 0xffff;
1977 x[2] = z >> k & 0xffff;
1978 x[3] = z >> k+16;
1979 i = 3;
1981 else {
1982 x[0] = y & 0xffff;
1983 x[1] = y >> 16;
1984 x[2] = z & 0xffff;
1985 x[3] = z >> 16;
1986 i = 3;
1989 else {
1990 #ifdef DEBUG
1991 if (!z)
1992 Bug("Zero passed to d2b");
1993 #endif
1994 k = lo0bits(&z);
1995 if (k >= 16) {
1996 x[0] = z;
1997 i = 0;
1999 else {
2000 x[0] = z & 0xffff;
2001 x[1] = z >> 16;
2002 i = 1;
2004 k += 32;
2006 while (!x[i])
2007 --i;
2008 b->wds = i + 1;
2009 #endif
2010 #ifndef Sudden_Underflow
2011 if (de) {
2012 #endif
2013 #ifdef IBM
2014 *e = (de - Bias - (P-1) << 2) + k;
2015 *bits = 4*P + 8 - k - hi0bits(word0(d) & Frac_mask);
2016 #else
2017 *e = de - Bias - (P-1) + k;
2018 *bits = P - k;
2019 #endif
2020 #ifndef Sudden_Underflow
2022 else {
2023 *e = de - Bias - (P-1) + 1 + k;
2024 #ifdef Pack_32
2025 *bits = 32*i - hi0bits(x[i-1]);
2026 #else
2027 *bits = (i+2)*16 - hi0bits(x[i]);
2028 #endif
2030 #endif
2031 return b;
2033 #undef d0
2034 #undef d1
2036 static double
2037 ratio(Bigint *a, Bigint *b)
2039 double da, db;
2040 int k, ka, kb;
2042 dval(da) = b2d(a, &ka);
2043 dval(db) = b2d(b, &kb);
2044 #ifdef Pack_32
2045 k = ka - kb + 32*(a->wds - b->wds);
2046 #else
2047 k = ka - kb + 16*(a->wds - b->wds);
2048 #endif
2049 #ifdef IBM
2050 if (k > 0) {
2051 word0(da) += (k >> 2)*Exp_msk1;
2052 if (k &= 3)
2053 dval(da) *= 1 << k;
2055 else {
2056 k = -k;
2057 word0(db) += (k >> 2)*Exp_msk1;
2058 if (k &= 3)
2059 dval(db) *= 1 << k;
2061 #else
2062 if (k > 0)
2063 word0(da) += k*Exp_msk1;
2064 else {
2065 k = -k;
2066 word0(db) += k*Exp_msk1;
2068 #endif
2069 return dval(da) / dval(db);
2072 static const double
2073 tens[] = {
2074 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
2075 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
2076 1e20, 1e21, 1e22
2077 #ifdef VAX
2078 , 1e23, 1e24
2079 #endif
2082 static const double
2083 #ifdef IEEE_Arith
2084 bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 };
2085 static const double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128,
2086 #ifdef Avoid_Underflow
2087 9007199254740992.*9007199254740992.e-256
2088 /* = 2^106 * 1e-53 */
2089 #else
2090 1e-256
2091 #endif
2093 /* The factor of 2^53 in tinytens[4] helps us avoid setting the underflow */
2094 /* flag unnecessarily. It leads to a song and dance at the end of strtod. */
2095 #define Scale_Bit 0x10
2096 #define n_bigtens 5
2097 #else
2098 #ifdef IBM
2099 bigtens[] = { 1e16, 1e32, 1e64 };
2100 static const double tinytens[] = { 1e-16, 1e-32, 1e-64 };
2101 #define n_bigtens 3
2102 #else
2103 bigtens[] = { 1e16, 1e32 };
2104 static const double tinytens[] = { 1e-16, 1e-32 };
2105 #define n_bigtens 2
2106 #endif
2107 #endif
2109 #ifndef IEEE_Arith
2110 #undef INFNAN_CHECK
2111 #endif
2113 #ifdef INFNAN_CHECK
2115 #ifndef NAN_WORD0
2116 #define NAN_WORD0 0x7ff80000
2117 #endif
2119 #ifndef NAN_WORD1
2120 #define NAN_WORD1 0
2121 #endif
2123 static int
2124 match(const char **sp, char *t)
2126 int c, d;
2127 const char *s = *sp;
2129 while (d = *t++) {
2130 if ((c = *++s) >= 'A' && c <= 'Z')
2131 c += 'a' - 'A';
2132 if (c != d)
2133 return 0;
2135 *sp = s + 1;
2136 return 1;
2139 #ifndef No_Hex_NaN
2140 static void
2141 hexnan(double *rvp, const char **sp)
2143 ULong c, x[2];
2144 const char *s;
2145 int havedig, udx0, xshift;
2147 x[0] = x[1] = 0;
2148 havedig = xshift = 0;
2149 udx0 = 1;
2150 s = *sp;
2151 while (c = *(const unsigned char*)++s) {
2152 if (c >= '0' && c <= '9')
2153 c -= '0';
2154 else if (c >= 'a' && c <= 'f')
2155 c += 10 - 'a';
2156 else if (c >= 'A' && c <= 'F')
2157 c += 10 - 'A';
2158 else if (c <= ' ') {
2159 if (udx0 && havedig) {
2160 udx0 = 0;
2161 xshift = 1;
2163 continue;
2165 else if (/*(*/ c == ')' && havedig) {
2166 *sp = s + 1;
2167 break;
2169 else
2170 return; /* invalid form: don't change *sp */
2171 havedig = 1;
2172 if (xshift) {
2173 xshift = 0;
2174 x[0] = x[1];
2175 x[1] = 0;
2177 if (udx0)
2178 x[0] = (x[0] << 4) | (x[1] >> 28);
2179 x[1] = (x[1] << 4) | c;
2181 if ((x[0] &= 0xfffff) || x[1]) {
2182 word0(*rvp) = Exp_mask | x[0];
2183 word1(*rvp) = x[1];
2186 #endif /*No_Hex_NaN*/
2187 #endif /* INFNAN_CHECK */
2189 double
2190 ruby_strtod(const char *s00, char **se)
2192 #ifdef Avoid_Underflow
2193 int scale;
2194 #endif
2195 int bb2, bb5, bbe, bd2, bd5, bbbits, bs2, c, dsign,
2196 e, e1, esign, i, j, k, nd, nd0, nf, nz, nz0, sign;
2197 const char *s, *s0, *s1;
2198 double aadj, aadj1, adj, rv, rv0;
2199 Long L;
2200 ULong y, z;
2201 Bigint *bb, *bb1, *bd, *bd0, *bs, *delta;
2202 #ifdef SET_INEXACT
2203 int inexact, oldinexact;
2204 #endif
2205 #ifdef Honor_FLT_ROUNDS
2206 int rounding;
2207 #endif
2208 #ifdef USE_LOCALE
2209 const char *s2;
2210 #endif
2212 errno = 0;
2213 sign = nz0 = nz = 0;
2214 dval(rv) = 0.;
2215 for (s = s00;;s++)
2216 switch (*s) {
2217 case '-':
2218 sign = 1;
2219 /* no break */
2220 case '+':
2221 if (*++s)
2222 goto break2;
2223 /* no break */
2224 case 0:
2225 goto ret0;
2226 case '\t':
2227 case '\n':
2228 case '\v':
2229 case '\f':
2230 case '\r':
2231 case ' ':
2232 continue;
2233 default:
2234 goto break2;
2236 break2:
2237 if (*s == '0') {
2238 nz0 = 1;
2239 while (*++s == '0') ;
2240 if (!*s)
2241 goto ret;
2243 s0 = s;
2244 y = z = 0;
2245 for (nd = nf = 0; (c = *s) >= '0' && c <= '9'; nd++, s++)
2246 if (nd < 9)
2247 y = 10*y + c - '0';
2248 else if (nd < 16)
2249 z = 10*z + c - '0';
2250 nd0 = nd;
2251 #ifdef USE_LOCALE
2252 s1 = localeconv()->decimal_point;
2253 if (c == *s1) {
2254 c = '.';
2255 if (*++s1) {
2256 s2 = s;
2257 for (;;) {
2258 if (*++s2 != *s1) {
2259 c = 0;
2260 break;
2262 if (!*++s1) {
2263 s = s2;
2264 break;
2269 #endif
2270 if (c == '.') {
2271 if (!ISDIGIT(s[1]))
2272 goto dig_done;
2273 c = *++s;
2274 if (!nd) {
2275 for (; c == '0'; c = *++s)
2276 nz++;
2277 if (c > '0' && c <= '9') {
2278 s0 = s;
2279 nf += nz;
2280 nz = 0;
2281 goto have_dig;
2283 goto dig_done;
2285 for (; c >= '0' && c <= '9'; c = *++s) {
2286 have_dig:
2287 nz++;
2288 if (c -= '0') {
2289 nf += nz;
2290 for (i = 1; i < nz; i++)
2291 if (nd++ < 9)
2292 y *= 10;
2293 else if (nd <= DBL_DIG + 1)
2294 z *= 10;
2295 if (nd++ < 9)
2296 y = 10*y + c;
2297 else if (nd <= DBL_DIG + 1)
2298 z = 10*z + c;
2299 nz = 0;
2303 dig_done:
2304 e = 0;
2305 if (c == 'e' || c == 'E') {
2306 if (!nd && !nz && !nz0) {
2307 goto ret0;
2309 s00 = s;
2310 esign = 0;
2311 switch (c = *++s) {
2312 case '-':
2313 esign = 1;
2314 case '+':
2315 c = *++s;
2317 if (c >= '0' && c <= '9') {
2318 while (c == '0')
2319 c = *++s;
2320 if (c > '0' && c <= '9') {
2321 L = c - '0';
2322 s1 = s;
2323 while ((c = *++s) >= '0' && c <= '9')
2324 L = 10*L + c - '0';
2325 if (s - s1 > 8 || L > 19999)
2326 /* Avoid confusion from exponents
2327 * so large that e might overflow.
2329 e = 19999; /* safe for 16 bit ints */
2330 else
2331 e = (int)L;
2332 if (esign)
2333 e = -e;
2335 else
2336 e = 0;
2338 else
2339 s = s00;
2341 if (!nd) {
2342 if (!nz && !nz0) {
2343 #ifdef INFNAN_CHECK
2344 /* Check for Nan and Infinity */
2345 switch (c) {
2346 case 'i':
2347 case 'I':
2348 if (match(&s,"nf")) {
2349 --s;
2350 if (!match(&s,"inity"))
2351 ++s;
2352 word0(rv) = 0x7ff00000;
2353 word1(rv) = 0;
2354 goto ret;
2356 break;
2357 case 'n':
2358 case 'N':
2359 if (match(&s, "an")) {
2360 word0(rv) = NAN_WORD0;
2361 word1(rv) = NAN_WORD1;
2362 #ifndef No_Hex_NaN
2363 if (*s == '(') /*)*/
2364 hexnan(&rv, &s);
2365 #endif
2366 goto ret;
2369 #endif /* INFNAN_CHECK */
2370 ret0:
2371 s = s00;
2372 sign = 0;
2374 goto ret;
2376 e1 = e -= nf;
2378 /* Now we have nd0 digits, starting at s0, followed by a
2379 * decimal point, followed by nd-nd0 digits. The number we're
2380 * after is the integer represented by those digits times
2381 * 10**e */
2383 if (!nd0)
2384 nd0 = nd;
2385 k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;
2386 dval(rv) = y;
2387 if (k > 9) {
2388 #ifdef SET_INEXACT
2389 if (k > DBL_DIG)
2390 oldinexact = get_inexact();
2391 #endif
2392 dval(rv) = tens[k - 9] * dval(rv) + z;
2394 bd0 = bb = bd = bs = delta = 0;
2395 if (nd <= DBL_DIG
2396 #ifndef RND_PRODQUOT
2397 #ifndef Honor_FLT_ROUNDS
2398 && Flt_Rounds == 1
2399 #endif
2400 #endif
2402 if (!e)
2403 goto ret;
2404 if (e > 0) {
2405 if (e <= Ten_pmax) {
2406 #ifdef VAX
2407 goto vax_ovfl_check;
2408 #else
2409 #ifdef Honor_FLT_ROUNDS
2410 /* round correctly FLT_ROUNDS = 2 or 3 */
2411 if (sign) {
2412 rv = -rv;
2413 sign = 0;
2415 #endif
2416 /* rv = */ rounded_product(dval(rv), tens[e]);
2417 goto ret;
2418 #endif
2420 i = DBL_DIG - nd;
2421 if (e <= Ten_pmax + i) {
2422 /* A fancier test would sometimes let us do
2423 * this for larger i values.
2425 #ifdef Honor_FLT_ROUNDS
2426 /* round correctly FLT_ROUNDS = 2 or 3 */
2427 if (sign) {
2428 rv = -rv;
2429 sign = 0;
2431 #endif
2432 e -= i;
2433 dval(rv) *= tens[i];
2434 #ifdef VAX
2435 /* VAX exponent range is so narrow we must
2436 * worry about overflow here...
2438 vax_ovfl_check:
2439 word0(rv) -= P*Exp_msk1;
2440 /* rv = */ rounded_product(dval(rv), tens[e]);
2441 if ((word0(rv) & Exp_mask)
2442 > Exp_msk1*(DBL_MAX_EXP+Bias-1-P))
2443 goto ovfl;
2444 word0(rv) += P*Exp_msk1;
2445 #else
2446 /* rv = */ rounded_product(dval(rv), tens[e]);
2447 #endif
2448 goto ret;
2451 #ifndef Inaccurate_Divide
2452 else if (e >= -Ten_pmax) {
2453 #ifdef Honor_FLT_ROUNDS
2454 /* round correctly FLT_ROUNDS = 2 or 3 */
2455 if (sign) {
2456 rv = -rv;
2457 sign = 0;
2459 #endif
2460 /* rv = */ rounded_quotient(dval(rv), tens[-e]);
2461 goto ret;
2463 #endif
2465 e1 += nd - k;
2467 #ifdef IEEE_Arith
2468 #ifdef SET_INEXACT
2469 inexact = 1;
2470 if (k <= DBL_DIG)
2471 oldinexact = get_inexact();
2472 #endif
2473 #ifdef Avoid_Underflow
2474 scale = 0;
2475 #endif
2476 #ifdef Honor_FLT_ROUNDS
2477 if ((rounding = Flt_Rounds) >= 2) {
2478 if (sign)
2479 rounding = rounding == 2 ? 0 : 2;
2480 else
2481 if (rounding != 2)
2482 rounding = 0;
2484 #endif
2485 #endif /*IEEE_Arith*/
2487 /* Get starting approximation = rv * 10**e1 */
2489 if (e1 > 0) {
2490 if ((i = e1 & 15) != 0)
2491 dval(rv) *= tens[i];
2492 if (e1 &= ~15) {
2493 if (e1 > DBL_MAX_10_EXP) {
2494 ovfl:
2495 #ifndef NO_ERRNO
2496 errno = ERANGE;
2497 #endif
2498 /* Can't trust HUGE_VAL */
2499 #ifdef IEEE_Arith
2500 #ifdef Honor_FLT_ROUNDS
2501 switch (rounding) {
2502 case 0: /* toward 0 */
2503 case 3: /* toward -infinity */
2504 word0(rv) = Big0;
2505 word1(rv) = Big1;
2506 break;
2507 default:
2508 word0(rv) = Exp_mask;
2509 word1(rv) = 0;
2511 #else /*Honor_FLT_ROUNDS*/
2512 word0(rv) = Exp_mask;
2513 word1(rv) = 0;
2514 #endif /*Honor_FLT_ROUNDS*/
2515 #ifdef SET_INEXACT
2516 /* set overflow bit */
2517 dval(rv0) = 1e300;
2518 dval(rv0) *= dval(rv0);
2519 #endif
2520 #else /*IEEE_Arith*/
2521 word0(rv) = Big0;
2522 word1(rv) = Big1;
2523 #endif /*IEEE_Arith*/
2524 if (bd0)
2525 goto retfree;
2526 goto ret;
2528 e1 >>= 4;
2529 for (j = 0; e1 > 1; j++, e1 >>= 1)
2530 if (e1 & 1)
2531 dval(rv) *= bigtens[j];
2532 /* The last multiplication could overflow. */
2533 word0(rv) -= P*Exp_msk1;
2534 dval(rv) *= bigtens[j];
2535 if ((z = word0(rv) & Exp_mask)
2536 > Exp_msk1*(DBL_MAX_EXP+Bias-P))
2537 goto ovfl;
2538 if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) {
2539 /* set to largest number */
2540 /* (Can't trust DBL_MAX) */
2541 word0(rv) = Big0;
2542 word1(rv) = Big1;
2544 else
2545 word0(rv) += P*Exp_msk1;
2548 else if (e1 < 0) {
2549 e1 = -e1;
2550 if ((i = e1 & 15) != 0)
2551 dval(rv) /= tens[i];
2552 if (e1 >>= 4) {
2553 if (e1 >= 1 << n_bigtens)
2554 goto undfl;
2555 #ifdef Avoid_Underflow
2556 if (e1 & Scale_Bit)
2557 scale = 2*P;
2558 for (j = 0; e1 > 0; j++, e1 >>= 1)
2559 if (e1 & 1)
2560 dval(rv) *= tinytens[j];
2561 if (scale && (j = 2*P + 1 - ((word0(rv) & Exp_mask)
2562 >> Exp_shift)) > 0) {
2563 /* scaled rv is denormal; zap j low bits */
2564 if (j >= 32) {
2565 word1(rv) = 0;
2566 if (j >= 53)
2567 word0(rv) = (P+2)*Exp_msk1;
2568 else
2569 word0(rv) &= 0xffffffff << (j-32);
2571 else
2572 word1(rv) &= 0xffffffff << j;
2574 #else
2575 for (j = 0; e1 > 1; j++, e1 >>= 1)
2576 if (e1 & 1)
2577 dval(rv) *= tinytens[j];
2578 /* The last multiplication could underflow. */
2579 dval(rv0) = dval(rv);
2580 dval(rv) *= tinytens[j];
2581 if (!dval(rv)) {
2582 dval(rv) = 2.*dval(rv0);
2583 dval(rv) *= tinytens[j];
2584 #endif
2585 if (!dval(rv)) {
2586 undfl:
2587 dval(rv) = 0.;
2588 #ifndef NO_ERRNO
2589 errno = ERANGE;
2590 #endif
2591 if (bd0)
2592 goto retfree;
2593 goto ret;
2595 #ifndef Avoid_Underflow
2596 word0(rv) = Tiny0;
2597 word1(rv) = Tiny1;
2598 /* The refinement below will clean
2599 * this approximation up.
2602 #endif
2606 /* Now the hard part -- adjusting rv to the correct value.*/
2608 /* Put digits into bd: true value = bd * 10^e */
2610 bd0 = s2b(s0, nd0, nd, y);
2612 for (;;) {
2613 bd = Balloc(bd0->k);
2614 Bcopy(bd, bd0);
2615 bb = d2b(dval(rv), &bbe, &bbbits); /* rv = bb * 2^bbe */
2616 bs = i2b(1);
2618 if (e >= 0) {
2619 bb2 = bb5 = 0;
2620 bd2 = bd5 = e;
2622 else {
2623 bb2 = bb5 = -e;
2624 bd2 = bd5 = 0;
2626 if (bbe >= 0)
2627 bb2 += bbe;
2628 else
2629 bd2 -= bbe;
2630 bs2 = bb2;
2631 #ifdef Honor_FLT_ROUNDS
2632 if (rounding != 1)
2633 bs2++;
2634 #endif
2635 #ifdef Avoid_Underflow
2636 j = bbe - scale;
2637 i = j + bbbits - 1; /* logb(rv) */
2638 if (i < Emin) /* denormal */
2639 j += P - Emin;
2640 else
2641 j = P + 1 - bbbits;
2642 #else /*Avoid_Underflow*/
2643 #ifdef Sudden_Underflow
2644 #ifdef IBM
2645 j = 1 + 4*P - 3 - bbbits + ((bbe + bbbits - 1) & 3);
2646 #else
2647 j = P + 1 - bbbits;
2648 #endif
2649 #else /*Sudden_Underflow*/
2650 j = bbe;
2651 i = j + bbbits - 1; /* logb(rv) */
2652 if (i < Emin) /* denormal */
2653 j += P - Emin;
2654 else
2655 j = P + 1 - bbbits;
2656 #endif /*Sudden_Underflow*/
2657 #endif /*Avoid_Underflow*/
2658 bb2 += j;
2659 bd2 += j;
2660 #ifdef Avoid_Underflow
2661 bd2 += scale;
2662 #endif
2663 i = bb2 < bd2 ? bb2 : bd2;
2664 if (i > bs2)
2665 i = bs2;
2666 if (i > 0) {
2667 bb2 -= i;
2668 bd2 -= i;
2669 bs2 -= i;
2671 if (bb5 > 0) {
2672 bs = pow5mult(bs, bb5);
2673 bb1 = mult(bs, bb);
2674 Bfree(bb);
2675 bb = bb1;
2677 if (bb2 > 0)
2678 bb = lshift(bb, bb2);
2679 if (bd5 > 0)
2680 bd = pow5mult(bd, bd5);
2681 if (bd2 > 0)
2682 bd = lshift(bd, bd2);
2683 if (bs2 > 0)
2684 bs = lshift(bs, bs2);
2685 delta = diff(bb, bd);
2686 dsign = delta->sign;
2687 delta->sign = 0;
2688 i = cmp(delta, bs);
2689 #ifdef Honor_FLT_ROUNDS
2690 if (rounding != 1) {
2691 if (i < 0) {
2692 /* Error is less than an ulp */
2693 if (!delta->x[0] && delta->wds <= 1) {
2694 /* exact */
2695 #ifdef SET_INEXACT
2696 inexact = 0;
2697 #endif
2698 break;
2700 if (rounding) {
2701 if (dsign) {
2702 adj = 1.;
2703 goto apply_adj;
2706 else if (!dsign) {
2707 adj = -1.;
2708 if (!word1(rv)
2709 && !(word0(rv) & Frac_mask)) {
2710 y = word0(rv) & Exp_mask;
2711 #ifdef Avoid_Underflow
2712 if (!scale || y > 2*P*Exp_msk1)
2713 #else
2714 if (y)
2715 #endif
2717 delta = lshift(delta,Log2P);
2718 if (cmp(delta, bs) <= 0)
2719 adj = -0.5;
2722 apply_adj:
2723 #ifdef Avoid_Underflow
2724 if (scale && (y = word0(rv) & Exp_mask)
2725 <= 2*P*Exp_msk1)
2726 word0(adj) += (2*P+1)*Exp_msk1 - y;
2727 #else
2728 #ifdef Sudden_Underflow
2729 if ((word0(rv) & Exp_mask) <=
2730 P*Exp_msk1) {
2731 word0(rv) += P*Exp_msk1;
2732 dval(rv) += adj*ulp(dval(rv));
2733 word0(rv) -= P*Exp_msk1;
2735 else
2736 #endif /*Sudden_Underflow*/
2737 #endif /*Avoid_Underflow*/
2738 dval(rv) += adj*ulp(dval(rv));
2740 break;
2742 adj = ratio(delta, bs);
2743 if (adj < 1.)
2744 adj = 1.;
2745 if (adj <= 0x7ffffffe) {
2746 /* adj = rounding ? ceil(adj) : floor(adj); */
2747 y = adj;
2748 if (y != adj) {
2749 if (!((rounding>>1) ^ dsign))
2750 y++;
2751 adj = y;
2754 #ifdef Avoid_Underflow
2755 if (scale && (y = word0(rv) & Exp_mask) <= 2*P*Exp_msk1)
2756 word0(adj) += (2*P+1)*Exp_msk1 - y;
2757 #else
2758 #ifdef Sudden_Underflow
2759 if ((word0(rv) & Exp_mask) <= P*Exp_msk1) {
2760 word0(rv) += P*Exp_msk1;
2761 adj *= ulp(dval(rv));
2762 if (dsign)
2763 dval(rv) += adj;
2764 else
2765 dval(rv) -= adj;
2766 word0(rv) -= P*Exp_msk1;
2767 goto cont;
2769 #endif /*Sudden_Underflow*/
2770 #endif /*Avoid_Underflow*/
2771 adj *= ulp(dval(rv));
2772 if (dsign)
2773 dval(rv) += adj;
2774 else
2775 dval(rv) -= adj;
2776 goto cont;
2778 #endif /*Honor_FLT_ROUNDS*/
2780 if (i < 0) {
2781 /* Error is less than half an ulp -- check for
2782 * special case of mantissa a power of two.
2784 if (dsign || word1(rv) || word0(rv) & Bndry_mask
2785 #ifdef IEEE_Arith
2786 #ifdef Avoid_Underflow
2787 || (word0(rv) & Exp_mask) <= (2*P+1)*Exp_msk1
2788 #else
2789 || (word0(rv) & Exp_mask) <= Exp_msk1
2790 #endif
2791 #endif
2793 #ifdef SET_INEXACT
2794 if (!delta->x[0] && delta->wds <= 1)
2795 inexact = 0;
2796 #endif
2797 break;
2799 if (!delta->x[0] && delta->wds <= 1) {
2800 /* exact result */
2801 #ifdef SET_INEXACT
2802 inexact = 0;
2803 #endif
2804 break;
2806 delta = lshift(delta,Log2P);
2807 if (cmp(delta, bs) > 0)
2808 goto drop_down;
2809 break;
2811 if (i == 0) {
2812 /* exactly half-way between */
2813 if (dsign) {
2814 if ((word0(rv) & Bndry_mask1) == Bndry_mask1
2815 && word1(rv) == (
2816 #ifdef Avoid_Underflow
2817 (scale && (y = word0(rv) & Exp_mask) <= 2*P*Exp_msk1)
2818 ? (0xffffffff & (0xffffffff << (2*P+1-(y>>Exp_shift)))) :
2819 #endif
2820 0xffffffff)) {
2821 /*boundary case -- increment exponent*/
2822 word0(rv) = (word0(rv) & Exp_mask)
2823 + Exp_msk1
2824 #ifdef IBM
2825 | Exp_msk1 >> 4
2826 #endif
2828 word1(rv) = 0;
2829 #ifdef Avoid_Underflow
2830 dsign = 0;
2831 #endif
2832 break;
2835 else if (!(word0(rv) & Bndry_mask) && !word1(rv)) {
2836 drop_down:
2837 /* boundary case -- decrement exponent */
2838 #ifdef Sudden_Underflow /*{{*/
2839 L = word0(rv) & Exp_mask;
2840 #ifdef IBM
2841 if (L < Exp_msk1)
2842 #else
2843 #ifdef Avoid_Underflow
2844 if (L <= (scale ? (2*P+1)*Exp_msk1 : Exp_msk1))
2845 #else
2846 if (L <= Exp_msk1)
2847 #endif /*Avoid_Underflow*/
2848 #endif /*IBM*/
2849 goto undfl;
2850 L -= Exp_msk1;
2851 #else /*Sudden_Underflow}{*/
2852 #ifdef Avoid_Underflow
2853 if (scale) {
2854 L = word0(rv) & Exp_mask;
2855 if (L <= (2*P+1)*Exp_msk1) {
2856 if (L > (P+2)*Exp_msk1)
2857 /* round even ==> */
2858 /* accept rv */
2859 break;
2860 /* rv = smallest denormal */
2861 goto undfl;
2864 #endif /*Avoid_Underflow*/
2865 L = (word0(rv) & Exp_mask) - Exp_msk1;
2866 #endif /*Sudden_Underflow}}*/
2867 word0(rv) = L | Bndry_mask1;
2868 word1(rv) = 0xffffffff;
2869 #ifdef IBM
2870 goto cont;
2871 #else
2872 break;
2873 #endif
2875 #ifndef ROUND_BIASED
2876 if (!(word1(rv) & LSB))
2877 break;
2878 #endif
2879 if (dsign)
2880 dval(rv) += ulp(dval(rv));
2881 #ifndef ROUND_BIASED
2882 else {
2883 dval(rv) -= ulp(dval(rv));
2884 #ifndef Sudden_Underflow
2885 if (!dval(rv))
2886 goto undfl;
2887 #endif
2889 #ifdef Avoid_Underflow
2890 dsign = 1 - dsign;
2891 #endif
2892 #endif
2893 break;
2895 if ((aadj = ratio(delta, bs)) <= 2.) {
2896 if (dsign)
2897 aadj = aadj1 = 1.;
2898 else if (word1(rv) || word0(rv) & Bndry_mask) {
2899 #ifndef Sudden_Underflow
2900 if (word1(rv) == Tiny1 && !word0(rv))
2901 goto undfl;
2902 #endif
2903 aadj = 1.;
2904 aadj1 = -1.;
2906 else {
2907 /* special case -- power of FLT_RADIX to be */
2908 /* rounded down... */
2910 if (aadj < 2./FLT_RADIX)
2911 aadj = 1./FLT_RADIX;
2912 else
2913 aadj *= 0.5;
2914 aadj1 = -aadj;
2917 else {
2918 aadj *= 0.5;
2919 aadj1 = dsign ? aadj : -aadj;
2920 #ifdef Check_FLT_ROUNDS
2921 switch (Rounding) {
2922 case 2: /* towards +infinity */
2923 aadj1 -= 0.5;
2924 break;
2925 case 0: /* towards 0 */
2926 case 3: /* towards -infinity */
2927 aadj1 += 0.5;
2929 #else
2930 if (Flt_Rounds == 0)
2931 aadj1 += 0.5;
2932 #endif /*Check_FLT_ROUNDS*/
2934 y = word0(rv) & Exp_mask;
2936 /* Check for overflow */
2938 if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) {
2939 dval(rv0) = dval(rv);
2940 word0(rv) -= P*Exp_msk1;
2941 adj = aadj1 * ulp(dval(rv));
2942 dval(rv) += adj;
2943 if ((word0(rv) & Exp_mask) >=
2944 Exp_msk1*(DBL_MAX_EXP+Bias-P)) {
2945 if (word0(rv0) == Big0 && word1(rv0) == Big1)
2946 goto ovfl;
2947 word0(rv) = Big0;
2948 word1(rv) = Big1;
2949 goto cont;
2951 else
2952 word0(rv) += P*Exp_msk1;
2954 else {
2955 #ifdef Avoid_Underflow
2956 if (scale && y <= 2*P*Exp_msk1) {
2957 if (aadj <= 0x7fffffff) {
2958 if ((z = aadj) <= 0)
2959 z = 1;
2960 aadj = z;
2961 aadj1 = dsign ? aadj : -aadj;
2963 word0(aadj1) += (2*P+1)*Exp_msk1 - y;
2965 adj = aadj1 * ulp(dval(rv));
2966 dval(rv) += adj;
2967 #else
2968 #ifdef Sudden_Underflow
2969 if ((word0(rv) & Exp_mask) <= P*Exp_msk1) {
2970 dval(rv0) = dval(rv);
2971 word0(rv) += P*Exp_msk1;
2972 adj = aadj1 * ulp(dval(rv));
2973 dval(rv) += adj;
2974 #ifdef IBM
2975 if ((word0(rv) & Exp_mask) < P*Exp_msk1)
2976 #else
2977 if ((word0(rv) & Exp_mask) <= P*Exp_msk1)
2978 #endif
2980 if (word0(rv0) == Tiny0 && word1(rv0) == Tiny1)
2981 goto undfl;
2982 word0(rv) = Tiny0;
2983 word1(rv) = Tiny1;
2984 goto cont;
2986 else
2987 word0(rv) -= P*Exp_msk1;
2989 else {
2990 adj = aadj1 * ulp(dval(rv));
2991 dval(rv) += adj;
2993 #else /*Sudden_Underflow*/
2994 /* Compute adj so that the IEEE rounding rules will
2995 * correctly round rv + adj in some half-way cases.
2996 * If rv * ulp(rv) is denormalized (i.e.,
2997 * y <= (P-1)*Exp_msk1), we must adjust aadj to avoid
2998 * trouble from bits lost to denormalization;
2999 * example: 1.2e-307 .
3001 if (y <= (P-1)*Exp_msk1 && aadj > 1.) {
3002 aadj1 = (double)(int)(aadj + 0.5);
3003 if (!dsign)
3004 aadj1 = -aadj1;
3006 adj = aadj1 * ulp(dval(rv));
3007 dval(rv) += adj;
3008 #endif /*Sudden_Underflow*/
3009 #endif /*Avoid_Underflow*/
3011 z = word0(rv) & Exp_mask;
3012 #ifndef SET_INEXACT
3013 #ifdef Avoid_Underflow
3014 if (!scale)
3015 #endif
3016 if (y == z) {
3017 /* Can we stop now? */
3018 L = (Long)aadj;
3019 aadj -= L;
3020 /* The tolerances below are conservative. */
3021 if (dsign || word1(rv) || word0(rv) & Bndry_mask) {
3022 if (aadj < .4999999 || aadj > .5000001)
3023 break;
3025 else if (aadj < .4999999/FLT_RADIX)
3026 break;
3028 #endif
3029 cont:
3030 Bfree(bb);
3031 Bfree(bd);
3032 Bfree(bs);
3033 Bfree(delta);
3035 #ifdef SET_INEXACT
3036 if (inexact) {
3037 if (!oldinexact) {
3038 word0(rv0) = Exp_1 + (70 << Exp_shift);
3039 word1(rv0) = 0;
3040 dval(rv0) += 1.;
3043 else if (!oldinexact)
3044 clear_inexact();
3045 #endif
3046 #ifdef Avoid_Underflow
3047 if (scale) {
3048 word0(rv0) = Exp_1 - 2*P*Exp_msk1;
3049 word1(rv0) = 0;
3050 dval(rv) *= dval(rv0);
3051 #ifndef NO_ERRNO
3052 /* try to avoid the bug of testing an 8087 register value */
3053 if (word0(rv) == 0 && word1(rv) == 0)
3054 errno = ERANGE;
3055 #endif
3057 #endif /* Avoid_Underflow */
3058 #ifdef SET_INEXACT
3059 if (inexact && !(word0(rv) & Exp_mask)) {
3060 /* set underflow bit */
3061 dval(rv0) = 1e-300;
3062 dval(rv0) *= dval(rv0);
3064 #endif
3065 retfree:
3066 Bfree(bb);
3067 Bfree(bd);
3068 Bfree(bs);
3069 Bfree(bd0);
3070 Bfree(delta);
3071 ret:
3072 if (se)
3073 *se = (char *)s;
3074 return sign ? -dval(rv) : dval(rv);
3077 static int
3078 quorem(Bigint *b, Bigint *S)
3080 int n;
3081 ULong *bx, *bxe, q, *sx, *sxe;
3082 #ifdef ULLong
3083 ULLong borrow, carry, y, ys;
3084 #else
3085 ULong borrow, carry, y, ys;
3086 #ifdef Pack_32
3087 ULong si, z, zs;
3088 #endif
3089 #endif
3091 n = S->wds;
3092 #ifdef DEBUG
3093 /*debug*/ if (b->wds > n)
3094 /*debug*/ Bug("oversize b in quorem");
3095 #endif
3096 if (b->wds < n)
3097 return 0;
3098 sx = S->x;
3099 sxe = sx + --n;
3100 bx = b->x;
3101 bxe = bx + n;
3102 q = *bxe / (*sxe + 1); /* ensure q <= true quotient */
3103 #ifdef DEBUG
3104 /*debug*/ if (q > 9)
3105 /*debug*/ Bug("oversized quotient in quorem");
3106 #endif
3107 if (q) {
3108 borrow = 0;
3109 carry = 0;
3110 do {
3111 #ifdef ULLong
3112 ys = *sx++ * (ULLong)q + carry;
3113 carry = ys >> 32;
3114 y = *bx - (ys & FFFFFFFF) - borrow;
3115 borrow = y >> 32 & (ULong)1;
3116 *bx++ = y & FFFFFFFF;
3117 #else
3118 #ifdef Pack_32
3119 si = *sx++;
3120 ys = (si & 0xffff) * q + carry;
3121 zs = (si >> 16) * q + (ys >> 16);
3122 carry = zs >> 16;
3123 y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
3124 borrow = (y & 0x10000) >> 16;
3125 z = (*bx >> 16) - (zs & 0xffff) - borrow;
3126 borrow = (z & 0x10000) >> 16;
3127 Storeinc(bx, z, y);
3128 #else
3129 ys = *sx++ * q + carry;
3130 carry = ys >> 16;
3131 y = *bx - (ys & 0xffff) - borrow;
3132 borrow = (y & 0x10000) >> 16;
3133 *bx++ = y & 0xffff;
3134 #endif
3135 #endif
3136 } while (sx <= sxe);
3137 if (!*bxe) {
3138 bx = b->x;
3139 while (--bxe > bx && !*bxe)
3140 --n;
3141 b->wds = n;
3144 if (cmp(b, S) >= 0) {
3145 q++;
3146 borrow = 0;
3147 carry = 0;
3148 bx = b->x;
3149 sx = S->x;
3150 do {
3151 #ifdef ULLong
3152 ys = *sx++ + carry;
3153 carry = ys >> 32;
3154 y = *bx - (ys & FFFFFFFF) - borrow;
3155 borrow = y >> 32 & (ULong)1;
3156 *bx++ = y & FFFFFFFF;
3157 #else
3158 #ifdef Pack_32
3159 si = *sx++;
3160 ys = (si & 0xffff) + carry;
3161 zs = (si >> 16) + (ys >> 16);
3162 carry = zs >> 16;
3163 y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
3164 borrow = (y & 0x10000) >> 16;
3165 z = (*bx >> 16) - (zs & 0xffff) - borrow;
3166 borrow = (z & 0x10000) >> 16;
3167 Storeinc(bx, z, y);
3168 #else
3169 ys = *sx++ + carry;
3170 carry = ys >> 16;
3171 y = *bx - (ys & 0xffff) - borrow;
3172 borrow = (y & 0x10000) >> 16;
3173 *bx++ = y & 0xffff;
3174 #endif
3175 #endif
3176 } while (sx <= sxe);
3177 bx = b->x;
3178 bxe = bx + n;
3179 if (!*bxe) {
3180 while (--bxe > bx && !*bxe)
3181 --n;
3182 b->wds = n;
3185 return q;
3188 #ifndef MULTIPLE_THREADS
3189 static char *dtoa_result;
3190 #endif
3192 static char *
3193 rv_alloc(int i)
3195 int j, k, *r;
3197 j = sizeof(ULong);
3198 for (k = 0;
3199 sizeof(Bigint) - sizeof(ULong) - sizeof(int) + j <= i;
3200 j <<= 1)
3201 k++;
3202 r = (int*)Balloc(k);
3203 *r = k;
3204 return
3205 #ifndef MULTIPLE_THREADS
3206 dtoa_result =
3207 #endif
3208 (char *)(r+1);
3211 static char *
3212 nrv_alloc(const char *s, char **rve, int n)
3214 char *rv, *t;
3216 t = rv = rv_alloc(n);
3217 while ((*t = *s++) != 0) t++;
3218 if (rve)
3219 *rve = t;
3220 return rv;
3223 /* freedtoa(s) must be used to free values s returned by dtoa
3224 * when MULTIPLE_THREADS is #defined. It should be used in all cases,
3225 * but for consistency with earlier versions of dtoa, it is optional
3226 * when MULTIPLE_THREADS is not defined.
3229 void
3230 freedtoa(char *s)
3232 Bigint *b = (Bigint *)((int *)s - 1);
3233 b->maxwds = 1 << (b->k = *(int*)b);
3234 Bfree(b);
3235 #ifndef MULTIPLE_THREADS
3236 if (s == dtoa_result)
3237 dtoa_result = 0;
3238 #endif
3241 /* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
3243 * Inspired by "How to Print Floating-Point Numbers Accurately" by
3244 * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 112-126].
3246 * Modifications:
3247 * 1. Rather than iterating, we use a simple numeric overestimate
3248 * to determine k = floor(log10(d)). We scale relevant
3249 * quantities using O(log2(k)) rather than O(k) multiplications.
3250 * 2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
3251 * try to generate digits strictly left to right. Instead, we
3252 * compute with fewer bits and propagate the carry if necessary
3253 * when rounding the final digit up. This is often faster.
3254 * 3. Under the assumption that input will be rounded nearest,
3255 * mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
3256 * That is, we allow equality in stopping tests when the
3257 * round-nearest rule will give the same floating-point value
3258 * as would satisfaction of the stopping test with strict
3259 * inequality.
3260 * 4. We remove common factors of powers of 2 from relevant
3261 * quantities.
3262 * 5. When converting floating-point integers less than 1e16,
3263 * we use floating-point arithmetic rather than resorting
3264 * to multiple-precision integers.
3265 * 6. When asked to produce fewer than 15 digits, we first try
3266 * to get by with floating-point arithmetic; we resort to
3267 * multiple-precision integer arithmetic only if we cannot
3268 * guarantee that the floating-point calculation has given
3269 * the correctly rounded result. For k requested digits and
3270 * "uniformly" distributed input, the probability is
3271 * something like 10^(k-15) that we must resort to the Long
3272 * calculation.
3275 char *
3276 dtoa(double d, int mode, int ndigits, int *decpt, int *sign, char **rve)
3278 /* Arguments ndigits, decpt, sign are similar to those
3279 of ecvt and fcvt; trailing zeros are suppressed from
3280 the returned string. If not null, *rve is set to point
3281 to the end of the return value. If d is +-Infinity or NaN,
3282 then *decpt is set to 9999.
3284 mode:
3285 0 ==> shortest string that yields d when read in
3286 and rounded to nearest.
3287 1 ==> like 0, but with Steele & White stopping rule;
3288 e.g. with IEEE P754 arithmetic , mode 0 gives
3289 1e23 whereas mode 1 gives 9.999999999999999e22.
3290 2 ==> max(1,ndigits) significant digits. This gives a
3291 return value similar to that of ecvt, except
3292 that trailing zeros are suppressed.
3293 3 ==> through ndigits past the decimal point. This
3294 gives a return value similar to that from fcvt,
3295 except that trailing zeros are suppressed, and
3296 ndigits can be negative.
3297 4,5 ==> similar to 2 and 3, respectively, but (in
3298 round-nearest mode) with the tests of mode 0 to
3299 possibly return a shorter string that rounds to d.
3300 With IEEE arithmetic and compilation with
3301 -DHonor_FLT_ROUNDS, modes 4 and 5 behave the same
3302 as modes 2 and 3 when FLT_ROUNDS != 1.
3303 6-9 ==> Debugging modes similar to mode - 4: don't try
3304 fast floating-point estimate (if applicable).
3306 Values of mode other than 0-9 are treated as mode 0.
3308 Sufficient space is allocated to the return value
3309 to hold the suppressed trailing zeros.
3312 int bbits, b2, b5, be, dig, i, ieps, ilim, ilim0, ilim1,
3313 j, j1, k, k0, k_check, leftright, m2, m5, s2, s5,
3314 spec_case, try_quick;
3315 Long L;
3316 #ifndef Sudden_Underflow
3317 int denorm;
3318 ULong x;
3319 #endif
3320 Bigint *b, *b1, *delta, *mlo = 0, *mhi = 0, *S;
3321 double d2, ds, eps;
3322 char *s, *s0;
3323 #ifdef Honor_FLT_ROUNDS
3324 int rounding;
3325 #endif
3326 #ifdef SET_INEXACT
3327 int inexact, oldinexact;
3328 #endif
3330 #ifndef MULTIPLE_THREADS
3331 if (dtoa_result) {
3332 freedtoa(dtoa_result);
3333 dtoa_result = 0;
3335 #endif
3337 if (word0(d) & Sign_bit) {
3338 /* set sign for everything, including 0's and NaNs */
3339 *sign = 1;
3340 word0(d) &= ~Sign_bit; /* clear sign bit */
3342 else
3343 *sign = 0;
3345 #if defined(IEEE_Arith) + defined(VAX)
3346 #ifdef IEEE_Arith
3347 if ((word0(d) & Exp_mask) == Exp_mask)
3348 #else
3349 if (word0(d) == 0x8000)
3350 #endif
3352 /* Infinity or NaN */
3353 *decpt = 9999;
3354 #ifdef IEEE_Arith
3355 if (!word1(d) && !(word0(d) & 0xfffff))
3356 return nrv_alloc("Infinity", rve, 8);
3357 #endif
3358 return nrv_alloc("NaN", rve, 3);
3360 #endif
3361 #ifdef IBM
3362 dval(d) += 0; /* normalize */
3363 #endif
3364 if (!dval(d)) {
3365 *decpt = 1;
3366 return nrv_alloc("0", rve, 1);
3369 #ifdef SET_INEXACT
3370 try_quick = oldinexact = get_inexact();
3371 inexact = 1;
3372 #endif
3373 #ifdef Honor_FLT_ROUNDS
3374 if ((rounding = Flt_Rounds) >= 2) {
3375 if (*sign)
3376 rounding = rounding == 2 ? 0 : 2;
3377 else
3378 if (rounding != 2)
3379 rounding = 0;
3381 #endif
3383 b = d2b(dval(d), &be, &bbits);
3384 #ifdef Sudden_Underflow
3385 i = (int)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1));
3386 #else
3387 if ((i = (int)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1))) != 0) {
3388 #endif
3389 dval(d2) = dval(d);
3390 word0(d2) &= Frac_mask1;
3391 word0(d2) |= Exp_11;
3392 #ifdef IBM
3393 if (j = 11 - hi0bits(word0(d2) & Frac_mask))
3394 dval(d2) /= 1 << j;
3395 #endif
3397 /* log(x) ~=~ log(1.5) + (x-1.5)/1.5
3398 * log10(x) = log(x) / log(10)
3399 * ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
3400 * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2)
3402 * This suggests computing an approximation k to log10(d) by
3404 * k = (i - Bias)*0.301029995663981
3405 * + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
3407 * We want k to be too large rather than too small.
3408 * The error in the first-order Taylor series approximation
3409 * is in our favor, so we just round up the constant enough
3410 * to compensate for any error in the multiplication of
3411 * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
3412 * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
3413 * adding 1e-13 to the constant term more than suffices.
3414 * Hence we adjust the constant term to 0.1760912590558.
3415 * (We could get a more accurate k by invoking log10,
3416 * but this is probably not worthwhile.)
3419 i -= Bias;
3420 #ifdef IBM
3421 i <<= 2;
3422 i += j;
3423 #endif
3424 #ifndef Sudden_Underflow
3425 denorm = 0;
3427 else {
3428 /* d is denormalized */
3430 i = bbits + be + (Bias + (P-1) - 1);
3431 x = i > 32 ? word0(d) << (64 - i) | word1(d) >> (i - 32)
3432 : word1(d) << (32 - i);
3433 dval(d2) = x;
3434 word0(d2) -= 31*Exp_msk1; /* adjust exponent */
3435 i -= (Bias + (P-1) - 1) + 1;
3436 denorm = 1;
3438 #endif
3439 ds = (dval(d2)-1.5)*0.289529654602168 + 0.1760912590558 + i*0.301029995663981;
3440 k = (int)ds;
3441 if (ds < 0. && ds != k)
3442 k--; /* want k = floor(ds) */
3443 k_check = 1;
3444 if (k >= 0 && k <= Ten_pmax) {
3445 if (dval(d) < tens[k])
3446 k--;
3447 k_check = 0;
3449 j = bbits - i - 1;
3450 if (j >= 0) {
3451 b2 = 0;
3452 s2 = j;
3454 else {
3455 b2 = -j;
3456 s2 = 0;
3458 if (k >= 0) {
3459 b5 = 0;
3460 s5 = k;
3461 s2 += k;
3463 else {
3464 b2 -= k;
3465 b5 = -k;
3466 s5 = 0;
3468 if (mode < 0 || mode > 9)
3469 mode = 0;
3471 #ifndef SET_INEXACT
3472 #ifdef Check_FLT_ROUNDS
3473 try_quick = Rounding == 1;
3474 #else
3475 try_quick = 1;
3476 #endif
3477 #endif /*SET_INEXACT*/
3479 if (mode > 5) {
3480 mode -= 4;
3481 try_quick = 0;
3483 leftright = 1;
3484 ilim = ilim1 = -1;
3485 switch (mode) {
3486 case 0:
3487 case 1:
3488 i = 18;
3489 ndigits = 0;
3490 break;
3491 case 2:
3492 leftright = 0;
3493 /* no break */
3494 case 4:
3495 if (ndigits <= 0)
3496 ndigits = 1;
3497 ilim = ilim1 = i = ndigits;
3498 break;
3499 case 3:
3500 leftright = 0;
3501 /* no break */
3502 case 5:
3503 i = ndigits + k + 1;
3504 ilim = i;
3505 ilim1 = i - 1;
3506 if (i <= 0)
3507 i = 1;
3509 s = s0 = rv_alloc(i);
3511 #ifdef Honor_FLT_ROUNDS
3512 if (mode > 1 && rounding != 1)
3513 leftright = 0;
3514 #endif
3516 if (ilim >= 0 && ilim <= Quick_max && try_quick) {
3518 /* Try to get by with floating-point arithmetic. */
3520 i = 0;
3521 dval(d2) = dval(d);
3522 k0 = k;
3523 ilim0 = ilim;
3524 ieps = 2; /* conservative */
3525 if (k > 0) {
3526 ds = tens[k&0xf];
3527 j = k >> 4;
3528 if (j & Bletch) {
3529 /* prevent overflows */
3530 j &= Bletch - 1;
3531 dval(d) /= bigtens[n_bigtens-1];
3532 ieps++;
3534 for (; j; j >>= 1, i++)
3535 if (j & 1) {
3536 ieps++;
3537 ds *= bigtens[i];
3539 dval(d) /= ds;
3541 else if ((j1 = -k) != 0) {
3542 dval(d) *= tens[j1 & 0xf];
3543 for (j = j1 >> 4; j; j >>= 1, i++)
3544 if (j & 1) {
3545 ieps++;
3546 dval(d) *= bigtens[i];
3549 if (k_check && dval(d) < 1. && ilim > 0) {
3550 if (ilim1 <= 0)
3551 goto fast_failed;
3552 ilim = ilim1;
3553 k--;
3554 dval(d) *= 10.;
3555 ieps++;
3557 dval(eps) = ieps*dval(d) + 7.;
3558 word0(eps) -= (P-1)*Exp_msk1;
3559 if (ilim == 0) {
3560 S = mhi = 0;
3561 dval(d) -= 5.;
3562 if (dval(d) > dval(eps))
3563 goto one_digit;
3564 if (dval(d) < -dval(eps))
3565 goto no_digits;
3566 goto fast_failed;
3568 #ifndef No_leftright
3569 if (leftright) {
3570 /* Use Steele & White method of only
3571 * generating digits needed.
3573 dval(eps) = 0.5/tens[ilim-1] - dval(eps);
3574 for (i = 0;;) {
3575 L = dval(d);
3576 dval(d) -= L;
3577 *s++ = '0' + (int)L;
3578 if (dval(d) < dval(eps))
3579 goto ret1;
3580 if (1. - dval(d) < dval(eps))
3581 goto bump_up;
3582 if (++i >= ilim)
3583 break;
3584 dval(eps) *= 10.;
3585 dval(d) *= 10.;
3588 else {
3589 #endif
3590 /* Generate ilim digits, then fix them up. */
3591 dval(eps) *= tens[ilim-1];
3592 for (i = 1;; i++, dval(d) *= 10.) {
3593 L = (Long)(dval(d));
3594 if (!(dval(d) -= L))
3595 ilim = i;
3596 *s++ = '0' + (int)L;
3597 if (i == ilim) {
3598 if (dval(d) > 0.5 + dval(eps))
3599 goto bump_up;
3600 else if (dval(d) < 0.5 - dval(eps)) {
3601 while (*--s == '0') ;
3602 s++;
3603 goto ret1;
3605 break;
3608 #ifndef No_leftright
3610 #endif
3611 fast_failed:
3612 s = s0;
3613 dval(d) = dval(d2);
3614 k = k0;
3615 ilim = ilim0;
3618 /* Do we have a "small" integer? */
3620 if (be >= 0 && k <= Int_max) {
3621 /* Yes. */
3622 ds = tens[k];
3623 if (ndigits < 0 && ilim <= 0) {
3624 S = mhi = 0;
3625 if (ilim < 0 || dval(d) <= 5*ds)
3626 goto no_digits;
3627 goto one_digit;
3629 for (i = 1;; i++, dval(d) *= 10.) {
3630 L = (Long)(dval(d) / ds);
3631 dval(d) -= L*ds;
3632 #ifdef Check_FLT_ROUNDS
3633 /* If FLT_ROUNDS == 2, L will usually be high by 1 */
3634 if (dval(d) < 0) {
3635 L--;
3636 dval(d) += ds;
3638 #endif
3639 *s++ = '0' + (int)L;
3640 if (!dval(d)) {
3641 #ifdef SET_INEXACT
3642 inexact = 0;
3643 #endif
3644 break;
3646 if (i == ilim) {
3647 #ifdef Honor_FLT_ROUNDS
3648 if (mode > 1)
3649 switch (rounding) {
3650 case 0: goto ret1;
3651 case 2: goto bump_up;
3653 #endif
3654 dval(d) += dval(d);
3655 if (dval(d) > ds || (dval(d) == ds && (L & 1))) {
3656 bump_up:
3657 while (*--s == '9')
3658 if (s == s0) {
3659 k++;
3660 *s = '0';
3661 break;
3663 ++*s++;
3665 break;
3668 goto ret1;
3671 m2 = b2;
3672 m5 = b5;
3673 if (leftright) {
3675 #ifndef Sudden_Underflow
3676 denorm ? be + (Bias + (P-1) - 1 + 1) :
3677 #endif
3678 #ifdef IBM
3679 1 + 4*P - 3 - bbits + ((bbits + be - 1) & 3);
3680 #else
3681 1 + P - bbits;
3682 #endif
3683 b2 += i;
3684 s2 += i;
3685 mhi = i2b(1);
3687 if (m2 > 0 && s2 > 0) {
3688 i = m2 < s2 ? m2 : s2;
3689 b2 -= i;
3690 m2 -= i;
3691 s2 -= i;
3693 if (b5 > 0) {
3694 if (leftright) {
3695 if (m5 > 0) {
3696 mhi = pow5mult(mhi, m5);
3697 b1 = mult(mhi, b);
3698 Bfree(b);
3699 b = b1;
3701 if ((j = b5 - m5) != 0)
3702 b = pow5mult(b, j);
3704 else
3705 b = pow5mult(b, b5);
3707 S = i2b(1);
3708 if (s5 > 0)
3709 S = pow5mult(S, s5);
3711 /* Check for special case that d is a normalized power of 2. */
3713 spec_case = 0;
3714 if ((mode < 2 || leftright)
3715 #ifdef Honor_FLT_ROUNDS
3716 && rounding == 1
3717 #endif
3719 if (!word1(d) && !(word0(d) & Bndry_mask)
3720 #ifndef Sudden_Underflow
3721 && word0(d) & (Exp_mask & ~Exp_msk1)
3722 #endif
3724 /* The special case */
3725 b2 += Log2P;
3726 s2 += Log2P;
3727 spec_case = 1;
3731 /* Arrange for convenient computation of quotients:
3732 * shift left if necessary so divisor has 4 leading 0 bits.
3734 * Perhaps we should just compute leading 28 bits of S once
3735 * and for all and pass them and a shift to quorem, so it
3736 * can do shifts and ors to compute the numerator for q.
3738 #ifdef Pack_32
3739 if ((i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0x1f) != 0)
3740 i = 32 - i;
3741 #else
3742 if ((i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0xf) != 0)
3743 i = 16 - i;
3744 #endif
3745 if (i > 4) {
3746 i -= 4;
3747 b2 += i;
3748 m2 += i;
3749 s2 += i;
3751 else if (i < 4) {
3752 i += 28;
3753 b2 += i;
3754 m2 += i;
3755 s2 += i;
3757 if (b2 > 0)
3758 b = lshift(b, b2);
3759 if (s2 > 0)
3760 S = lshift(S, s2);
3761 if (k_check) {
3762 if (cmp(b,S) < 0) {
3763 k--;
3764 b = multadd(b, 10, 0); /* we botched the k estimate */
3765 if (leftright)
3766 mhi = multadd(mhi, 10, 0);
3767 ilim = ilim1;
3770 if (ilim <= 0 && (mode == 3 || mode == 5)) {
3771 if (ilim < 0 || cmp(b,S = multadd(S,5,0)) <= 0) {
3772 /* no digits, fcvt style */
3773 no_digits:
3774 k = -1 - ndigits;
3775 goto ret;
3777 one_digit:
3778 *s++ = '1';
3779 k++;
3780 goto ret;
3782 if (leftright) {
3783 if (m2 > 0)
3784 mhi = lshift(mhi, m2);
3786 /* Compute mlo -- check for special case
3787 * that d is a normalized power of 2.
3790 mlo = mhi;
3791 if (spec_case) {
3792 mhi = Balloc(mhi->k);
3793 Bcopy(mhi, mlo);
3794 mhi = lshift(mhi, Log2P);
3797 for (i = 1;;i++) {
3798 dig = quorem(b,S) + '0';
3799 /* Do we yet have the shortest decimal string
3800 * that will round to d?
3802 j = cmp(b, mlo);
3803 delta = diff(S, mhi);
3804 j1 = delta->sign ? 1 : cmp(b, delta);
3805 Bfree(delta);
3806 #ifndef ROUND_BIASED
3807 if (j1 == 0 && mode != 1 && !(word1(d) & 1)
3808 #ifdef Honor_FLT_ROUNDS
3809 && rounding >= 1
3810 #endif
3812 if (dig == '9')
3813 goto round_9_up;
3814 if (j > 0)
3815 dig++;
3816 #ifdef SET_INEXACT
3817 else if (!b->x[0] && b->wds <= 1)
3818 inexact = 0;
3819 #endif
3820 *s++ = dig;
3821 goto ret;
3823 #endif
3824 if (j < 0 || (j == 0 && mode != 1
3825 #ifndef ROUND_BIASED
3826 && !(word1(d) & 1)
3827 #endif
3828 )) {
3829 if (!b->x[0] && b->wds <= 1) {
3830 #ifdef SET_INEXACT
3831 inexact = 0;
3832 #endif
3833 goto accept_dig;
3835 #ifdef Honor_FLT_ROUNDS
3836 if (mode > 1)
3837 switch (rounding) {
3838 case 0: goto accept_dig;
3839 case 2: goto keep_dig;
3841 #endif /*Honor_FLT_ROUNDS*/
3842 if (j1 > 0) {
3843 b = lshift(b, 1);
3844 j1 = cmp(b, S);
3845 if ((j1 > 0 || (j1 == 0 && (dig & 1))) && dig++ == '9')
3846 goto round_9_up;
3848 accept_dig:
3849 *s++ = dig;
3850 goto ret;
3852 if (j1 > 0) {
3853 #ifdef Honor_FLT_ROUNDS
3854 if (!rounding)
3855 goto accept_dig;
3856 #endif
3857 if (dig == '9') { /* possible if i == 1 */
3858 round_9_up:
3859 *s++ = '9';
3860 goto roundoff;
3862 *s++ = dig + 1;
3863 goto ret;
3865 #ifdef Honor_FLT_ROUNDS
3866 keep_dig:
3867 #endif
3868 *s++ = dig;
3869 if (i == ilim)
3870 break;
3871 b = multadd(b, 10, 0);
3872 if (mlo == mhi)
3873 mlo = mhi = multadd(mhi, 10, 0);
3874 else {
3875 mlo = multadd(mlo, 10, 0);
3876 mhi = multadd(mhi, 10, 0);
3880 else
3881 for (i = 1;; i++) {
3882 *s++ = dig = quorem(b,S) + '0';
3883 if (!b->x[0] && b->wds <= 1) {
3884 #ifdef SET_INEXACT
3885 inexact = 0;
3886 #endif
3887 goto ret;
3889 if (i >= ilim)
3890 break;
3891 b = multadd(b, 10, 0);
3894 /* Round off last digit */
3896 #ifdef Honor_FLT_ROUNDS
3897 switch (rounding) {
3898 case 0: goto trimzeros;
3899 case 2: goto roundoff;
3901 #endif
3902 b = lshift(b, 1);
3903 j = cmp(b, S);
3904 if (j > 0 || (j == 0 && (dig & 1))) {
3905 roundoff:
3906 while (*--s == '9')
3907 if (s == s0) {
3908 k++;
3909 *s++ = '1';
3910 goto ret;
3912 ++*s++;
3914 else {
3915 while (*--s == '0') ;
3916 s++;
3918 ret:
3919 Bfree(S);
3920 if (mhi) {
3921 if (mlo && mlo != mhi)
3922 Bfree(mlo);
3923 Bfree(mhi);
3925 ret1:
3926 #ifdef SET_INEXACT
3927 if (inexact) {
3928 if (!oldinexact) {
3929 word0(d) = Exp_1 + (70 << Exp_shift);
3930 word1(d) = 0;
3931 dval(d) += 1.;
3934 else if (!oldinexact)
3935 clear_inexact();
3936 #endif
3937 Bfree(b);
3938 *s = 0;
3939 *decpt = k + 1;
3940 if (rve)
3941 *rve = s;
3942 return s0;
3945 void
3946 ruby_each_words(const char *str, void (*func)(const char*, int, void*), void *arg)
3948 const char *end;
3949 int len;
3951 if (!str) return;
3952 for (; *str; str = end) {
3953 while (ISSPACE(*str) || *str == ',') str++;
3954 if (!*str) break;
3955 end = str;
3956 while (*end && !ISSPACE(*end) && *end != ',') end++;
3957 len = end - str;
3958 (*func)(str, len, arg);
3962 #ifdef __cplusplus
3964 #endif