1 /**********************************************************************
6 created at: Fri Mar 10 17:22:34 JST 1995
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
10 **********************************************************************/
12 #include "ruby/ruby.h"
21 #include "missing/file.h"
23 #if defined(__CYGWIN32__)
26 #define _unlink unlink
27 #define _access access
32 #include "ruby/util.h"
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') {
49 ruby_scan_hex(const char *start
, int len
, int *retlen
)
51 static char hexdigit
[] = "0123456789abcdef0123456789ABCDEF";
52 register const char *s
= start
;
53 register unsigned long retval
= 0;
56 while (len
-- && *s
&& (tmp
= strchr(hexdigit
, *s
))) {
58 retval
|= (tmp
- hexdigit
) & 15;
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
;
94 while ((c
= (unsigned char)*str
++) != '\0') {
96 if (d
== -1 || base
<= d
) {
97 *retlen
= (str
-1) - start
;
100 if (mul_overflow
< ret
)
108 *retlen
= (str
-1) - start
;
113 ruby_strtoul(const char *str
, char **endptr
, int base
)
119 const char *subject_found
= str
;
121 if (base
== 1 || 36 < base
) {
126 while ((c
= *str
) && ISSPACE(c
))
139 subject_found
= str
+1;
140 if (base
== 0 || base
== 16) {
141 if (str
[1] == 'x' || str
[1] == 'X') {
146 b
= base
== 0 ? 8 : 16;
156 b
= base
== 0 ? 10 : base
;
159 ret
= scan_digits(str
, b
, &len
, &overflow
);
162 subject_found
= str
+len
;
165 *endptr
= (char*)subject_found
;
181 #include <sys/types.h>
182 #include <sys/stat.h>
186 #if defined(HAVE_FCNTL_H)
191 # define S_ISDIR(m) ((m & S_IFMT) == S_IFDIR)
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
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
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)
244 * foo.bak => foo.$$$ (fallback)
245 * foo.$$$ => foo.~~~ (fallback)
246 * makefile => makefile.bak
248 * suffix = "~" (style 2)
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)
274 ruby_add_suffix(VALUE str
, const char *suffix
)
277 int extlen
= strlen(suffix
);
282 if (RSTRING_LEN(str
) > 1000)
283 rb_fatal("Cannot do inplace edit on long filename (%ld characters)",
286 #if defined(DJGPP) || defined(__CYGWIN32__) || defined(_WIN32)
288 slen
= RSTRING_LEN(str
);
289 rb_str_cat(str
, suffix
, extlen
);
291 if (_USE_LFN
) return;
293 if (valid_filename(RSTRING_PTR(str
))) return;
296 /* Fooey, style 0 failed. Fix str before continuing. */
297 rb_str_resize(str
, slen
);
301 t
= buf
; baselen
= 0; s
= RSTRING_PTR(str
);
302 while ((*t
= *s
) && *s
!= '.') {
304 if (*s
== '\\' || *s
== '/') baselen
= 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
;
317 else if (suffix
[1] == '\0') { /* Style 2 */
319 ext
[extlen
] = *suffix
;
320 ext
[++extlen
] = '\0';
322 else if (baselen
< 8) {
325 else if (ext
[3] != *suffix
) {
328 else if (buf
[7] != *suffix
) {
334 else { /* Style 3: Panic */
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)
344 valid_filename(const char *s
)
349 // It doesn't exist, so see if we can open it.
352 if ((fd
= _open(s
, O_CREAT
|O_EXCL
, 0666)) >= 0) {
354 _unlink(s
); /* don't leave it laying around */
357 else if (errno
== EEXIST
) {
358 /* if the file exists, then it's a valid filename! */
366 #if defined __DJGPP__
370 static char dbcs_table
[256];
382 memset(&r
, 0, sizeof(r
));
384 __dpmi_int(0x21, &r
);
385 offset
= r
.x
.ds
* 16 + r
.x
.si
;
389 dosmemget(offset
, sizeof vec
, &vec
);
390 if (!vec
.start
&& !vec
.end
)
392 for (i
= vec
.start
; i
<= vec
.end
; i
++)
399 mblen(const char *s
, size_t n
)
401 static int need_init
= 1;
407 if (n
== 0 || *s
== 0)
411 return dbcs_table
[(unsigned char)*s
] + 1;
418 struct PathList
*next
;
423 struct PathList
*head
;
428 push_element(const char *path
, VALUE vinfo
)
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
;
444 int __opendir_flags
= __OPENDIR_PRESERVE_CASE
;
447 __crt0_glob_function(char *path
)
449 int len
= strlen(path
);
452 char path_buffer
[PATH_MAX
];
453 char *buf
= path_buffer
;
455 struct PathInfo info
;
456 struct PathList
*plist
;
459 buf
= ruby_xmalloc(len
+ 1);
461 strncpy(buf
, path
, len
);
464 for (p
= buf
; *p
; p
+= mblen(p
, RUBY_MBCHAR_MAXSIZE
))
471 ruby_glob(buf
, 0, push_element
, (VALUE
)&info
);
473 if (buf
!= path_buffer
)
479 rv
= ruby_xmalloc((info
.count
+ 1) * sizeof (char *));
484 struct PathList
*cur
;
504 #define mmprepare(base, size) do {\
505 if (((long)base & (0x3)) == 0)\
506 if (size >= 16) mmkind = 1;\
509 high = (size & (~0xf));\
510 low = (size & 0x0c);\
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
)
521 register char *t
= a
+ high
;
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;
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
;}}}
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
)
545 register char *t
= a
+ high
;
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;
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
;}}}
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)
565 /*****************************************************/
567 /* qs6 (Quick sort function) */
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)))
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
);
598 if (stack
== top
) return; /* return if stack is empty */
603 if (L
+ size
== R
) { /* 2 elements */
604 if ((*cmp
)(L
,R
,d
) > 0) mmswap(L
,R
); goto nxt
;
608 t
= (r
- l
+ size
) / size
; /* number of elements */
609 m
= l
+ size
* (t
>> 1); /* calculate median value */
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
);
624 m3
= med3(p1
, p2
, p3
);
628 t
= size
*(t
>>2); /* number of bytes in splitting 4 */
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 */
640 for (p
=l
; p
<r
; p
+=size
) if ((*cmp
)(p
,p
+size
,d
) > 0) goto fail
;
643 fail
: goto loopA
; /*3-5-7*/
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 */
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 */
661 fail2
: mmswap(l
,r
); goto loopA
; /*7-5-3*/
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*/
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 */
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;}
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;}
697 mmswap(l
,r
); /* swap left and right */
700 loopB
: eq_l
= 1; eq_r
= 1; /* splitting type B */ /* left < median <= right */
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;}
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;}
716 mmswap(l
,r
); /* swap left and right */
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 */
731 ruby_strdup(const char *str
)
734 int len
= strlen(str
) + 1;
737 memcpy(tmp
, str
, len
);
747 char *buf
= xmalloc(size
);
749 while (!getcwd(buf
, size
)) {
750 if (errno
!= ERANGE
) {
752 rb_sys_fail("getcwd");
755 buf
= xrealloc(buf
, size
);
759 # define PATH_MAX 8192
761 char *buf
= xmalloc(PATH_MAX
+1);
765 rb_sys_fail("getwd");
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
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].
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
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
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
939 #define IEEE_LITTLE_ENDIAN
944 #undef IEEE_BIG_ENDIAN
945 #undef IEEE_LITTLE_ENDIAN
948 #if defined(__arm__) && !defined(__VFP_FP__)
949 #define IEEE_BIG_ENDIAN
950 #undef IEEE_LITTLE_ENDIAN
958 #define ULong unsigned int
959 #elif SIZEOF_LONG == 4
960 #define Long long int
961 #define ULong unsigned long int
965 #define Llong LONG_LONG
970 #define Bug(x) {fprintf(stderr, "%s\n", x); exit(1);}
981 extern void *MALLOC(size_t);
983 #define MALLOC malloc
986 #ifndef Omit_Private_Memory
988 #define PRIVATE_MEM 2304
990 #define PRIVATE_mem ((PRIVATE_MEM+sizeof(double)-1)/sizeof(double))
991 static double private_mem
[PRIVATE_mem
], *pmem_next
= private_mem
;
995 #undef Avoid_Underflow
996 #ifdef IEEE_BIG_ENDIAN
999 #ifdef IEEE_LITTLE_ENDIAN
1009 #define DBL_MAX_10_EXP 308
1010 #define DBL_MAX_EXP 1024
1012 #endif /*IEEE_Arith*/
1016 #define DBL_MAX_10_EXP 75
1017 #define DBL_MAX_EXP 63
1018 #define FLT_RADIX 16
1019 #define DBL_MAX 7.2370055773322621e+75
1024 #define DBL_MAX_10_EXP 38
1025 #define DBL_MAX_EXP 127
1027 #define DBL_MAX 1.7014118346046923e+38
1031 #define LONG_MAX 2147483647
1034 #else /* ifndef Bad_float_h */
1036 #endif /* Bad_float_h */
1046 #if defined(IEEE_LITTLE_ENDIAN) + defined(IEEE_BIG_ENDIAN) + defined(VAX) + defined(IBM) != 1
1047 Exactly one of IEEE_LITTLE_ENDIAN
, IEEE_BIG_ENDIAN
, VAX
, or IBM should be defined
.
1050 typedef union { double d
; ULong L
[2]; } U
;
1054 #ifdef IEEE_LITTLE_ENDIAN
1055 #define word0(x) ((ULong *)&x)[1]
1056 #define word1(x) ((ULong *)&x)[0]
1058 #define word0(x) ((ULong *)&x)[0]
1059 #define word1(x) ((ULong *)&x)[1]
1062 #ifdef IEEE_LITTLE_ENDIAN
1063 #define word0(x) ((U*)&x)->L[1]
1064 #define word1(x) ((U*)&x)->L[0]
1066 #define word0(x) ((U*)&x)->L[0]
1067 #define word1(x) ((U*)&x)->L[1]
1069 #define dval(x) ((U*)&x)->d
1072 /* The following definition of Storeinc is appropriate for MIPS processors.
1073 * An alternative that might be better on some machines is
1074 * #define Storeinc(a,b,c) (*a++ = b << 16 | c & 0xffff)
1076 #if defined(IEEE_LITTLE_ENDIAN) + defined(VAX) + defined(__arm__)
1077 #define Storeinc(a,b,c) (((unsigned short *)a)[1] = (unsigned short)b, \
1078 ((unsigned short *)a)[0] = (unsigned short)c, a++)
1080 #define Storeinc(a,b,c) (((unsigned short *)a)[0] = (unsigned short)b, \
1081 ((unsigned short *)a)[1] = (unsigned short)c, a++)
1084 /* #define P DBL_MANT_DIG */
1085 /* Ten_pmax = floor(P*log(2)/log(5)) */
1086 /* Bletch = (highest power of 2 < DBL_MAX_10_EXP) / 16 */
1087 /* Quick_max = floor((P-1)*log(FLT_RADIX)/log(10) - 1) */
1088 /* Int_max = floor(P*log(FLT_RADIX)/log(10) - 1) */
1091 #define Exp_shift 20
1092 #define Exp_shift1 20
1093 #define Exp_msk1 0x100000
1094 #define Exp_msk11 0x100000
1095 #define Exp_mask 0x7ff00000
1098 #define Emin (-1022)
1099 #define Exp_1 0x3ff00000
1100 #define Exp_11 0x3ff00000
1102 #define Frac_mask 0xfffff
1103 #define Frac_mask1 0xfffff
1106 #define Bndry_mask 0xfffff
1107 #define Bndry_mask1 0xfffff
1109 #define Sign_bit 0x80000000
1113 #define Quick_max 14
1115 #ifndef NO_IEEE_Scale
1116 #define Avoid_Underflow
1117 #ifdef Flush_Denorm /* debugging option */
1118 #undef Sudden_Underflow
1124 #define Flt_Rounds FLT_ROUNDS
1126 #define Flt_Rounds 1
1128 #endif /*Flt_Rounds*/
1130 #ifdef Honor_FLT_ROUNDS
1131 #define Rounding rounding
1132 #undef Check_FLT_ROUNDS
1133 #define Check_FLT_ROUNDS
1135 #define Rounding Flt_Rounds
1138 #else /* ifndef IEEE_Arith */
1139 #undef Check_FLT_ROUNDS
1140 #undef Honor_FLT_ROUNDS
1142 #undef Sudden_Underflow
1143 #define Sudden_Underflow
1146 #define Flt_Rounds 0
1147 #define Exp_shift 24
1148 #define Exp_shift1 24
1149 #define Exp_msk1 0x1000000
1150 #define Exp_msk11 0x1000000
1151 #define Exp_mask 0x7f000000
1154 #define Exp_1 0x41000000
1155 #define Exp_11 0x41000000
1156 #define Ebits 8 /* exponent has 7 bits, but 8 is the right value in b2d */
1157 #define Frac_mask 0xffffff
1158 #define Frac_mask1 0xffffff
1161 #define Bndry_mask 0xefffff
1162 #define Bndry_mask1 0xffffff
1164 #define Sign_bit 0x80000000
1166 #define Tiny0 0x100000
1168 #define Quick_max 14
1172 #define Flt_Rounds 1
1173 #define Exp_shift 23
1174 #define Exp_shift1 7
1175 #define Exp_msk1 0x80
1176 #define Exp_msk11 0x800000
1177 #define Exp_mask 0x7f80
1180 #define Exp_1 0x40800000
1181 #define Exp_11 0x4080
1183 #define Frac_mask 0x7fffff
1184 #define Frac_mask1 0xffff007f
1187 #define Bndry_mask 0xffff007f
1188 #define Bndry_mask1 0xffff007f
1190 #define Sign_bit 0x8000
1194 #define Quick_max 15
1196 #endif /* IBM, VAX */
1197 #endif /* IEEE_Arith */
1200 #define ROUND_BIASED
1204 #define rounded_product(a,b) a = rnd_prod(a, b)
1205 #define rounded_quotient(a,b) a = rnd_quot(a, b)
1206 extern double rnd_prod(double, double), rnd_quot(double, double);
1208 #define rounded_product(a,b) a *= b
1209 #define rounded_quotient(a,b) a /= b
1212 #define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
1213 #define Big1 0xffffffff
1219 #define FFFFFFFF 0xffffffffUL
1225 /* When Pack_32 is not defined, we store 16 bits per 32-bit Long.
1226 * This makes some inner loops simpler and sometimes saves work
1227 * during multiplications, but it often seems to make things slightly
1228 * slower. Hence the default is now to store 32 bits per Long.
1231 #else /* long long available */
1233 #define Llong long long
1236 #define ULLong unsigned Llong
1238 #endif /* NO_LONG_LONG */
1240 #ifndef MULTIPLE_THREADS
1241 #define ACQUIRE_DTOA_LOCK(n) /*nothing*/
1242 #define FREE_DTOA_LOCK(n) /*nothing*/
1248 struct Bigint
*next
;
1249 int k
, maxwds
, sign
, wds
;
1253 typedef struct Bigint Bigint
;
1255 static Bigint
*freelist
[Kmax
+1];
1262 #ifndef Omit_Private_Memory
1266 ACQUIRE_DTOA_LOCK(0);
1267 if ((rv
= freelist
[k
]) != 0) {
1268 freelist
[k
] = rv
->next
;
1272 #ifdef Omit_Private_Memory
1273 rv
= (Bigint
*)MALLOC(sizeof(Bigint
) + (x
-1)*sizeof(ULong
));
1275 len
= (sizeof(Bigint
) + (x
-1)*sizeof(ULong
) + sizeof(double) - 1)
1277 if (pmem_next
- private_mem
+ len
<= PRIVATE_mem
) {
1278 rv
= (Bigint
*)pmem_next
;
1282 rv
= (Bigint
*)MALLOC(len
*sizeof(double));
1288 rv
->sign
= rv
->wds
= 0;
1296 ACQUIRE_DTOA_LOCK(0);
1297 v
->next
= freelist
[v
->k
];
1303 #define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign, \
1304 y->wds*sizeof(Long) + 2*sizeof(int))
1307 multadd(Bigint
*b
, int m
, int a
) /* multiply by m and add a */
1327 y
= *x
* (ULLong
)m
+ carry
;
1329 *x
++ = y
& FFFFFFFF
;
1333 y
= (xi
& 0xffff) * m
+ carry
;
1334 z
= (xi
>> 16) * m
+ (y
>> 16);
1336 *x
++ = (z
<< 16) + (y
& 0xffff);
1343 } while (++i
< wds
);
1345 if (wds
>= b
->maxwds
) {
1346 b1
= Balloc(b
->k
+1);
1351 b
->x
[wds
++] = carry
;
1358 s2b(const char *s
, int nd0
, int nd
, ULong y9
)
1365 for (k
= 0, y
= 1; x
> y
; y
<<= 1, k
++) ;
1372 b
->x
[0] = y9
& 0xffff;
1373 b
->wds
= (b
->x
[1] = y9
>> 16) ? 2 : 1;
1380 b
= multadd(b
, 10, *s
++ - '0');
1381 } while (++i
< nd0
);
1387 b
= multadd(b
, 10, *s
++ - '0');
1392 hi0bits(register ULong x
)
1396 if (!(x
& 0xffff0000)) {
1400 if (!(x
& 0xff000000)) {
1404 if (!(x
& 0xf0000000)) {
1408 if (!(x
& 0xc0000000)) {
1412 if (!(x
& 0x80000000)) {
1414 if (!(x
& 0x40000000))
1424 register ULong x
= *y
;
1437 if (!(x
& 0xffff)) {
1475 mult(Bigint
*a
, Bigint
*b
)
1479 ULong
*x
, *xa
, *xae
, *xb
, *xbe
, *xc
, *xc0
;
1490 if (a
->wds
< b
->wds
) {
1502 for (x
= c
->x
, xa
= x
+ wc
; x
< xa
; x
++)
1510 for (; xb
< xbe
; xc0
++) {
1511 if ((y
= *xb
++) != 0) {
1516 z
= *x
++ * (ULLong
)y
+ *xc
+ carry
;
1518 *xc
++ = z
& FFFFFFFF
;
1525 for (; xb
< xbe
; xb
++, xc0
++) {
1526 if (y
= *xb
& 0xffff) {
1531 z
= (*x
& 0xffff) * y
+ (*xc
& 0xffff) + carry
;
1533 z2
= (*x
++ >> 16) * y
+ (*xc
>> 16) + carry
;
1535 Storeinc(xc
, z2
, z
);
1539 if (y
= *xb
>> 16) {
1545 z
= (*x
& 0xffff) * y
+ (*xc
>> 16) + carry
;
1547 Storeinc(xc
, z
, z2
);
1548 z2
= (*x
++ >> 16) * y
+ (*xc
& 0xffff) + carry
;
1555 for (; xb
< xbe
; xc0
++) {
1561 z
= *x
++ * y
+ *xc
+ carry
;
1570 for (xc0
= c
->x
, xc
= xc0
+ wc
; wc
> 0 && !*--xc
; --wc
) ;
1578 pow5mult(Bigint
*b
, int k
)
1580 Bigint
*b1
, *p5
, *p51
;
1582 static int p05
[3] = { 5, 25, 125 };
1584 if ((i
= k
& 3) != 0)
1585 b
= multadd(b
, p05
[i
-1], 0);
1591 #ifdef MULTIPLE_THREADS
1592 ACQUIRE_DTOA_LOCK(1);
1594 p5
= p5s
= i2b(625);
1599 p5
= p5s
= i2b(625);
1611 if (!(p51
= p5
->next
)) {
1612 #ifdef MULTIPLE_THREADS
1613 ACQUIRE_DTOA_LOCK(1);
1614 if (!(p51
= p5
->next
)) {
1615 p51
= p5
->next
= mult(p5
,p5
);
1620 p51
= p5
->next
= mult(p5
,p5
);
1630 lshift(Bigint
*b
, int k
)
1634 ULong
*x
, *x1
, *xe
, z
;
1642 n1
= n
+ b
->wds
+ 1;
1643 for (i
= b
->maxwds
; n1
> i
; i
<<= 1)
1647 for (i
= 0; i
< n
; i
++)
1656 *x1
++ = *x
<< k
| z
;
1667 *x1
++ = *x
<< k
& 0xffff | z
;
1684 cmp(Bigint
*a
, Bigint
*b
)
1686 ULong
*xa
, *xa0
, *xb
, *xb0
;
1692 if (i
> 1 && !a
->x
[i
-1])
1693 Bug("cmp called with a->x[a->wds-1] == 0");
1694 if (j
> 1 && !b
->x
[j
-1])
1695 Bug("cmp called with b->x[b->wds-1] == 0");
1705 return *xa
< *xb
? -1 : 1;
1713 diff(Bigint
*a
, Bigint
*b
)
1717 ULong
*xa
, *xae
, *xb
, *xbe
, *xc
;
1754 y
= (ULLong
)*xa
++ - *xb
++ - borrow
;
1755 borrow
= y
>> 32 & (ULong
)1;
1756 *xc
++ = y
& FFFFFFFF
;
1760 borrow
= y
>> 32 & (ULong
)1;
1761 *xc
++ = y
& FFFFFFFF
;
1766 y
= (*xa
& 0xffff) - (*xb
& 0xffff) - borrow
;
1767 borrow
= (y
& 0x10000) >> 16;
1768 z
= (*xa
++ >> 16) - (*xb
++ >> 16) - borrow
;
1769 borrow
= (z
& 0x10000) >> 16;
1773 y
= (*xa
& 0xffff) - borrow
;
1774 borrow
= (y
& 0x10000) >> 16;
1775 z
= (*xa
++ >> 16) - borrow
;
1776 borrow
= (z
& 0x10000) >> 16;
1781 y
= *xa
++ - *xb
++ - borrow
;
1782 borrow
= (y
& 0x10000) >> 16;
1787 borrow
= (y
& 0x10000) >> 16;
1804 L
= (word0(x
) & Exp_mask
) - (P
-1)*Exp_msk1
;
1805 #ifndef Avoid_Underflow
1806 #ifndef Sudden_Underflow
1815 #ifndef Avoid_Underflow
1816 #ifndef Sudden_Underflow
1819 L
= -L
>> Exp_shift
;
1820 if (L
< Exp_shift
) {
1821 word0(a
) = 0x80000 >> L
;
1827 word1(a
) = L
>= 31 ? 1 : 1 << 31 - L
;
1836 b2d(Bigint
*a
, int *e
)
1838 ULong
*xa
, *xa0
, w
, y
, z
;
1852 if (!y
) Bug("zero y in b2d");
1858 d0
= Exp_1
| y
>> (Ebits
- k
);
1859 w
= xa
> xa0
? *--xa
: 0;
1860 d1
= y
<< ((32-Ebits
) + k
) | w
>> (Ebits
- k
);
1863 z
= xa
> xa0
? *--xa
: 0;
1865 d0
= Exp_1
| y
<< k
| z
>> (32 - k
);
1866 y
= xa
> xa0
? *--xa
: 0;
1867 d1
= z
<< k
| y
>> (32 - k
);
1874 if (k
< Ebits
+ 16) {
1875 z
= xa
> xa0
? *--xa
: 0;
1876 d0
= Exp_1
| y
<< k
- Ebits
| z
>> Ebits
+ 16 - k
;
1877 w
= xa
> xa0
? *--xa
: 0;
1878 y
= xa
> xa0
? *--xa
: 0;
1879 d1
= z
<< k
+ 16 - Ebits
| w
<< k
- Ebits
| y
>> 16 + Ebits
- k
;
1882 z
= xa
> xa0
? *--xa
: 0;
1883 w
= xa
> xa0
? *--xa
: 0;
1885 d0
= Exp_1
| y
<< k
+ 16 | z
<< k
| w
>> 16 - k
;
1886 y
= xa
> xa0
? *--xa
: 0;
1887 d1
= w
<< k
+ 16 | y
<< k
;
1891 word0(d
) = d0
>> 16 | d0
<< 16;
1892 word1(d
) = d1
>> 16 | d1
<< 16;
1901 d2b(double d
, int *e
, int *bits
)
1906 #ifndef Sudden_Underflow
1911 d0
= word0(d
) >> 16 | word0(d
) << 16;
1912 d1
= word1(d
) >> 16 | word1(d
) << 16;
1926 d0
&= 0x7fffffff; /* clear sign bit, which we ignore */
1927 #ifdef Sudden_Underflow
1928 de
= (int)(d0
>> Exp_shift
);
1933 if ((de
= (int)(d0
>> Exp_shift
)) != 0)
1937 if ((y
= d1
) != 0) {
1938 if ((k
= lo0bits(&y
)) != 0) {
1939 x
[0] = y
| z
<< (32 - k
);
1944 #ifndef Sudden_Underflow
1947 b
->wds
= (x
[1] = z
) ? 2 : 1;
1952 Bug("Zero passed to d2b");
1956 #ifndef Sudden_Underflow
1964 if (k
= lo0bits(&y
))
1966 x
[0] = y
| z
<< 32 - k
& 0xffff;
1967 x
[1] = z
>> k
- 16 & 0xffff;
1973 x
[1] = y
>> 16 | z
<< 16 - k
& 0xffff;
1974 x
[2] = z
>> k
& 0xffff;
1989 Bug("Zero passed to d2b");
2007 #ifndef Sudden_Underflow
2011 *e
= (de
- Bias
- (P
-1) << 2) + k
;
2012 *bits
= 4*P
+ 8 - k
- hi0bits(word0(d
) & Frac_mask
);
2014 *e
= de
- Bias
- (P
-1) + k
;
2017 #ifndef Sudden_Underflow
2020 *e
= de
- Bias
- (P
-1) + 1 + k
;
2022 *bits
= 32*i
- hi0bits(x
[i
-1]);
2024 *bits
= (i
+2)*16 - hi0bits(x
[i
]);
2034 ratio(Bigint
*a
, Bigint
*b
)
2039 dval(da
) = b2d(a
, &ka
);
2040 dval(db
) = b2d(b
, &kb
);
2042 k
= ka
- kb
+ 32*(a
->wds
- b
->wds
);
2044 k
= ka
- kb
+ 16*(a
->wds
- b
->wds
);
2048 word0(da
) += (k
>> 2)*Exp_msk1
;
2054 word0(db
) += (k
>> 2)*Exp_msk1
;
2060 word0(da
) += k
*Exp_msk1
;
2063 word0(db
) += k
*Exp_msk1
;
2066 return dval(da
) / dval(db
);
2071 1e0
, 1e1
, 1e2
, 1e3
, 1e4
, 1e5
, 1e6
, 1e7
, 1e8
, 1e9
,
2072 1e10
, 1e11
, 1e12
, 1e13
, 1e14
, 1e15
, 1e16
, 1e17
, 1e18
, 1e19
,
2081 bigtens
[] = { 1e16
, 1e32
, 1e64
, 1e128
, 1e256
};
2082 static const double tinytens
[] = { 1e-16, 1e-32, 1e-64, 1e-128,
2083 #ifdef Avoid_Underflow
2084 9007199254740992.*9007199254740992.e
-256
2085 /* = 2^106 * 1e-53 */
2090 /* The factor of 2^53 in tinytens[4] helps us avoid setting the underflow */
2091 /* flag unnecessarily. It leads to a song and dance at the end of strtod. */
2092 #define Scale_Bit 0x10
2096 bigtens
[] = { 1e16
, 1e32
, 1e64
};
2097 static const double tinytens
[] = { 1e-16, 1e-32, 1e-64 };
2100 bigtens
[] = { 1e16
, 1e32
};
2101 static const double tinytens
[] = { 1e-16, 1e-32 };
2113 #define NAN_WORD0 0x7ff80000
2121 match(const char **sp
, char *t
)
2124 const char *s
= *sp
;
2127 if ((c
= *++s
) >= 'A' && c
<= 'Z')
2138 hexnan(double *rvp
, const char **sp
)
2142 int havedig
, udx0
, xshift
;
2145 havedig
= xshift
= 0;
2148 while (c
= *(const unsigned char*)++s
) {
2149 if (c
>= '0' && c
<= '9')
2151 else if (c
>= 'a' && c
<= 'f')
2153 else if (c
>= 'A' && c
<= 'F')
2155 else if (c
<= ' ') {
2156 if (udx0
&& havedig
) {
2162 else if (/*(*/ c
== ')' && havedig
) {
2167 return; /* invalid form: don't change *sp */
2175 x
[0] = (x
[0] << 4) | (x
[1] >> 28);
2176 x
[1] = (x
[1] << 4) | c
;
2178 if ((x
[0] &= 0xfffff) || x
[1]) {
2179 word0(*rvp
) = Exp_mask
| x
[0];
2183 #endif /*No_Hex_NaN*/
2184 #endif /* INFNAN_CHECK */
2187 ruby_strtod(const char *s00
, char **se
)
2189 #ifdef Avoid_Underflow
2192 int bb2
, bb5
, bbe
, bd2
, bd5
, bbbits
, bs2
, c
, dsign
,
2193 e
, e1
, esign
, i
, j
, k
, nd
, nd0
, nf
, nz
, nz0
, sign
;
2194 const char *s
, *s0
, *s1
;
2195 double aadj
, aadj1
, adj
, rv
, rv0
;
2198 Bigint
*bb
, *bb1
, *bd
, *bd0
, *bs
, *delta
;
2200 int inexact
, oldinexact
;
2202 #ifdef Honor_FLT_ROUNDS
2209 sign
= nz0
= nz
= 0;
2235 while (*++s
== '0') ;
2241 for (nd
= nf
= 0; (c
= *s
) >= '0' && c
<= '9'; nd
++, s
++)
2248 s1
= localeconv()->decimal_point
;
2269 for (; c
== '0'; c
= *++s
)
2271 if (c
> '0' && c
<= '9') {
2279 for (; c
>= '0' && c
<= '9'; c
= *++s
) {
2284 for (i
= 1; i
< nz
; i
++)
2287 else if (nd
<= DBL_DIG
+ 1)
2291 else if (nd
<= DBL_DIG
+ 1)
2299 if (c
== 'e' || c
== 'E') {
2300 if (!nd
&& !nz
&& !nz0
) {
2311 if (c
>= '0' && c
<= '9') {
2314 if (c
> '0' && c
<= '9') {
2317 while ((c
= *++s
) >= '0' && c
<= '9')
2319 if (s
- s1
> 8 || L
> 19999)
2320 /* Avoid confusion from exponents
2321 * so large that e might overflow.
2323 e
= 19999; /* safe for 16 bit ints */
2338 /* Check for Nan and Infinity */
2342 if (match(&s
,"nf")) {
2344 if (!match(&s
,"inity"))
2346 word0(rv
) = 0x7ff00000;
2353 if (match(&s
, "an")) {
2354 word0(rv
) = NAN_WORD0
;
2355 word1(rv
) = NAN_WORD1
;
2357 if (*s
== '(') /*)*/
2363 #endif /* INFNAN_CHECK */
2372 /* Now we have nd0 digits, starting at s0, followed by a
2373 * decimal point, followed by nd-nd0 digits. The number we're
2374 * after is the integer represented by those digits times
2379 k
= nd
< DBL_DIG
+ 1 ? nd
: DBL_DIG
+ 1;
2384 oldinexact
= get_inexact();
2386 dval(rv
) = tens
[k
- 9] * dval(rv
) + z
;
2390 #ifndef RND_PRODQUOT
2391 #ifndef Honor_FLT_ROUNDS
2399 if (e
<= Ten_pmax
) {
2401 goto vax_ovfl_check
;
2403 #ifdef Honor_FLT_ROUNDS
2404 /* round correctly FLT_ROUNDS = 2 or 3 */
2410 /* rv = */ rounded_product(dval(rv
), tens
[e
]);
2415 if (e
<= Ten_pmax
+ i
) {
2416 /* A fancier test would sometimes let us do
2417 * this for larger i values.
2419 #ifdef Honor_FLT_ROUNDS
2420 /* round correctly FLT_ROUNDS = 2 or 3 */
2427 dval(rv
) *= tens
[i
];
2429 /* VAX exponent range is so narrow we must
2430 * worry about overflow here...
2433 word0(rv
) -= P
*Exp_msk1
;
2434 /* rv = */ rounded_product(dval(rv
), tens
[e
]);
2435 if ((word0(rv
) & Exp_mask
)
2436 > Exp_msk1
*(DBL_MAX_EXP
+Bias
-1-P
))
2438 word0(rv
) += P
*Exp_msk1
;
2440 /* rv = */ rounded_product(dval(rv
), tens
[e
]);
2445 #ifndef Inaccurate_Divide
2446 else if (e
>= -Ten_pmax
) {
2447 #ifdef Honor_FLT_ROUNDS
2448 /* round correctly FLT_ROUNDS = 2 or 3 */
2454 /* rv = */ rounded_quotient(dval(rv
), tens
[-e
]);
2465 oldinexact
= get_inexact();
2467 #ifdef Avoid_Underflow
2470 #ifdef Honor_FLT_ROUNDS
2471 if ((rounding
= Flt_Rounds
) >= 2) {
2473 rounding
= rounding
== 2 ? 0 : 2;
2479 #endif /*IEEE_Arith*/
2481 /* Get starting approximation = rv * 10**e1 */
2484 if ((i
= e1
& 15) != 0)
2485 dval(rv
) *= tens
[i
];
2487 if (e1
> DBL_MAX_10_EXP
) {
2492 /* Can't trust HUGE_VAL */
2494 #ifdef Honor_FLT_ROUNDS
2496 case 0: /* toward 0 */
2497 case 3: /* toward -infinity */
2502 word0(rv
) = Exp_mask
;
2505 #else /*Honor_FLT_ROUNDS*/
2506 word0(rv
) = Exp_mask
;
2508 #endif /*Honor_FLT_ROUNDS*/
2510 /* set overflow bit */
2512 dval(rv0
) *= dval(rv0
);
2514 #else /*IEEE_Arith*/
2517 #endif /*IEEE_Arith*/
2523 for (j
= 0; e1
> 1; j
++, e1
>>= 1)
2525 dval(rv
) *= bigtens
[j
];
2526 /* The last multiplication could overflow. */
2527 word0(rv
) -= P
*Exp_msk1
;
2528 dval(rv
) *= bigtens
[j
];
2529 if ((z
= word0(rv
) & Exp_mask
)
2530 > Exp_msk1
*(DBL_MAX_EXP
+Bias
-P
))
2532 if (z
> Exp_msk1
*(DBL_MAX_EXP
+Bias
-1-P
)) {
2533 /* set to largest number */
2534 /* (Can't trust DBL_MAX) */
2539 word0(rv
) += P
*Exp_msk1
;
2544 if ((i
= e1
& 15) != 0)
2545 dval(rv
) /= tens
[i
];
2547 if (e1
>= 1 << n_bigtens
)
2549 #ifdef Avoid_Underflow
2552 for (j
= 0; e1
> 0; j
++, e1
>>= 1)
2554 dval(rv
) *= tinytens
[j
];
2555 if (scale
&& (j
= 2*P
+ 1 - ((word0(rv
) & Exp_mask
)
2556 >> Exp_shift
)) > 0) {
2557 /* scaled rv is denormal; zap j low bits */
2561 word0(rv
) = (P
+2)*Exp_msk1
;
2563 word0(rv
) &= 0xffffffff << (j
-32);
2566 word1(rv
) &= 0xffffffff << j
;
2569 for (j
= 0; e1
> 1; j
++, e1
>>= 1)
2571 dval(rv
) *= tinytens
[j
];
2572 /* The last multiplication could underflow. */
2573 dval(rv0
) = dval(rv
);
2574 dval(rv
) *= tinytens
[j
];
2576 dval(rv
) = 2.*dval(rv0
);
2577 dval(rv
) *= tinytens
[j
];
2589 #ifndef Avoid_Underflow
2592 /* The refinement below will clean
2593 * this approximation up.
2600 /* Now the hard part -- adjusting rv to the correct value.*/
2602 /* Put digits into bd: true value = bd * 10^e */
2604 bd0
= s2b(s0
, nd0
, nd
, y
);
2607 bd
= Balloc(bd0
->k
);
2609 bb
= d2b(dval(rv
), &bbe
, &bbbits
); /* rv = bb * 2^bbe */
2625 #ifdef Honor_FLT_ROUNDS
2629 #ifdef Avoid_Underflow
2631 i
= j
+ bbbits
- 1; /* logb(rv) */
2632 if (i
< Emin
) /* denormal */
2636 #else /*Avoid_Underflow*/
2637 #ifdef Sudden_Underflow
2639 j
= 1 + 4*P
- 3 - bbbits
+ ((bbe
+ bbbits
- 1) & 3);
2643 #else /*Sudden_Underflow*/
2645 i
= j
+ bbbits
- 1; /* logb(rv) */
2646 if (i
< Emin
) /* denormal */
2650 #endif /*Sudden_Underflow*/
2651 #endif /*Avoid_Underflow*/
2654 #ifdef Avoid_Underflow
2657 i
= bb2
< bd2
? bb2
: bd2
;
2666 bs
= pow5mult(bs
, bb5
);
2672 bb
= lshift(bb
, bb2
);
2674 bd
= pow5mult(bd
, bd5
);
2676 bd
= lshift(bd
, bd2
);
2678 bs
= lshift(bs
, bs2
);
2679 delta
= diff(bb
, bd
);
2680 dsign
= delta
->sign
;
2683 #ifdef Honor_FLT_ROUNDS
2684 if (rounding
!= 1) {
2686 /* Error is less than an ulp */
2687 if (!delta
->x
[0] && delta
->wds
<= 1) {
2703 && !(word0(rv
) & Frac_mask
)) {
2704 y
= word0(rv
) & Exp_mask
;
2705 #ifdef Avoid_Underflow
2706 if (!scale
|| y
> 2*P
*Exp_msk1
)
2711 delta
= lshift(delta
,Log2P
);
2712 if (cmp(delta
, bs
) <= 0)
2717 #ifdef Avoid_Underflow
2718 if (scale
&& (y
= word0(rv
) & Exp_mask
)
2720 word0(adj
) += (2*P
+1)*Exp_msk1
- y
;
2722 #ifdef Sudden_Underflow
2723 if ((word0(rv
) & Exp_mask
) <=
2725 word0(rv
) += P
*Exp_msk1
;
2726 dval(rv
) += adj
*ulp(dval(rv
));
2727 word0(rv
) -= P
*Exp_msk1
;
2730 #endif /*Sudden_Underflow*/
2731 #endif /*Avoid_Underflow*/
2732 dval(rv
) += adj
*ulp(dval(rv
));
2736 adj
= ratio(delta
, bs
);
2739 if (adj
<= 0x7ffffffe) {
2740 /* adj = rounding ? ceil(adj) : floor(adj); */
2743 if (!((rounding
>>1) ^ dsign
))
2748 #ifdef Avoid_Underflow
2749 if (scale
&& (y
= word0(rv
) & Exp_mask
) <= 2*P
*Exp_msk1
)
2750 word0(adj
) += (2*P
+1)*Exp_msk1
- y
;
2752 #ifdef Sudden_Underflow
2753 if ((word0(rv
) & Exp_mask
) <= P
*Exp_msk1
) {
2754 word0(rv
) += P
*Exp_msk1
;
2755 adj
*= ulp(dval(rv
));
2760 word0(rv
) -= P
*Exp_msk1
;
2763 #endif /*Sudden_Underflow*/
2764 #endif /*Avoid_Underflow*/
2765 adj
*= ulp(dval(rv
));
2772 #endif /*Honor_FLT_ROUNDS*/
2775 /* Error is less than half an ulp -- check for
2776 * special case of mantissa a power of two.
2778 if (dsign
|| word1(rv
) || word0(rv
) & Bndry_mask
2780 #ifdef Avoid_Underflow
2781 || (word0(rv
) & Exp_mask
) <= (2*P
+1)*Exp_msk1
2783 || (word0(rv
) & Exp_mask
) <= Exp_msk1
2788 if (!delta
->x
[0] && delta
->wds
<= 1)
2793 if (!delta
->x
[0] && delta
->wds
<= 1) {
2800 delta
= lshift(delta
,Log2P
);
2801 if (cmp(delta
, bs
) > 0)
2806 /* exactly half-way between */
2808 if ((word0(rv
) & Bndry_mask1
) == Bndry_mask1
2810 #ifdef Avoid_Underflow
2811 (scale
&& (y
= word0(rv
) & Exp_mask
) <= 2*P
*Exp_msk1
)
2812 ? (0xffffffff & (0xffffffff << (2*P
+1-(y
>>Exp_shift
)))) :
2815 /*boundary case -- increment exponent*/
2816 word0(rv
) = (word0(rv
) & Exp_mask
)
2823 #ifdef Avoid_Underflow
2829 else if (!(word0(rv
) & Bndry_mask
) && !word1(rv
)) {
2831 /* boundary case -- decrement exponent */
2832 #ifdef Sudden_Underflow /*{{*/
2833 L
= word0(rv
) & Exp_mask
;
2837 #ifdef Avoid_Underflow
2838 if (L
<= (scale
? (2*P
+1)*Exp_msk1
: Exp_msk1
))
2841 #endif /*Avoid_Underflow*/
2845 #else /*Sudden_Underflow}{*/
2846 #ifdef Avoid_Underflow
2848 L
= word0(rv
) & Exp_mask
;
2849 if (L
<= (2*P
+1)*Exp_msk1
) {
2850 if (L
> (P
+2)*Exp_msk1
)
2851 /* round even ==> */
2854 /* rv = smallest denormal */
2858 #endif /*Avoid_Underflow*/
2859 L
= (word0(rv
) & Exp_mask
) - Exp_msk1
;
2860 #endif /*Sudden_Underflow}}*/
2861 word0(rv
) = L
| Bndry_mask1
;
2862 word1(rv
) = 0xffffffff;
2869 #ifndef ROUND_BIASED
2870 if (!(word1(rv
) & LSB
))
2874 dval(rv
) += ulp(dval(rv
));
2875 #ifndef ROUND_BIASED
2877 dval(rv
) -= ulp(dval(rv
));
2878 #ifndef Sudden_Underflow
2883 #ifdef Avoid_Underflow
2889 if ((aadj
= ratio(delta
, bs
)) <= 2.) {
2892 else if (word1(rv
) || word0(rv
) & Bndry_mask
) {
2893 #ifndef Sudden_Underflow
2894 if (word1(rv
) == Tiny1
&& !word0(rv
))
2901 /* special case -- power of FLT_RADIX to be */
2902 /* rounded down... */
2904 if (aadj
< 2./FLT_RADIX
)
2905 aadj
= 1./FLT_RADIX
;
2913 aadj1
= dsign
? aadj
: -aadj
;
2914 #ifdef Check_FLT_ROUNDS
2916 case 2: /* towards +infinity */
2919 case 0: /* towards 0 */
2920 case 3: /* towards -infinity */
2924 if (Flt_Rounds
== 0)
2926 #endif /*Check_FLT_ROUNDS*/
2928 y
= word0(rv
) & Exp_mask
;
2930 /* Check for overflow */
2932 if (y
== Exp_msk1
*(DBL_MAX_EXP
+Bias
-1)) {
2933 dval(rv0
) = dval(rv
);
2934 word0(rv
) -= P
*Exp_msk1
;
2935 adj
= aadj1
* ulp(dval(rv
));
2937 if ((word0(rv
) & Exp_mask
) >=
2938 Exp_msk1
*(DBL_MAX_EXP
+Bias
-P
)) {
2939 if (word0(rv0
) == Big0
&& word1(rv0
) == Big1
)
2946 word0(rv
) += P
*Exp_msk1
;
2949 #ifdef Avoid_Underflow
2950 if (scale
&& y
<= 2*P
*Exp_msk1
) {
2951 if (aadj
<= 0x7fffffff) {
2952 if ((z
= aadj
) <= 0)
2955 aadj1
= dsign
? aadj
: -aadj
;
2957 word0(aadj1
) += (2*P
+1)*Exp_msk1
- y
;
2959 adj
= aadj1
* ulp(dval(rv
));
2962 #ifdef Sudden_Underflow
2963 if ((word0(rv
) & Exp_mask
) <= P
*Exp_msk1
) {
2964 dval(rv0
) = dval(rv
);
2965 word0(rv
) += P
*Exp_msk1
;
2966 adj
= aadj1
* ulp(dval(rv
));
2969 if ((word0(rv
) & Exp_mask
) < P
*Exp_msk1
)
2971 if ((word0(rv
) & Exp_mask
) <= P
*Exp_msk1
)
2974 if (word0(rv0
) == Tiny0
&& word1(rv0
) == Tiny1
)
2981 word0(rv
) -= P
*Exp_msk1
;
2984 adj
= aadj1
* ulp(dval(rv
));
2987 #else /*Sudden_Underflow*/
2988 /* Compute adj so that the IEEE rounding rules will
2989 * correctly round rv + adj in some half-way cases.
2990 * If rv * ulp(rv) is denormalized (i.e.,
2991 * y <= (P-1)*Exp_msk1), we must adjust aadj to avoid
2992 * trouble from bits lost to denormalization;
2993 * example: 1.2e-307 .
2995 if (y
<= (P
-1)*Exp_msk1
&& aadj
> 1.) {
2996 aadj1
= (double)(int)(aadj
+ 0.5);
3000 adj
= aadj1
* ulp(dval(rv
));
3002 #endif /*Sudden_Underflow*/
3003 #endif /*Avoid_Underflow*/
3005 z
= word0(rv
) & Exp_mask
;
3007 #ifdef Avoid_Underflow
3011 /* Can we stop now? */
3014 /* The tolerances below are conservative. */
3015 if (dsign
|| word1(rv
) || word0(rv
) & Bndry_mask
) {
3016 if (aadj
< .4999999 || aadj
> .5000001)
3019 else if (aadj
< .4999999/FLT_RADIX
)
3032 word0(rv0
) = Exp_1
+ (70 << Exp_shift
);
3037 else if (!oldinexact
)
3040 #ifdef Avoid_Underflow
3042 word0(rv0
) = Exp_1
- 2*P
*Exp_msk1
;
3044 dval(rv
) *= dval(rv0
);
3046 /* try to avoid the bug of testing an 8087 register value */
3047 if (word0(rv
) == 0 && word1(rv
) == 0)
3051 #endif /* Avoid_Underflow */
3053 if (inexact
&& !(word0(rv
) & Exp_mask
)) {
3054 /* set underflow bit */
3056 dval(rv0
) *= dval(rv0
);
3068 return sign
? -dval(rv
) : dval(rv
);
3072 quorem(Bigint
*b
, Bigint
*S
)
3075 ULong
*bx
, *bxe
, q
, *sx
, *sxe
;
3077 ULLong borrow
, carry
, y
, ys
;
3079 ULong borrow
, carry
, y
, ys
;
3087 /*debug*/ if (b
->wds
> n
)
3088 /*debug*/ Bug("oversize b in quorem");
3096 q
= *bxe
/ (*sxe
+ 1); /* ensure q <= true quotient */
3098 /*debug*/ if (q
> 9)
3099 /*debug*/ Bug("oversized quotient in quorem");
3106 ys
= *sx
++ * (ULLong
)q
+ carry
;
3108 y
= *bx
- (ys
& FFFFFFFF
) - borrow
;
3109 borrow
= y
>> 32 & (ULong
)1;
3110 *bx
++ = y
& FFFFFFFF
;
3114 ys
= (si
& 0xffff) * q
+ carry
;
3115 zs
= (si
>> 16) * q
+ (ys
>> 16);
3117 y
= (*bx
& 0xffff) - (ys
& 0xffff) - borrow
;
3118 borrow
= (y
& 0x10000) >> 16;
3119 z
= (*bx
>> 16) - (zs
& 0xffff) - borrow
;
3120 borrow
= (z
& 0x10000) >> 16;
3123 ys
= *sx
++ * q
+ carry
;
3125 y
= *bx
- (ys
& 0xffff) - borrow
;
3126 borrow
= (y
& 0x10000) >> 16;
3130 } while (sx
<= sxe
);
3133 while (--bxe
> bx
&& !*bxe
)
3138 if (cmp(b
, S
) >= 0) {
3148 y
= *bx
- (ys
& FFFFFFFF
) - borrow
;
3149 borrow
= y
>> 32 & (ULong
)1;
3150 *bx
++ = y
& FFFFFFFF
;
3154 ys
= (si
& 0xffff) + carry
;
3155 zs
= (si
>> 16) + (ys
>> 16);
3157 y
= (*bx
& 0xffff) - (ys
& 0xffff) - borrow
;
3158 borrow
= (y
& 0x10000) >> 16;
3159 z
= (*bx
>> 16) - (zs
& 0xffff) - borrow
;
3160 borrow
= (z
& 0x10000) >> 16;
3165 y
= *bx
- (ys
& 0xffff) - borrow
;
3166 borrow
= (y
& 0x10000) >> 16;
3170 } while (sx
<= sxe
);
3174 while (--bxe
> bx
&& !*bxe
)
3182 #ifndef MULTIPLE_THREADS
3183 static char *dtoa_result
;
3193 sizeof(Bigint
) - sizeof(ULong
) - sizeof(int) + j
<= i
;
3196 r
= (int*)Balloc(k
);
3199 #ifndef MULTIPLE_THREADS
3206 nrv_alloc(char *s
, char **rve
, int n
)
3210 t
= rv
= rv_alloc(n
);
3211 while ((*t
= *s
++) != 0) t
++;
3217 /* freedtoa(s) must be used to free values s returned by dtoa
3218 * when MULTIPLE_THREADS is #defined. It should be used in all cases,
3219 * but for consistency with earlier versions of dtoa, it is optional
3220 * when MULTIPLE_THREADS is not defined.
3226 Bigint
*b
= (Bigint
*)((int *)s
- 1);
3227 b
->maxwds
= 1 << (b
->k
= *(int*)b
);
3229 #ifndef MULTIPLE_THREADS
3230 if (s
== dtoa_result
)
3235 /* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
3237 * Inspired by "How to Print Floating-Point Numbers Accurately" by
3238 * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 112-126].
3241 * 1. Rather than iterating, we use a simple numeric overestimate
3242 * to determine k = floor(log10(d)). We scale relevant
3243 * quantities using O(log2(k)) rather than O(k) multiplications.
3244 * 2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
3245 * try to generate digits strictly left to right. Instead, we
3246 * compute with fewer bits and propagate the carry if necessary
3247 * when rounding the final digit up. This is often faster.
3248 * 3. Under the assumption that input will be rounded nearest,
3249 * mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
3250 * That is, we allow equality in stopping tests when the
3251 * round-nearest rule will give the same floating-point value
3252 * as would satisfaction of the stopping test with strict
3254 * 4. We remove common factors of powers of 2 from relevant
3256 * 5. When converting floating-point integers less than 1e16,
3257 * we use floating-point arithmetic rather than resorting
3258 * to multiple-precision integers.
3259 * 6. When asked to produce fewer than 15 digits, we first try
3260 * to get by with floating-point arithmetic; we resort to
3261 * multiple-precision integer arithmetic only if we cannot
3262 * guarantee that the floating-point calculation has given
3263 * the correctly rounded result. For k requested digits and
3264 * "uniformly" distributed input, the probability is
3265 * something like 10^(k-15) that we must resort to the Long
3270 dtoa(double d
, int mode
, int ndigits
, int *decpt
, int *sign
, char **rve
)
3272 /* Arguments ndigits, decpt, sign are similar to those
3273 of ecvt and fcvt; trailing zeros are suppressed from
3274 the returned string. If not null, *rve is set to point
3275 to the end of the return value. If d is +-Infinity or NaN,
3276 then *decpt is set to 9999.
3279 0 ==> shortest string that yields d when read in
3280 and rounded to nearest.
3281 1 ==> like 0, but with Steele & White stopping rule;
3282 e.g. with IEEE P754 arithmetic , mode 0 gives
3283 1e23 whereas mode 1 gives 9.999999999999999e22.
3284 2 ==> max(1,ndigits) significant digits. This gives a
3285 return value similar to that of ecvt, except
3286 that trailing zeros are suppressed.
3287 3 ==> through ndigits past the decimal point. This
3288 gives a return value similar to that from fcvt,
3289 except that trailing zeros are suppressed, and
3290 ndigits can be negative.
3291 4,5 ==> similar to 2 and 3, respectively, but (in
3292 round-nearest mode) with the tests of mode 0 to
3293 possibly return a shorter string that rounds to d.
3294 With IEEE arithmetic and compilation with
3295 -DHonor_FLT_ROUNDS, modes 4 and 5 behave the same
3296 as modes 2 and 3 when FLT_ROUNDS != 1.
3297 6-9 ==> Debugging modes similar to mode - 4: don't try
3298 fast floating-point estimate (if applicable).
3300 Values of mode other than 0-9 are treated as mode 0.
3302 Sufficient space is allocated to the return value
3303 to hold the suppressed trailing zeros.
3306 int bbits
, b2
, b5
, be
, dig
, i
, ieps
, ilim
, ilim0
, ilim1
,
3307 j
, j1
, k
, k0
, k_check
, leftright
, m2
, m5
, s2
, s5
,
3308 spec_case
, try_quick
;
3310 #ifndef Sudden_Underflow
3314 Bigint
*b
, *b1
, *delta
, *mlo
, *mhi
, *S
;
3317 #ifdef Honor_FLT_ROUNDS
3321 int inexact
, oldinexact
;
3324 #ifndef MULTIPLE_THREADS
3326 freedtoa(dtoa_result
);
3331 if (word0(d
) & Sign_bit
) {
3332 /* set sign for everything, including 0's and NaNs */
3334 word0(d
) &= ~Sign_bit
; /* clear sign bit */
3339 #if defined(IEEE_Arith) + defined(VAX)
3341 if ((word0(d
) & Exp_mask
) == Exp_mask
)
3343 if (word0(d
) == 0x8000)
3346 /* Infinity or NaN */
3349 if (!word1(d
) && !(word0(d
) & 0xfffff))
3350 return nrv_alloc("Infinity", rve
, 8);
3352 return nrv_alloc("NaN", rve
, 3);
3356 dval(d
) += 0; /* normalize */
3360 return nrv_alloc("0", rve
, 1);
3364 try_quick
= oldinexact
= get_inexact();
3367 #ifdef Honor_FLT_ROUNDS
3368 if ((rounding
= Flt_Rounds
) >= 2) {
3370 rounding
= rounding
== 2 ? 0 : 2;
3377 b
= d2b(dval(d
), &be
, &bbits
);
3378 #ifdef Sudden_Underflow
3379 i
= (int)(word0(d
) >> Exp_shift1
& (Exp_mask
>>Exp_shift1
));
3381 if ((i
= (int)(word0(d
) >> Exp_shift1
& (Exp_mask
>>Exp_shift1
))) != 0) {
3384 word0(d2
) &= Frac_mask1
;
3385 word0(d2
) |= Exp_11
;
3387 if (j
= 11 - hi0bits(word0(d2
) & Frac_mask
))
3391 /* log(x) ~=~ log(1.5) + (x-1.5)/1.5
3392 * log10(x) = log(x) / log(10)
3393 * ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
3394 * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2)
3396 * This suggests computing an approximation k to log10(d) by
3398 * k = (i - Bias)*0.301029995663981
3399 * + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
3401 * We want k to be too large rather than too small.
3402 * The error in the first-order Taylor series approximation
3403 * is in our favor, so we just round up the constant enough
3404 * to compensate for any error in the multiplication of
3405 * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
3406 * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
3407 * adding 1e-13 to the constant term more than suffices.
3408 * Hence we adjust the constant term to 0.1760912590558.
3409 * (We could get a more accurate k by invoking log10,
3410 * but this is probably not worthwhile.)
3418 #ifndef Sudden_Underflow
3422 /* d is denormalized */
3424 i
= bbits
+ be
+ (Bias
+ (P
-1) - 1);
3425 x
= i
> 32 ? word0(d
) << (64 - i
) | word1(d
) >> (i
- 32)
3426 : word1(d
) << (32 - i
);
3428 word0(d2
) -= 31*Exp_msk1
; /* adjust exponent */
3429 i
-= (Bias
+ (P
-1) - 1) + 1;
3433 ds
= (dval(d2
)-1.5)*0.289529654602168 + 0.1760912590558 + i
*0.301029995663981;
3435 if (ds
< 0. && ds
!= k
)
3436 k
--; /* want k = floor(ds) */
3438 if (k
>= 0 && k
<= Ten_pmax
) {
3439 if (dval(d
) < tens
[k
])
3462 if (mode
< 0 || mode
> 9)
3466 #ifdef Check_FLT_ROUNDS
3467 try_quick
= Rounding
== 1;
3471 #endif /*SET_INEXACT*/
3491 ilim
= ilim1
= i
= ndigits
;
3497 i
= ndigits
+ k
+ 1;
3503 s
= s0
= rv_alloc(i
);
3505 #ifdef Honor_FLT_ROUNDS
3506 if (mode
> 1 && rounding
!= 1)
3510 if (ilim
>= 0 && ilim
<= Quick_max
&& try_quick
) {
3512 /* Try to get by with floating-point arithmetic. */
3518 ieps
= 2; /* conservative */
3523 /* prevent overflows */
3525 dval(d
) /= bigtens
[n_bigtens
-1];
3528 for (; j
; j
>>= 1, i
++)
3535 else if ((j1
= -k
) != 0) {
3536 dval(d
) *= tens
[j1
& 0xf];
3537 for (j
= j1
>> 4; j
; j
>>= 1, i
++)
3540 dval(d
) *= bigtens
[i
];
3543 if (k_check
&& dval(d
) < 1. && ilim
> 0) {
3551 dval(eps
) = ieps
*dval(d
) + 7.;
3552 word0(eps
) -= (P
-1)*Exp_msk1
;
3556 if (dval(d
) > dval(eps
))
3558 if (dval(d
) < -dval(eps
))
3562 #ifndef No_leftright
3564 /* Use Steele & White method of only
3565 * generating digits needed.
3567 dval(eps
) = 0.5/tens
[ilim
-1] - dval(eps
);
3571 *s
++ = '0' + (int)L
;
3572 if (dval(d
) < dval(eps
))
3574 if (1. - dval(d
) < dval(eps
))
3584 /* Generate ilim digits, then fix them up. */
3585 dval(eps
) *= tens
[ilim
-1];
3586 for (i
= 1;; i
++, dval(d
) *= 10.) {
3587 L
= (Long
)(dval(d
));
3588 if (!(dval(d
) -= L
))
3590 *s
++ = '0' + (int)L
;
3592 if (dval(d
) > 0.5 + dval(eps
))
3594 else if (dval(d
) < 0.5 - dval(eps
)) {
3595 while (*--s
== '0') ;
3602 #ifndef No_leftright
3612 /* Do we have a "small" integer? */
3614 if (be
>= 0 && k
<= Int_max
) {
3617 if (ndigits
< 0 && ilim
<= 0) {
3619 if (ilim
< 0 || dval(d
) <= 5*ds
)
3623 for (i
= 1;; i
++, dval(d
) *= 10.) {
3624 L
= (Long
)(dval(d
) / ds
);
3626 #ifdef Check_FLT_ROUNDS
3627 /* If FLT_ROUNDS == 2, L will usually be high by 1 */
3633 *s
++ = '0' + (int)L
;
3641 #ifdef Honor_FLT_ROUNDS
3645 case 2: goto bump_up
;
3649 if (dval(d
) > ds
|| (dval(d
) == ds
&& (L
& 1))) {
3670 #ifndef Sudden_Underflow
3671 denorm
? be
+ (Bias
+ (P
-1) - 1 + 1) :
3674 1 + 4*P
- 3 - bbits
+ ((bbits
+ be
- 1) & 3);
3682 if (m2
> 0 && s2
> 0) {
3683 i
= m2
< s2
? m2
: s2
;
3691 mhi
= pow5mult(mhi
, m5
);
3696 if ((j
= b5
- m5
) != 0)
3700 b
= pow5mult(b
, b5
);
3704 S
= pow5mult(S
, s5
);
3706 /* Check for special case that d is a normalized power of 2. */
3709 if ((mode
< 2 || leftright
)
3710 #ifdef Honor_FLT_ROUNDS
3714 if (!word1(d
) && !(word0(d
) & Bndry_mask
)
3715 #ifndef Sudden_Underflow
3716 && word0(d
) & (Exp_mask
& ~Exp_msk1
)
3719 /* The special case */
3726 /* Arrange for convenient computation of quotients:
3727 * shift left if necessary so divisor has 4 leading 0 bits.
3729 * Perhaps we should just compute leading 28 bits of S once
3730 * and for all and pass them and a shift to quorem, so it
3731 * can do shifts and ors to compute the numerator for q.
3734 if ((i
= ((s5
? 32 - hi0bits(S
->x
[S
->wds
-1]) : 1) + s2
) & 0x1f) != 0)
3737 if ((i
= ((s5
? 32 - hi0bits(S
->x
[S
->wds
-1]) : 1) + s2
) & 0xf) != 0)
3759 b
= multadd(b
, 10, 0); /* we botched the k estimate */
3761 mhi
= multadd(mhi
, 10, 0);
3765 if (ilim
<= 0 && (mode
== 3 || mode
== 5)) {
3766 if (ilim
< 0 || cmp(b
,S
= multadd(S
,5,0)) <= 0) {
3767 /* no digits, fcvt style */
3779 mhi
= lshift(mhi
, m2
);
3781 /* Compute mlo -- check for special case
3782 * that d is a normalized power of 2.
3787 mhi
= Balloc(mhi
->k
);
3789 mhi
= lshift(mhi
, Log2P
);
3793 dig
= quorem(b
,S
) + '0';
3794 /* Do we yet have the shortest decimal string
3795 * that will round to d?
3798 delta
= diff(S
, mhi
);
3799 j1
= delta
->sign
? 1 : cmp(b
, delta
);
3801 #ifndef ROUND_BIASED
3802 if (j1
== 0 && mode
!= 1 && !(word1(d
) & 1)
3803 #ifdef Honor_FLT_ROUNDS
3812 else if (!b
->x
[0] && b
->wds
<= 1)
3819 if (j
< 0 || (j
== 0 && mode
!= 1
3820 #ifndef ROUND_BIASED
3824 if (!b
->x
[0] && b
->wds
<= 1) {
3830 #ifdef Honor_FLT_ROUNDS
3833 case 0: goto accept_dig
;
3834 case 2: goto keep_dig
;
3836 #endif /*Honor_FLT_ROUNDS*/
3840 if ((j1
> 0 || (j1
== 0 && (dig
& 1))) && dig
++ == '9')
3848 #ifdef Honor_FLT_ROUNDS
3852 if (dig
== '9') { /* possible if i == 1 */
3860 #ifdef Honor_FLT_ROUNDS
3866 b
= multadd(b
, 10, 0);
3868 mlo
= mhi
= multadd(mhi
, 10, 0);
3870 mlo
= multadd(mlo
, 10, 0);
3871 mhi
= multadd(mhi
, 10, 0);
3877 *s
++ = dig
= quorem(b
,S
) + '0';
3878 if (!b
->x
[0] && b
->wds
<= 1) {
3886 b
= multadd(b
, 10, 0);
3889 /* Round off last digit */
3891 #ifdef Honor_FLT_ROUNDS
3893 case 0: goto trimzeros
;
3894 case 2: goto roundoff
;
3899 if (j
> 0 || (j
== 0 && (dig
& 1))) {
3910 while (*--s
== '0') ;
3916 if (mlo
&& mlo
!= mhi
)
3924 word0(d
) = Exp_1
+ (70 << Exp_shift
);
3929 else if (!oldinexact
)
3941 ruby_each_words(const char *str
, void (*func
)(const char*, int, void*), void *arg
)
3947 for (; *str
; str
= end
) {
3948 while (ISSPACE(*str
) || *str
== ',') str
++;
3951 while (*end
&& !ISSPACE(*end
) && *end
!= ',') end
++;
3953 (*func
)(str
, len
, arg
);