PageRenderTime 37ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/util.c

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