PageRenderTime 61ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/util.c

https://github.com/nazy/ruby
C | 4033 lines | 3289 code | 234 blank | 510 comment | 871 complexity | 726a532a856582a5caa8d63d711efa02 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, AGPL-3.0, 0BSD, Unlicense

Large files files are truncated, but you can click here to view the full file

  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. * makefile => makefile.bak
  208. * suffix = ".$$$" (style 1)
  209. * foo.$$$ => foo.~~~ (fallback)
  210. *
  211. * suffix = "~" (style 2)
  212. * foo.c => foo.c~
  213. * foo.c~ => foo.c~~
  214. * foo.c~~ => foo~.c~~
  215. * foo~.c~~ => foo~~.c~~
  216. * foo~~~~~.c~~ => foo~~~~~.$$$ (fallback)
  217. *
  218. * foo.pas => foo~.pas
  219. * makefile => makefile.~
  220. * longname.fil => longname.fi~
  221. * longname.fi~ => longnam~.fi~
  222. * longnam~.fi~ => longnam~.$$$
  223. *
  224. */
  225. static int valid_filename(const char *s);
  226. static const char suffix1[] = ".$$$";
  227. static const char suffix2[] = ".~~~";
  228. #define strEQ(s1,s2) (strcmp(s1,s2) == 0)
  229. extern const char *ruby_find_basename(const char *, long *, long *);
  230. extern const char *ruby_find_extname(const char *, long *);
  231. void
  232. ruby_add_suffix(VALUE str, const char *suffix)
  233. {
  234. long baselen;
  235. long extlen = strlen(suffix);
  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 > (long)(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)) {
  256. extlen = sizeof(suffix1) - 1; /* suffix2 must be same length */
  257. suffix = strEQ(suffix, suffix1) ? suffix2 : suffix1;
  258. }
  259. slen = ext - name;
  260. }
  261. rb_str_resize(str, slen);
  262. rb_str_cat(str, suffix, extlen);
  263. }
  264. else {
  265. char *p = buf, *q;
  266. strncpy(buf, name, slen);
  267. if (ext)
  268. p += (ext - name);
  269. else
  270. p += slen;
  271. p[len] = '\0';
  272. if (suffix[1] == '\0') { /* Style 2 */
  273. q = (char *)ruby_find_basename(buf, &baselen, 0);
  274. if (len <= 3) {
  275. if (len == 0 && baselen >= 8 && p + 3 <= buf + sizeof(buf)) p[len++] = '.'; /* DOSISH */
  276. p[len] = *suffix;
  277. p[++len] = '\0';
  278. }
  279. else if (q && baselen < 8) {
  280. q += baselen;
  281. *q++ = *suffix;
  282. if (ext) {
  283. strncpy(q, ext, ext - name);
  284. q[ext - name + 1] = '\0';
  285. }
  286. else
  287. *q = '\0';
  288. }
  289. else if (len == 4 && p[3] != *suffix)
  290. p[3] = *suffix;
  291. else if (baselen == 8 && q[7] != *suffix)
  292. q[7] = *suffix;
  293. else
  294. goto fallback;
  295. }
  296. else { /* Style 3: Panic */
  297. fallback:
  298. (void)memcpy(p, !ext || strEQ(ext, suffix1) ? suffix2 : suffix1, 5);
  299. }
  300. rb_str_resize(str, strlen(buf));
  301. memcpy(RSTRING_PTR(str), buf, RSTRING_LEN(str));
  302. }
  303. }
  304. static int
  305. valid_filename(const char *s)
  306. {
  307. int fd;
  308. /*
  309. // It doesn't exist, so see if we can open it.
  310. */
  311. if ((fd = open(s, O_CREAT|O_EXCL, 0666)) >= 0) {
  312. close(fd);
  313. unlink(s); /* don't leave it laying around */
  314. return 1;
  315. }
  316. else if (errno == EEXIST) {
  317. /* if the file exists, then it's a valid filename! */
  318. return 1;
  319. }
  320. return 0;
  321. }
  322. #endif
  323. /* mm.c */
  324. #define A ((int*)a)
  325. #define B ((int*)b)
  326. #define C ((int*)c)
  327. #define D ((int*)d)
  328. #define mmprepare(base, size) do {\
  329. if (((long)base & (0x3)) == 0)\
  330. if (size >= 16) mmkind = 1;\
  331. else mmkind = 0;\
  332. else mmkind = -1;\
  333. high = (size & (~0xf));\
  334. low = (size & 0x0c);\
  335. } while (0)\
  336. #define mmarg mmkind, size, high, low
  337. static void mmswap_(register char *a, register char *b, int mmkind, size_t size, size_t high, size_t low)
  338. {
  339. register int s;
  340. if (a == b) return;
  341. if (mmkind >= 0) {
  342. if (mmkind > 0) {
  343. register char *t = a + high;
  344. do {
  345. s = A[0]; A[0] = B[0]; B[0] = s;
  346. s = A[1]; A[1] = B[1]; B[1] = s;
  347. s = A[2]; A[2] = B[2]; B[2] = s;
  348. s = A[3]; A[3] = B[3]; B[3] = s; a += 16; b += 16;
  349. } while (a < t);
  350. }
  351. if (low != 0) { s = A[0]; A[0] = B[0]; B[0] = s;
  352. if (low >= 8) { s = A[1]; A[1] = B[1]; B[1] = s;
  353. if (low == 12) {s = A[2]; A[2] = B[2]; B[2] = s;}}}
  354. }
  355. else {
  356. register char *t = a + size;
  357. do {s = *a; *a++ = *b; *b++ = s;} while (a < t);
  358. }
  359. }
  360. #define mmswap(a,b) mmswap_((a),(b),mmarg)
  361. static void mmrot3_(register char *a, register char *b, register char *c, int mmkind, size_t size, size_t high, size_t low)
  362. {
  363. register int s;
  364. if (mmkind >= 0) {
  365. if (mmkind > 0) {
  366. register char *t = a + high;
  367. do {
  368. s = A[0]; A[0] = B[0]; B[0] = C[0]; C[0] = s;
  369. s = A[1]; A[1] = B[1]; B[1] = C[1]; C[1] = s;
  370. s = A[2]; A[2] = B[2]; B[2] = C[2]; C[2] = s;
  371. s = A[3]; A[3] = B[3]; B[3] = C[3]; C[3] = s; a += 16; b += 16; c += 16;
  372. } while (a < t);
  373. }
  374. if (low != 0) { s = A[0]; A[0] = B[0]; B[0] = C[0]; C[0] = s;
  375. if (low >= 8) { s = A[1]; A[1] = B[1]; B[1] = C[1]; C[1] = s;
  376. if (low == 12) {s = A[2]; A[2] = B[2]; B[2] = C[2]; C[2] = s;}}}
  377. }
  378. else {
  379. register char *t = a + size;
  380. do {s = *a; *a++ = *b; *b++ = *c; *c++ = s;} while (a < t);
  381. }
  382. }
  383. #define mmrot3(a,b,c) mmrot3_((a),(b),(c),mmarg)
  384. /* qs6.c */
  385. /*****************************************************/
  386. /* */
  387. /* qs6 (Quick sort function) */
  388. /* */
  389. /* by Tomoyuki Kawamura 1995.4.21 */
  390. /* kawamura@tokuyama.ac.jp */
  391. /*****************************************************/
  392. typedef struct { char *LL, *RR; } stack_node; /* Stack structure for L,l,R,r */
  393. #define PUSH(ll,rr) do { top->LL = (ll); top->RR = (rr); ++top; } while (0) /* Push L,l,R,r */
  394. #define POP(ll,rr) do { --top; ll = top->LL; rr = top->RR; } while (0) /* Pop L,l,R,r */
  395. #define med3(a,b,c) ((*cmp)(a,b,d)<0 ? \
  396. ((*cmp)(b,c,d)<0 ? b : ((*cmp)(a,c,d)<0 ? c : a)) : \
  397. ((*cmp)(b,c,d)>0 ? b : ((*cmp)(a,c,d)<0 ? a : c)))
  398. void
  399. ruby_qsort(void* base, const size_t nel, const size_t size,
  400. int (*cmp)(const void*, const void*, void*), void *d)
  401. {
  402. register char *l, *r, *m; /* l,r:left,right group m:median point */
  403. register int t, eq_l, eq_r; /* eq_l: all items in left group are equal to S */
  404. char *L = base; /* left end of current region */
  405. char *R = (char*)base + size*(nel-1); /* right end of current region */
  406. size_t chklim = 63; /* threshold of ordering element check */
  407. stack_node stack[32], *top = stack; /* 32 is enough for 32bit CPU */
  408. int mmkind;
  409. size_t high, low, n;
  410. if (nel <= 1) return; /* need not to sort */
  411. mmprepare(base, size);
  412. goto start;
  413. nxt:
  414. if (stack == top) return; /* return if stack is empty */
  415. POP(L,R);
  416. for (;;) {
  417. start:
  418. if (L + size == R) { /* 2 elements */
  419. if ((*cmp)(L,R,d) > 0) mmswap(L,R); goto nxt;
  420. }
  421. l = L; r = R;
  422. n = (r - l + size) / size; /* number of elements */
  423. m = l + size * (n >> 1); /* calculate median value */
  424. if (n >= 60) {
  425. register char *m1;
  426. register char *m3;
  427. if (n >= 200) {
  428. n = size*(n>>3); /* number of bytes in splitting 8 */
  429. {
  430. register char *p1 = l + n;
  431. register char *p2 = p1 + n;
  432. register char *p3 = p2 + n;
  433. m1 = med3(p1, p2, p3);
  434. p1 = m + n;
  435. p2 = p1 + n;
  436. p3 = p2 + n;
  437. m3 = med3(p1, p2, p3);
  438. }
  439. }
  440. else {
  441. n = size*(n>>2); /* number of bytes in splitting 4 */
  442. m1 = l + n;
  443. m3 = m + n;
  444. }
  445. m = med3(m1, m, m3);
  446. }
  447. if ((t = (*cmp)(l,m,d)) < 0) { /*3-5-?*/
  448. if ((t = (*cmp)(m,r,d)) < 0) { /*3-5-7*/
  449. if (chklim && nel >= chklim) { /* check if already ascending order */
  450. char *p;
  451. chklim = 0;
  452. for (p=l; p<r; p+=size) if ((*cmp)(p,p+size,d) > 0) goto fail;
  453. goto nxt;
  454. }
  455. fail: goto loopA; /*3-5-7*/
  456. }
  457. if (t > 0) {
  458. if ((*cmp)(l,r,d) <= 0) {mmswap(m,r); goto loopA;} /*3-5-4*/
  459. mmrot3(r,m,l); goto loopA; /*3-5-2*/
  460. }
  461. goto loopB; /*3-5-5*/
  462. }
  463. if (t > 0) { /*7-5-?*/
  464. if ((t = (*cmp)(m,r,d)) > 0) { /*7-5-3*/
  465. if (chklim && nel >= chklim) { /* check if already ascending order */
  466. char *p;
  467. chklim = 0;
  468. for (p=l; p<r; p+=size) if ((*cmp)(p,p+size,d) < 0) goto fail2;
  469. while (l<r) {mmswap(l,r); l+=size; r-=size;} /* reverse region */
  470. goto nxt;
  471. }
  472. fail2: mmswap(l,r); goto loopA; /*7-5-3*/
  473. }
  474. if (t < 0) {
  475. if ((*cmp)(l,r,d) <= 0) {mmswap(l,m); goto loopB;} /*7-5-8*/
  476. mmrot3(l,m,r); goto loopA; /*7-5-6*/
  477. }
  478. mmswap(l,r); goto loopA; /*7-5-5*/
  479. }
  480. if ((t = (*cmp)(m,r,d)) < 0) {goto loopA;} /*5-5-7*/
  481. if (t > 0) {mmswap(l,r); goto loopB;} /*5-5-3*/
  482. /* determining splitting type in case 5-5-5 */ /*5-5-5*/
  483. for (;;) {
  484. if ((l += size) == r) goto nxt; /*5-5-5*/
  485. if (l == m) continue;
  486. if ((t = (*cmp)(l,m,d)) > 0) {mmswap(l,r); l = L; goto loopA;}/*575-5*/
  487. if (t < 0) {mmswap(L,l); l = L; goto loopB;} /*535-5*/
  488. }
  489. loopA: eq_l = 1; eq_r = 1; /* splitting type A */ /* left <= median < right */
  490. for (;;) {
  491. for (;;) {
  492. if ((l += size) == r)
  493. {l -= size; if (l != m) mmswap(m,l); l -= size; goto fin;}
  494. if (l == m) continue;
  495. if ((t = (*cmp)(l,m,d)) > 0) {eq_r = 0; break;}
  496. if (t < 0) eq_l = 0;
  497. }
  498. for (;;) {
  499. if (l == (r -= size))
  500. {l -= size; if (l != m) mmswap(m,l); l -= size; goto fin;}
  501. if (r == m) {m = l; break;}
  502. if ((t = (*cmp)(r,m,d)) < 0) {eq_l = 0; break;}
  503. if (t == 0) break;
  504. }
  505. mmswap(l,r); /* swap left and right */
  506. }
  507. loopB: eq_l = 1; eq_r = 1; /* splitting type B */ /* left < median <= right */
  508. for (;;) {
  509. for (;;) {
  510. if (l == (r -= size))
  511. {r += size; if (r != m) mmswap(r,m); r += size; goto fin;}
  512. if (r == m) continue;
  513. if ((t = (*cmp)(r,m,d)) < 0) {eq_l = 0; break;}
  514. if (t > 0) eq_r = 0;
  515. }
  516. for (;;) {
  517. if ((l += size) == r)
  518. {r += size; if (r != m) mmswap(r,m); r += size; goto fin;}
  519. if (l == m) {m = r; break;}
  520. if ((t = (*cmp)(l,m,d)) > 0) {eq_r = 0; break;}
  521. if (t == 0) break;
  522. }
  523. mmswap(l,r); /* swap left and right */
  524. }
  525. fin:
  526. if (eq_l == 0) /* need to sort left side */
  527. if (eq_r == 0) /* need to sort right side */
  528. if (l-L < R-r) {PUSH(r,R); R = l;} /* sort left side first */
  529. else {PUSH(L,l); L = r;} /* sort right side first */
  530. else R = l; /* need to sort left side only */
  531. else if (eq_r == 0) L = r; /* need to sort right side only */
  532. else goto nxt; /* need not to sort both sides */
  533. }
  534. }
  535. char *
  536. ruby_strdup(const char *str)
  537. {
  538. char *tmp;
  539. size_t len = strlen(str) + 1;
  540. tmp = xmalloc(len);
  541. memcpy(tmp, str, len);
  542. return tmp;
  543. }
  544. char *
  545. ruby_getcwd(void)
  546. {
  547. #ifdef HAVE_GETCWD
  548. int size = 200;
  549. char *buf = xmalloc(size);
  550. while (!getcwd(buf, size)) {
  551. if (errno != ERANGE) {
  552. xfree(buf);
  553. rb_sys_fail("getcwd");
  554. }
  555. size *= 2;
  556. buf = xrealloc(buf, size);
  557. }
  558. #else
  559. # ifndef PATH_MAX
  560. # define PATH_MAX 8192
  561. # endif
  562. char *buf = xmalloc(PATH_MAX+1);
  563. if (!getwd(buf)) {
  564. xfree(buf);
  565. rb_sys_fail("getwd");
  566. }
  567. #endif
  568. return buf;
  569. }
  570. /****************************************************************
  571. *
  572. * The author of this software is David M. Gay.
  573. *
  574. * Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
  575. *
  576. * Permission to use, copy, modify, and distribute this software for any
  577. * purpose without fee is hereby granted, provided that this entire notice
  578. * is included in all copies of any software which is or includes a copy
  579. * or modification of this software and in all copies of the supporting
  580. * documentation for such software.
  581. *
  582. * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
  583. * WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
  584. * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
  585. * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
  586. *
  587. ***************************************************************/
  588. /* Please send bug reports to David M. Gay (dmg at acm dot org,
  589. * with " at " changed at "@" and " dot " changed to "."). */
  590. /* On a machine with IEEE extended-precision registers, it is
  591. * necessary to specify double-precision (53-bit) rounding precision
  592. * before invoking strtod or dtoa. If the machine uses (the equivalent
  593. * of) Intel 80x87 arithmetic, the call
  594. * _control87(PC_53, MCW_PC);
  595. * does this with many compilers. Whether this or another call is
  596. * appropriate depends on the compiler; for this to work, it may be
  597. * necessary to #include "float.h" or another system-dependent header
  598. * file.
  599. */
  600. /* strtod for IEEE-, VAX-, and IBM-arithmetic machines.
  601. *
  602. * This strtod returns a nearest machine number to the input decimal
  603. * string (or sets errno to ERANGE). With IEEE arithmetic, ties are
  604. * broken by the IEEE round-even rule. Otherwise ties are broken by
  605. * biased rounding (add half and chop).
  606. *
  607. * Inspired loosely by William D. Clinger's paper "How to Read Floating
  608. * Point Numbers Accurately" [Proc. ACM SIGPLAN '90, pp. 92-101].
  609. *
  610. * Modifications:
  611. *
  612. * 1. We only require IEEE, IBM, or VAX double-precision
  613. * arithmetic (not IEEE double-extended).
  614. * 2. We get by with floating-point arithmetic in a case that
  615. * Clinger missed -- when we're computing d * 10^n
  616. * for a small integer d and the integer n is not too
  617. * much larger than 22 (the maximum integer k for which
  618. * we can represent 10^k exactly), we may be able to
  619. * compute (d*10^k) * 10^(e-k) with just one roundoff.
  620. * 3. Rather than a bit-at-a-time adjustment of the binary
  621. * result in the hard case, we use floating-point
  622. * arithmetic to determine the adjustment to within
  623. * one bit; only in really hard cases do we need to
  624. * compute a second residual.
  625. * 4. Because of 3., we don't need a large table of powers of 10
  626. * for ten-to-e (just some small tables, e.g. of 10^k
  627. * for 0 <= k <= 22).
  628. */
  629. /*
  630. * #define IEEE_LITTLE_ENDIAN for IEEE-arithmetic machines where the least
  631. * significant byte has the lowest address.
  632. * #define IEEE_BIG_ENDIAN for IEEE-arithmetic machines where the most
  633. * significant byte has the lowest address.
  634. * #define Long int on machines with 32-bit ints and 64-bit longs.
  635. * #define IBM for IBM mainframe-style floating-point arithmetic.
  636. * #define VAX for VAX-style floating-point arithmetic (D_floating).
  637. * #define No_leftright to omit left-right logic in fast floating-point
  638. * computation of dtoa.
  639. * #define Honor_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3
  640. * and strtod and dtoa should round accordingly.
  641. * #define Check_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3
  642. * and Honor_FLT_ROUNDS is not #defined.
  643. * #define RND_PRODQUOT to use rnd_prod and rnd_quot (assembly routines
  644. * that use extended-precision instructions to compute rounded
  645. * products and quotients) with IBM.
  646. * #define ROUND_BIASED for IEEE-format with biased rounding.
  647. * #define Inaccurate_Divide for IEEE-format with correctly rounded
  648. * products but inaccurate quotients, e.g., for Intel i860.
  649. * #define NO_LONG_LONG on machines that do not have a "long long"
  650. * integer type (of >= 64 bits). On such machines, you can
  651. * #define Just_16 to store 16 bits per 32-bit Long when doing
  652. * high-precision integer arithmetic. Whether this speeds things
  653. * up or slows things down depends on the machine and the number
  654. * being converted. If long long is available and the name is
  655. * something other than "long long", #define Llong to be the name,
  656. * and if "unsigned Llong" does not work as an unsigned version of
  657. * Llong, #define #ULLong to be the corresponding unsigned type.
  658. * #define KR_headers for old-style C function headers.
  659. * #define Bad_float_h if your system lacks a float.h or if it does not
  660. * define some or all of DBL_DIG, DBL_MAX_10_EXP, DBL_MAX_EXP,
  661. * FLT_RADIX, FLT_ROUNDS, and DBL_MAX.
  662. * #define MALLOC your_malloc, where your_malloc(n) acts like malloc(n)
  663. * if memory is available and otherwise does something you deem
  664. * appropriate. If MALLOC is undefined, malloc will be invoked
  665. * directly -- and assumed always to succeed.
  666. * #define Omit_Private_Memory to omit logic (added Jan. 1998) for making
  667. * memory allocations from a private pool of memory when possible.
  668. * When used, the private pool is PRIVATE_MEM bytes long: 2304 bytes,
  669. * unless #defined to be a different length. This default length
  670. * suffices to get rid of MALLOC calls except for unusual cases,
  671. * such as decimal-to-binary conversion of a very long string of
  672. * digits. The longest string dtoa can return is about 751 bytes
  673. * long. For conversions by strtod of strings of 800 digits and
  674. * all dtoa conversions in single-threaded executions with 8-byte
  675. * pointers, PRIVATE_MEM >= 7400 appears to suffice; with 4-byte
  676. * pointers, PRIVATE_MEM >= 7112 appears adequate.
  677. * #define INFNAN_CHECK on IEEE systems to cause strtod to check for
  678. * Infinity and NaN (case insensitively). On some systems (e.g.,
  679. * some HP systems), it may be necessary to #define NAN_WORD0
  680. * appropriately -- to the most significant word of a quiet NaN.
  681. * (On HP Series 700/800 machines, -DNAN_WORD0=0x7ff40000 works.)
  682. * When INFNAN_CHECK is #defined and No_Hex_NaN is not #defined,
  683. * strtod also accepts (case insensitively) strings of the form
  684. * NaN(x), where x is a string of hexadecimal digits and spaces;
  685. * if there is only one string of hexadecimal digits, it is taken
  686. * for the 52 fraction bits of the resulting NaN; if there are two
  687. * or more strings of hex digits, the first is for the high 20 bits,
  688. * the second and subsequent for the low 32 bits, with intervening
  689. * white space ignored; but if this results in none of the 52
  690. * fraction bits being on (an IEEE Infinity symbol), then NAN_WORD0
  691. * and NAN_WORD1 are used instead.
  692. * #define MULTIPLE_THREADS if the system offers preemptively scheduled
  693. * multiple threads. In this case, you must provide (or suitably
  694. * #define) two locks, acquired by ACQUIRE_DTOA_LOCK(n) and freed
  695. * by FREE_DTOA_LOCK(n) for n = 0 or 1. (The second lock, accessed
  696. * in pow5mult, ensures lazy evaluation of only one copy of high
  697. * powers of 5; omitting this lock would introduce a small
  698. * probability of wasting memory, but would otherwise be harmless.)
  699. * You must also invoke freedtoa(s) to free the value s returned by
  700. * dtoa. You may do so whether or not MULTIPLE_THREADS is #defined.
  701. * #define NO_IEEE_Scale to disable new (Feb. 1997) logic in strtod that
  702. * avoids underflows on inputs whose result does not underflow.
  703. * If you #define NO_IEEE_Scale on a machine that uses IEEE-format
  704. * floating-point numbers and flushes underflows to zero rather
  705. * than implementing gradual underflow, then you must also #define
  706. * Sudden_Underflow.
  707. * #define YES_ALIAS to permit aliasing certain double values with
  708. * arrays of ULongs. This leads to slightly better code with
  709. * some compilers and was always used prior to 19990916, but it
  710. * is not strictly legal and can cause trouble with aggressively
  711. * optimizing compilers (e.g., gcc 2.95.1 under -O2).
  712. * #define USE_LOCALE to use the current locale's decimal_point value.
  713. * #define SET_INEXACT if IEEE arithmetic is being used and extra
  714. * computation should be done to set the inexact flag when the
  715. * result is inexact and avoid setting inexact when the result
  716. * is exact. In this case, dtoa.c must be compiled in
  717. * an environment, perhaps provided by #include "dtoa.c" in a
  718. * suitable wrapper, that defines two functions,
  719. * int get_inexact(void);
  720. * void clear_inexact(void);
  721. * such that get_inexact() returns a nonzero value if the
  722. * inexact bit is already set, and clear_inexact() sets the
  723. * inexact bit to 0. When SET_INEXACT is #defined, strtod
  724. * also does extra computations to set the underflow and overflow
  725. * flags when appropriate (i.e., when the result is tiny and
  726. * inexact or when it is a numeric value rounded to +-infinity).
  727. * #define NO_ERRNO if strtod should not assign errno = ERANGE when
  728. * the result overflows to +-Infinity or underflows to 0.
  729. */
  730. #ifdef WORDS_BIGENDIAN
  731. #define IEEE_BIG_ENDIAN
  732. #else
  733. #define IEEE_LITTLE_ENDIAN
  734. #endif
  735. #ifdef __vax__
  736. #define VAX
  737. #undef IEEE_BIG_ENDIAN
  738. #undef IEEE_LITTLE_ENDIAN
  739. #endif
  740. #if defined(__arm__) && !defined(__VFP_FP__)
  741. #define IEEE_BIG_ENDIAN
  742. #undef IEEE_LITTLE_ENDIAN
  743. #endif
  744. #undef Long
  745. #undef ULong
  746. #if SIZEOF_INT == 4
  747. #define Long int
  748. #define ULong unsigned int
  749. #elif SIZEOF_LONG == 4
  750. #define Long long int
  751. #define ULong unsigned long int
  752. #endif
  753. #if HAVE_LONG_LONG
  754. #define Llong LONG_LONG
  755. #endif
  756. #ifdef DEBUG
  757. #include "stdio.h"
  758. #define Bug(x) {fprintf(stderr, "%s\n", x); exit(1);}
  759. #endif
  760. #include "stdlib.h"
  761. #include "string.h"
  762. #ifdef USE_LOCALE
  763. #include "locale.h"
  764. #endif
  765. #ifdef MALLOC
  766. extern void *MALLOC(size_t);
  767. #else
  768. #define MALLOC malloc
  769. #endif
  770. #ifndef Omit_Private_Memory
  771. #ifndef PRIVATE_MEM
  772. #define PRIVATE_MEM 2304
  773. #endif
  774. #define PRIVATE_mem ((PRIVATE_MEM+sizeof(double)-1)/sizeof(double))
  775. static double private_mem[PRIVATE_mem], *pmem_next = private_mem;
  776. #endif
  777. #undef IEEE_Arith
  778. #undef Avoid_Underflow
  779. #ifdef IEEE_BIG_ENDIAN
  780. #define IEEE_Arith
  781. #endif
  782. #ifdef IEEE_LITTLE_ENDIAN
  783. #define IEEE_Arith
  784. #endif
  785. #ifdef Bad_float_h
  786. #ifdef IEEE_Arith
  787. #define DBL_DIG 15
  788. #define DBL_MAX_10_EXP 308
  789. #define DBL_MAX_EXP 1024
  790. #define FLT_RADIX 2
  791. #endif /*IEEE_Arith*/
  792. #ifdef IBM
  793. #define DBL_DIG 16
  794. #define DBL_MAX_10_EXP 75
  795. #define DBL_MAX_EXP 63
  796. #define FLT_RADIX 16
  797. #define DBL_MAX 7.2370055773322621e+75
  798. #endif
  799. #ifdef VAX
  800. #define DBL_DIG 16
  801. #define DBL_MAX_10_EXP 38
  802. #define DBL_MAX_EXP 127
  803. #define FLT_RADIX 2
  804. #define DBL_MAX 1.7014118346046923e+38
  805. #endif
  806. #ifndef LONG_MAX
  807. #define LONG_MAX 2147483647
  808. #endif
  809. #else /* ifndef Bad_float_h */
  810. #include "float.h"
  811. #endif /* Bad_float_h */
  812. #ifndef __MATH_H__
  813. #include "math.h"
  814. #endif
  815. #ifdef __cplusplus
  816. extern "C" {
  817. #if 0
  818. }
  819. #endif
  820. #endif
  821. #if defined(IEEE_LITTLE_ENDIAN) + defined(IEEE_BIG_ENDIAN) + defined(VAX) + defined(IBM) != 1
  822. Exactly one of IEEE_LITTLE_ENDIAN, IEEE_BIG_ENDIAN, VAX, or IBM should be defined.
  823. #endif
  824. typedef union { double d; ULong L[2]; } U;
  825. #ifdef YES_ALIAS
  826. typedef double double_u;
  827. # define dval(x) x
  828. # ifdef IEEE_LITTLE_ENDIAN
  829. # define word0(x) (((ULong *)&x)[1])
  830. # define word1(x) (((ULong *)&x)[0])
  831. # else
  832. # define word0(x) (((ULong *)&x)[0])
  833. # define word1(x) (((ULong *)&x)[1])
  834. # endif
  835. #else
  836. typedef U double_u;
  837. # ifdef IEEE_LITTLE_ENDIAN
  838. # define word0(x) (x.L[1])
  839. # define word1(x) (x.L[0])
  840. # else
  841. # define word0(x) (x.L[0])
  842. # define word1(x) (x.L[1])
  843. # endif
  844. # define dval(x) (x.d)
  845. #endif
  846. /* The following definition of Storeinc is appropriate for MIPS processors.
  847. * An alternative that might be better on some machines is
  848. * #define Storeinc(a,b,c) (*a++ = b << 16 | c & 0xffff)
  849. */
  850. #if defined(IEEE_LITTLE_ENDIAN) + defined(VAX) + defined(__arm__)
  851. #define Storeinc(a,b,c) (((unsigned short *)a)[1] = (unsigned short)b, \
  852. ((unsigned short *)a)[0] = (unsigned short)c, a++)
  853. #else
  854. #define Storeinc(a,b,c) (((unsigned short *)a)[0] = (unsigned short)b, \
  855. ((unsigned short *)a)[1] = (unsigned short)c, a++)
  856. #endif
  857. /* #define P DBL_MANT_DIG */
  858. /* Ten_pmax = floor(P*log(2)/log(5)) */
  859. /* Bletch = (highest power of 2 < DBL_MAX_10_EXP) / 16 */
  860. /* Quick_max = floor((P-1)*log(FLT_RADIX)/log(10) - 1) */
  861. /* Int_max = floor(P*log(FLT_RADIX)/log(10) - 1) */
  862. #ifdef IEEE_Arith
  863. #define Exp_shift 20
  864. #define Exp_shift1 20
  865. #define Exp_msk1 0x100000
  866. #define Exp_msk11 0x100000
  867. #define Exp_mask 0x7ff00000
  868. #define P 53
  869. #define Bias 1023
  870. #define Emin (-1022)
  871. #define Exp_1 0x3ff00000
  872. #define Exp_11 0x3ff00000
  873. #define Ebits 11
  874. #define Frac_mask 0xfffff
  875. #define Frac_mask1 0xfffff
  876. #define Ten_pmax 22
  877. #define Bletch 0x10
  878. #define Bndry_mask 0xfffff
  879. #define Bndry_mask1 0xfffff
  880. #define LSB 1
  881. #define Sign_bit 0x80000000
  882. #define Log2P 1
  883. #define Tiny0 0
  884. #define Tiny1 1
  885. #define Quick_max 14
  886. #define Int_max 14
  887. #ifndef NO_IEEE_Scale
  888. #define Avoid_Underflow
  889. #ifdef Flush_Denorm /* debugging option */
  890. #undef Sudden_Underflow
  891. #endif
  892. #endif
  893. #ifndef Flt_Rounds
  894. #ifdef FLT_ROUNDS
  895. #define Flt_Rounds FLT_ROUNDS
  896. #else
  897. #define Flt_Rounds 1
  898. #endif
  899. #endif /*Flt_Rounds*/
  900. #ifdef Honor_FLT_ROUNDS
  901. #define Rounding rounding
  902. #undef Check_FLT_ROUNDS
  903. #define Check_FLT_ROUNDS
  904. #else
  905. #define Rounding Flt_Rounds
  906. #endif
  907. #else /* ifndef IEEE_Arith */
  908. #undef Check_FLT_ROUNDS
  909. #undef Honor_FLT_ROUNDS
  910. #undef SET_INEXACT
  911. #undef Sudden_Underflow
  912. #define Sudden_Underflow
  913. #ifdef IBM
  914. #undef Flt_Rounds
  915. #define Flt_Rounds 0
  916. #define Exp_shift 24
  917. #define Exp_shift1 24
  918. #define Exp_msk1 0x1000000
  919. #define Exp_msk11 0x1000000
  920. #define Exp_mask 0x7f000000
  921. #define P 14
  922. #define Bias 65
  923. #define Exp_1 0x41000000
  924. #define Exp_11 0x41000000
  925. #define Ebits 8 /* exponent has 7 bits, but 8 is the right value in b2d */
  926. #define Frac_mask 0xffffff
  927. #define Frac_mask1 0xffffff
  928. #define Bletch 4
  929. #define Ten_pmax 22
  930. #define Bndry_mask 0xefffff
  931. #define Bndry_mask1 0xffffff
  932. #define LSB 1
  933. #define Sign_bit 0x80000000
  934. #define Log2P 4
  935. #define Tiny0 0x100000
  936. #define Tiny1 0
  937. #define Quick_max 14
  938. #define Int_max 15
  939. #else /* VAX */
  940. #undef Flt_Rounds
  941. #define Flt_Rounds 1
  942. #define Exp_shift 23
  943. #define Exp_shift1 7
  944. #define Exp_msk1 0x80
  945. #define Exp_msk11 0x800000
  946. #define Exp_mask 0x7f80
  947. #define P 56
  948. #define Bias 129
  949. #define Exp_1 0x40800000
  950. #define Exp_11 0x4080
  951. #define Ebits 8
  952. #define Frac_mask 0x7fffff
  953. #define Frac_mask1 0xffff007f
  954. #define Ten_pmax 24
  955. #define Bletch 2
  956. #define Bndry_mask 0xffff007f
  957. #define Bndry_mask1 0xffff007f
  958. #define LSB 0x10000
  959. #define Sign_bit 0x8000
  960. #define Log2P 1
  961. #define Tiny0 0x80
  962. #define Tiny1 0
  963. #define Quick_max 15
  964. #define Int_max 15
  965. #endif /* IBM, VAX */
  966. #endif /* IEEE_Arith */
  967. #ifndef IEEE_Arith
  968. #define ROUND_BIASED
  969. #endif
  970. #ifdef RND_PRODQUOT
  971. #define rounded_product(a,b) a = rnd_prod(a, b)
  972. #define rounded_quotient(a,b) a = rnd_quot(a, b)
  973. extern double rnd_prod(double, double), rnd_quot(double, double);
  974. #else
  975. #define rounded_product(a,b) a *= b
  976. #define rounded_quotient(a,b) a /= b
  977. #endif
  978. #define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
  979. #define Big1 0xffffffff
  980. #ifndef Pack_32
  981. #define Pack_32
  982. #endif
  983. #define FFFFFFFF 0xffffffffUL
  984. #ifdef NO_LONG_LONG
  985. #undef ULLong
  986. #ifdef Just_16
  987. #undef Pack_32
  988. /* When Pack_32 is not defined, we store 16 bits per 32-bit Long.
  989. * This makes some inner loops simpler and sometimes saves work
  990. * during multiplications, but it often seems to make things slightly
  991. * slower. Hence the default is now to store 32 bits per Long.
  992. */
  993. #endif
  994. #else /* long long available */
  995. #ifndef Llong
  996. #define Llong long long
  997. #endif
  998. #ifndef ULLong
  999. #define ULLong unsigned Llong
  1000. #endif
  1001. #endif /* NO_LONG_LONG */
  1002. #define MULTIPLE_THREADS 1
  1003. #ifndef MULTIPLE_THREADS
  1004. #define ACQUIRE_DTOA_LOCK(n) /*nothing*/
  1005. #define FREE_DTOA_LOCK(n) /*nothing*/
  1006. #else
  1007. #define ACQUIRE_DTOA_LOCK(n) /*unused right now*/
  1008. #define FREE_DTOA_LOCK(n) /*unused right now*/
  1009. #endif
  1010. #define Kmax 15
  1011. struct Bigint {
  1012. struct Bigint *next;
  1013. int k, maxwds, sign, wds;
  1014. ULong x[1];
  1015. };
  1016. typedef struct Bigint Bigint;
  1017. static Bigint *freelist[Kmax+1];
  1018. static Bigint *
  1019. Balloc(int k)
  1020. {
  1021. int x;
  1022. Bigint *rv;
  1023. #ifndef Omit_Private_Memory
  1024. size_t len;
  1025. #endif
  1026. ACQUIRE_DTOA_LOCK(0);
  1027. if ((rv = freelist[k]) != 0) {
  1028. freelist[k] = rv->next;
  1029. }
  1030. else {
  1031. x = 1 << k;
  1032. #ifdef Omit_Private_Memory
  1033. rv = (Bigint *)MALLOC(sizeof(Bigint) + (x-1)*sizeof(ULong));
  1034. #else
  1035. len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)
  1036. /sizeof(double);
  1037. if (pmem_next - private_mem + len <= PRIVATE_mem) {
  1038. rv = (Bigint*)pmem_next;
  1039. pmem_next += len;
  1040. }
  1041. else
  1042. rv = (Bigint*)MALLOC(len*sizeof(double));
  1043. #endif
  1044. rv->k = k;
  1045. rv->maxwds = x;
  1046. }
  1047. FREE_DTOA_LOCK(0);
  1048. rv->sign = rv->wds = 0;
  1049. return rv;
  1050. }
  1051. static void
  1052. Bfree(Bigint *v)
  1053. {
  1054. if (v) {
  1055. ACQUIRE_DTOA_LOCK(0);
  1056. v->next = freelist[v->k];
  1057. freelist[v->k] = v;
  1058. FREE_DTOA_LOCK(0);
  1059. }
  1060. }
  1061. #define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign, \
  1062. y->wds*sizeof(Long) + 2*sizeof(int))
  1063. static Bigint *
  1064. multadd(Bigint *b, int m, int a) /* multiply by m and add a */
  1065. {
  1066. int i, wds;
  1067. ULong *x;
  1068. #ifdef ULLong
  1069. ULLong carry, y;
  1070. #else
  1071. ULong carry, y;
  1072. #ifdef Pack_32
  1073. ULong xi, z;
  1074. #endif
  1075. #endif
  1076. Bigint *b1;
  1077. wds = b->wds;
  1078. x = b->x;
  1079. i = 0;
  1080. carry = a;
  1081. do {
  1082. #ifdef ULLong
  1083. y = *x * (ULLong)m + carry;
  1084. carry = y >> 32;
  1085. *x++ = (ULong)(y & FFFFFFFF);
  1086. #else
  1087. #ifdef Pack_32
  1088. xi = *x;
  1089. y = (xi & 0xffff) * m + carry;
  1090. z = (xi >> 16) * m + (y >> 16);
  1091. carry = z >> 16;
  1092. *x++ = (z << 16) + (y & 0xffff);
  1093. #else
  1094. y = *x * m + carry;
  1095. carry = y >> 16;
  1096. *x++ = y & 0xffff;
  1097. #endif
  1098. #endif
  1099. } while (++i < wds);
  1100. if (carry) {
  1101. if (wds >= b->maxwds) {
  1102. b1 = Balloc(b->k+1);
  1103. Bcopy(b1, b);
  1104. Bfree(b);
  1105. b = b1;
  1106. }
  1107. b->x[wds++] = (ULong)carry;
  1108. b->wds = wds;
  1109. }
  1110. return b;
  1111. }
  1112. static Bigint *
  1113. s2b(const char *s, int nd0, int nd, ULong y9)
  1114. {
  1115. Bigint *b;
  1116. int i, k;
  1117. Long x, y;
  1118. x = (nd + 8) / 9;
  1119. for (k = 0, y = 1; x > y; y <<= 1, k++) ;
  1120. #ifdef Pack_32
  1121. b = Balloc(k);
  1122. b->x[0] = y9;
  1123. b->wds = 1;
  1124. #else
  1125. b = Balloc(k+1);
  1126. b->x[0] = y9 & 0xffff;
  1127. b->wds = (b->x[1] = y9 >> 16) ? 2 : 1;
  1128. #endif
  1129. i = 9;
  1130. if (9 < nd0) {
  1131. s += 9;
  1132. do {
  1133. b = multadd(b, 10, *s++ - '0');
  1134. } while (++i < nd0);
  1135. s++;
  1136. }
  1137. else
  1138. s += 10;
  1139. for (; i < nd; i++)
  1140. b = multadd(b, 10, *s++ - '0');
  1141. return b;
  1142. }
  1143. static int
  1144. hi0bits(register ULong x)
  1145. {
  1146. register int k = 0;
  1147. if (!(x & 0xffff0000)) {
  1148. k = 16;
  1149. x <<= 16;
  1150. }
  1151. if (!(x & 0xff000000)) {
  1152. k += 8;
  1153. x <<= 8;
  1154. }
  1155. if (!(x & 0xf0000000)) {
  1156. k += 4;
  1157. x <<= 4;
  1158. }
  1159. if (!(x & 0xc0000000)) {
  1160. k += 2;
  1161. x <<= 2;
  1162. }
  1163. if (!(x & 0x80000000)) {
  1164. k++;
  1165. if (!(x & 0x40000000))
  1166. return 32;
  1167. }
  1168. return k;
  1169. }
  1170. static int
  1171. lo0bits(ULong *y)
  1172. {
  1173. register int k;
  1174. register ULong x = *y;
  1175. if (x & 7) {
  1176. if (x & 1)
  1177. return 0;
  1178. if (x & 2) {
  1179. *y = x >> 1;
  1180. return 1;
  1181. }
  1182. *y = x >> 2;
  1183. return 2;
  1184. }
  1185. k = 0;
  1186. if (!(x & 0xffff)) {
  1187. k = 16;
  1188. x >>= 16;
  1189. }
  1190. if (!(x & 0xff)) {
  1191. k += 8;
  1192. x >>= 8;
  1193. }
  1194. if (!(x & 0xf)) {
  1195. k += 4;
  1196. x >>= 4;
  1197. }
  1198. if (!(x & 0x3)) {
  1199. k += 2;
  1200. x >>= 2;
  1201. }
  1202. if (!(x & 1)) {
  1203. k++;
  1204. x >>= 1;
  1205. if (!x)
  1206. return 32;
  1207. }
  1208. *y = x;
  1209. return k;
  1210. }
  1211. static Bigint *
  1212. i2b(int i)
  1213. {
  1214. Bigint *b;
  1215. b = Balloc(1);
  1216. b->x[0] = i;
  1217. b->wds = 1;
  1218. return b;
  1219. }
  1220. static Bigint *
  1221. mult(Bigint *a, Bigint *b)
  1222. {
  1223. Bigint *c;
  1224. int k, wa, wb, wc;
  1225. ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
  1226. ULong y;
  1227. #ifdef ULLong
  1228. ULLong carry, z;
  1229. #else
  1230. ULong carry, z;
  1231. #ifdef Pack_32
  1232. ULong z2;
  1233. #endif
  1234. #endif
  1235. if (a->wds < b->wds) {
  1236. c = a;
  1237. a = b;
  1238. b = c;
  1239. }
  1240. k = a->k;
  1241. wa = a->wds;
  1242. wb = b->wds;
  1243. wc = wa + wb;
  1244. if (wc > a->maxwds)
  1245. k++;
  1246. c = Balloc(k);
  1247. for (x = c->x, xa = x + wc; x < xa; x++)
  1248. *x = 0;
  1249. xa = a->x;
  1250. xae = xa + wa;
  1251. xb = b->x;
  1252. xbe = xb + wb;
  1253. xc0 = c->x;
  1254. #ifdef ULLong
  1255. for (; xb < xbe; xc0++) {
  1256. if ((y = *xb++) != 0) {
  1257. x = xa;
  1258. xc = xc0;
  1259. carry = 0;
  1260. do {
  1261. z = *x++ * (ULLong)y + *xc + carry;
  1262. carry = z >> 32;
  1263. *xc++ = (ULong)(z & FFFFFFFF);
  1264. } while (x < xae);
  1265. *xc = (ULong)carry;
  1266. }
  1267. }
  1268. #else
  1269. #ifdef Pack_32
  1270. for (; xb < xbe; xb++, xc0++) {
  1271. if (y = *xb & 0xffff) {
  1272. x = xa;
  1273. xc = xc0;
  1274. carry = 0;
  1275. do {
  1276. z = (*x & 0xffff) * y + (*xc & 0xffff) + carry;
  1277. carry = z >> 16;
  1278. z2 = (*x++ >> 16) * y + (*xc >> 16) + carry;
  1279. carry = z2 >> 16;
  1280. Storeinc(xc, z2, z);
  1281. } while (x < xae);
  1282. *xc = (ULong)carry;
  1283. }
  1284. if (y = *xb >> 16) {
  1285. x = xa;
  1286. xc = xc0;
  1287. carry = 0;
  1288. z2 = *xc;
  1289. do {
  1290. z = (*x & 0xffff) * y + (*xc >> 16) + carry;
  1291. carry = z >> 16;
  1292. Storeinc(xc, z, z2);
  1293. z2 = (*x++ >> 16) * y + (*xc & 0xffff) + carry;
  1294. carry = z2 >> 16;
  1295. } while (x < xae);
  1296. *xc = z2;
  1297. }
  1298. }
  1299. #else
  1300. for (; xb < xbe; xc0++) {
  1301. if (y = *xb++) {
  1302. x = xa;
  1303. xc = xc0;
  1304. carry = 0;
  1305. do {
  1306. z = *x++ * y + *xc + carry;
  1307. carry = z >> 16;
  1308. *xc++ = z & 0xffff;
  1309. } while (x < xae);
  1310. *xc = (ULong)carry;
  1311. }
  1312. }
  1313. #endif
  1314. #endif
  1315. for (xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ;
  1316. c->wds = wc;
  1317. return c;
  1318. }
  1319. static Bigint *p5s;
  1320. static Bigint *
  1321. pow5mult(Bigint *b, int k)
  1322. {
  1323. Bigint *b1, *p5, *p51;
  1324. int i;
  1325. static int p05[3] = { 5, 25, 125 };
  1326. if ((i = k & 3) != 0)
  1327. b = multadd(b, p05[i-1], 0);
  1328. if (!(k >>= 2))
  1329. return b;
  1330. if (!(p5 = p5s)) {
  1331. /* first time */
  1332. #ifdef MULTIPLE_THREADS
  1333. ACQUIRE_DTOA_LOCK(1);
  1334. if (!(p5 = p5s)) {
  1335. p5 = p5s = i2b(625);
  1336. p5->next = 0;
  1337. }
  1338. FREE_DTOA_LOCK(1);
  1339. #else
  1340. p5 = p5s = i2b(625);
  1341. p5->next = 0;
  1342. #endif
  1343. }
  1344. for (;;) {
  1345. if (k & 1) {
  1346. b1 = mult(b, p5);
  1347. Bfree(b);
  1348. b = b1;
  1349. }
  1350. if (!(k >>= 1))
  1351. break;
  1352. if (!(p51 = p5->next)) {
  1353. #ifdef MULTIPLE_THREADS
  1354. ACQUIRE_DTOA_LOCK(1);
  1355. if (!(p51 = p5->next)) {
  1356. p51 = p5->next = mult(p5,p5);
  1357. p51->next = 0;
  1358. }
  1359. FREE_DTOA_LOCK(1);
  1360. #else
  1361. p51 = p5->next = mult(p5,p5);
  1362. p51->next = 0;
  1363. #endif
  1364. }
  1365. p5 = p51;
  1366. }
  1367. return b;
  1368. }
  1369. static Bigint *
  1370. lshift(Bigint *b, int k)
  1371. {
  1372. int i, k1, n, n1;
  1373. Bigint *b1;
  1374. ULong *x, *x1, *xe, z;
  1375. #ifdef Pack_32
  1376. n = k >> 5;
  1377. #else
  1378. n = k >> 4;
  1379. #endif
  1380. k1 = b->k;
  1381. n1 = n + b->wds + 1;
  1382. for (i = b->maxwds; n1 > i; i <<= 1)
  1383. k1++;
  1384. b1 = Balloc(k1);
  1385. x1 = b1->x;
  1386. for (i = 0; i < n; i++)
  1387. *x1++ = 0;
  1388. x = b->x;
  1389. xe = x + b->wds;
  1390. #ifdef Pack_32
  1391. if (k &= 0x1f) {
  1392. k1 = 32 - k;
  1393. z = 0;
  1394. do {
  1395. *x1++ = *x << k | z;
  1396. z = *x++ >> k1;
  1397. } while (x < xe);
  1398. if ((*x1 = z) != 0)
  1399. ++n1;
  1400. }
  1401. #else
  1402. if (k &= 0xf) {
  1403. k1 = 16 - k;
  1404. z = 0;
  1405. do {
  1406. *x1++ = *x << k & 0xffff | z;
  1407. z = *x++ >> k1;
  1408. } while (x < xe);
  1409. if (*x1 = z)
  1410. ++n1;
  1411. }
  1412. #endif
  1413. else
  1414. do {
  1415. *x1++ = *x++;
  1416. } while (x < xe);
  1417. b1->wds = n1 - 1;
  1418. Bfree(b);
  1419. return b1;
  1420. }
  1421. static int
  1422. cmp(Bigint *a, Bigint *b)
  1423. {
  1424. ULong *xa, *xa0, *xb, *xb0;
  1425. int i, j;
  1426. i = a->wds;
  1427. j = b->wds;
  1428. #ifdef DEBUG
  1429. if (i > 1 && !a->x[i-1])
  1430. Bug("cmp called with a->x[a->wds-1] == 0");
  1431. if (j > 1 && !b->x[j-1])
  1432. Bug("cmp called with b->x[b->wds-1] == 0");
  1433. #endif
  1434. if (i -= j)
  1435. return i;
  1436. xa0 = a->x;
  1437. xa = xa0 + j;
  1438. xb0 = b->x;
  1439. xb = xb0 + j;
  1440. for (;;) {
  1441. if (*--xa != *--xb)
  1442. return *xa < *xb ? -1 : 1;
  1443. if (xa <= xa0)
  1444. break;
  1445. }
  1446. return 0;
  1447. }
  1448. static Bigint *
  1449. diff(Bigint *a, Bigint *b)
  1450. {
  1451. Bigint *c;
  1452. int i, wa, wb;
  1453. ULong *xa, *xae, *xb, *xbe, *xc;
  1454. #ifdef ULLong
  1455. ULLong borrow, y;
  1456. #else
  1457. ULong borrow, y;
  1458. #ifdef Pack_32
  1459. ULong z;
  1460. #endif
  1461. #endif
  1462. i = cmp(a,b);
  1463. if (!i) {
  1464. c = Balloc(0);
  1465. c->wds = 1;
  1466. c->x[0] = 0;
  1467. return c;
  1468. }
  1469. if (i < 0) {
  1470. c = a;
  1471. a = b;
  1472. b = c;
  1473. i = 1;
  1474. }
  1475. else
  1476. i = 0;
  1477. c = Balloc(a->k);
  1478. c->sign = i;
  1479. wa = a->wds;
  1480. xa = a->x;
  1481. xae = xa + wa;
  1482. wb = b->wds;
  1483. xb = b->x;
  1484. xbe = xb + wb;
  1485. xc = c->x;
  1486. borrow = 0;
  1487. #ifdef ULLong
  1488. do {
  1489. y = (ULLong)*xa++ - *xb++ - borrow;
  1490. borrow = y >> 32 & (ULong)1;
  1491. *xc++ = (ULong)(y & FFFFFFFF);
  1492. } while (xb < xbe);
  1493. while (xa < xae) {
  1494. y = *xa++ - borrow;
  1495. borrow = y >> 32 & (ULong)1;
  1496. *xc++ = (ULong)(y & FFFFFFFF);
  1497. }
  1498. #else
  1499. #ifdef Pack_32
  1500. do {
  1501. y = (*xa & 0xffff) - (*xb & 0xffff) - borrow;
  1502. borrow = (y & 0x10000) >> 16;
  1503. z = (*xa++ >> 16) - (*xb++ >> 16) - borrow;
  1504. borrow = (z & 0x10000) >> 16;
  1505. Storeinc(xc, z, y);
  1506. } while (xb < xbe);
  1507. while (xa < xae) {
  1508. y = (*xa & 0xffff) - borrow;
  1509. borrow = (y & 0x10000) >> 16;
  1510. z = (*xa++ >> 16) - borrow;
  1511. borrow = (z & 0x10000) >> 16;
  1512. Storeinc(xc, z, y);
  1513. }
  1514. #else
  1515. do {
  1516. y = *xa++ - *xb++ - borrow;
  1517. borrow = (y & 0x10000) >> 16;
  1518. *xc++ = y & 0xffff;
  1519. } while (xb < xbe);
  1520. while (xa < xae) {
  1521. y = *xa++ - borrow;
  1522. borrow = (y & 0x10000) >> 16;
  1523. *xc++ = y & 0xffff;
  1524. }
  1525. #endif
  1526. #endif
  1527. while (!*--xc)
  1528. wa--;
  1529. c->wds = wa;
  1530. return c;
  1531. }
  1532. static double
  1533. ulp(double x_)
  1534. {
  1535. register Long L;
  1536. double_u x, a;
  1537. dval(x) = x_;
  1538. L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1;
  1539. #ifndef Avoid_Underflow
  1540. #ifndef Sudden_Underflow
  1541. if (L > 0) {
  1542. #endif
  1543. #endif
  1544. #ifdef IBM
  1545. L |= Exp_msk1 >> 4;
  1546. #endif
  1547. word0(a) = L;
  1548. word1(a) = 0;
  1549. #ifndef Avoid_Underflow
  1550. #ifndef Sudden_Underflow
  1551. }
  1552. else {
  1553. L = -L >> Exp_shift;
  1554. if (L < Exp_shift) {
  1555. word0(a) = 0x80000 >> L;
  1556. word1(a) = 0;
  1557. }
  1558. else {
  1559. word0(a) = 0;
  1560. L -= Exp_shift;
  1561. word1(a) = L >= 31 ? 1 : 1 << 31 - L;
  1562. }
  1563. }
  1564. #endif
  1565. #endif
  1566. return dval(a);
  1567. }
  1568. static double
  1569. b2d(Bigint *a, int *e)
  1570. {
  1571. ULong *xa, *xa0, w, y, z;
  1572. int k;
  1573. double_u d;
  1574. #ifdef VAX
  1575. ULong d0, d1;
  1576. #else
  1577. #define d0 word0(d)
  1578. #define d1 word1(d)
  1579. #endif
  1580. xa0 = a->x;
  1581. xa = xa0 + a->wds;
  1582. y = *--xa;
  1583. #ifdef DEBUG
  1584. if (!y) Bug("zero y in b2d");
  1585. #endif
  1586. k = hi0bits(y);
  1587. *e = 32 - k;
  1588. #ifdef Pack_32
  1589. if (k < Ebits) {
  1590. d0 = Exp_1 | y >> (Ebits - k);
  1591. w = xa > xa0 ? *--xa : 0;
  1592. d1 = y << ((32-Ebits) + k) | w >> (Ebits - k);
  1593. goto ret_d;
  1594. }
  1595. z = xa > xa0 ? *--xa : 0;
  1596. if (k -= Ebits) {
  1597. d0 = Exp_1 | y << k | z >> (32 - k);
  1598. y = xa > xa0 ? *--xa : 0;
  1599. d1 = z << k | y >> (32 - k);
  1600. }
  1601. else {
  1602. d0 = Exp_1 | y;
  1603. d1 = z;
  1604. }
  1605. #else
  1606. if (k < Ebits + 16) {
  1607. z = xa > xa0 ? *--xa : 0;
  1608. d0 = Exp_1 | y << k - Ebits | z >> Ebits + 16 - k;
  1609. w = xa > xa0 ? *--xa : 0;
  1610. y = xa > xa0 ? *--xa : 0;
  1611. d1 = z << k + 16 - Ebits | w << k - Ebits | y >> 16 + Ebits - k;
  1612. goto ret_d;
  1613. }
  1614. z = xa > xa0 ? *--xa : 0;
  1615. w = xa > xa0 ? *--xa : 0;
  1616. k -= Ebits + 16;
  1617. d0 = Exp_1 | y << k + 16 | z << k | w >> 16 - k;
  1618. y = xa > xa0 ? *--xa : 0;
  1619. d1 = w << k + 16 | y << k;
  1620. #endif
  1621. ret_d:
  1622. #ifdef VAX
  1623. word0(d) = d0 >> 16 | d0 << 16;
  1624. word1(d) = d1 >> 16 | d1 << 16;
  1625. #else
  1626. #undef d0
  1627. #undef d1
  1628. #endif
  1629. return dval(d);
  1630. }
  1631. static Bigint *
  1632. d2b(double d_, int *e, int *bits)
  1633. {
  1634. double_u d;
  1635. Bigint *b;
  1636. int de, k;
  1637. ULong *x, y, z;
  1638. #ifndef Sudden_Underflow
  1639. int i;
  1640. #endif
  1641. #ifdef VAX
  1642. ULong d0, d1;
  1643. #endif
  1644. dval(d) = d_;
  1645. #ifdef VAX
  1646. d0 = word0(d) >> 16 | word0(d) << 16;
  1647. d1 = word1(d) >> 16 | word1(d) << 16;
  1648. #else
  1649. #define d0 word0(d)
  1650. #define d1 word1(d)
  1651. #endif
  1652. #ifdef Pack_32
  1653. b = Balloc(1);
  1654. #else
  1655. b = Balloc(2);
  1656. #endif
  1657. x = b->x;
  1658. z = d0 & Frac_mask;
  1659. d0 &= 0x7fffffff; /* clear sign bit, which we ignore */
  1660. #ifdef Sudden_Underflow
  1661. de = (int)(d0 >> Exp_shift);
  1662. #ifndef IBM
  1663. z |= Exp_msk11;
  1664. #endif
  1665. #else
  1666. if ((de = (int)(d0 >> Exp_shift)) != 0)
  1667. z |= Exp_msk1;
  1668. #endif
  1669. #ifdef Pack_32
  1670. if ((y = d1) != 0) {
  1671. if ((k = lo0bits(&y)) != 0) {
  1672. x[0] = y | z << (32 - k);
  1673. z >>= k;
  1674. }
  1675. else
  1676. x[0] = y;
  1677. #ifndef Sudden_Underflow
  1678. i =
  1679. #endif
  1680. b->wds = (x[1] = z) ? 2 : 1;
  1681. }
  1682. else {
  1683. #ifdef DEBUG
  1684. if (!z)
  1685. Bug("Zero passed to d2b");
  1686. #endif
  1687. k = lo0bits(&z);
  1688. x[0] = z;
  1689. #ifndef Sudden_Underflow
  1690. i =
  1691. #endif
  1692. b->wds = 1;
  1693. k += 32;
  1694. }
  1695. #else
  1696. if (y = d1) {
  1697. if (k = lo0bits(&y))
  1698. if (k >= 16) {
  1699. x[0] = y | z << 32 - k & 0xffff;
  1700. x[1] = z >> k - 16 & 0xffff;
  1701. x[2] = z >> k;
  1702. i = 2;
  1703. }
  1704. else {
  1705. x[0] = y & 0xffff;
  1706. x[1] = y >> 16 | z << 16 - k & 0xffff;
  1707. x[2] = z >> k & 0xffff;
  1708. x[3] = z >> k+16;
  1709. i = 3;
  1710. }
  1711. else {
  1712. x[0] = y & 0xffff;
  1713. x[1] = y >> 16;
  1714. x[2] = z & 0xffff;
  1715. x[3] = z >> 16;
  1716. i = 3;
  1717. }
  1718. }
  1719. else {
  1720. #ifdef DEBUG
  1721. if (!z)
  1722. Bug("Zero passed to d2b");
  1723. #endif
  1724. k = lo0bits(&z);
  1725. if (k >= 16) {
  1726. x[0] = z;
  1727. i = 0;
  1728. }
  1729. else {
  1730. x[0] = z & 0xffff;
  1731. x[1] = z >> 16;
  1732. i = 1;
  1733. }
  1734. k += 32;
  1735. }
  1736. while (!x[i])
  1737. --i;
  1738. b->wds = i + 1;
  1739. #endif
  1740. #ifndef Sudden_Underflow
  1741. if (de) {
  1742. #endif
  1743. #ifdef IBM
  1744. *e = (de - Bias - (P-1) << 2) + k;
  1745. *bits = 4*P + 8 - k - hi0bits(word0(d) & Frac_mask);
  1746. #else
  1747. *e = de - Bias - (P-1) + k;
  1748. *bits = P - k;
  1749. #endif
  1750. #ifndef Sudden_Underflow
  1751. }
  1752. else {
  1753. *e = de - Bias - (P-1) + 1 + k;
  1754. #ifdef Pack_32
  1755. *bits = 32*i - hi0bits(x[i-1]);
  1756. #else
  1757. *bits = (i+2)*16 - hi0bits(x[i]);
  1758. #endif
  1759. }
  1760. #endif
  1761. return b;
  1762. }
  1763. #undef d0
  1764. #undef d1
  1765. static double
  1766. ratio(Bigint *a, Bigint *b)
  1767. {
  1768. double_u da, db;
  1769. int k, ka, kb;
  1770. dval(da) = b2d(a, &ka);
  1771. dval(db) = b2d(b, &kb);
  1772. #ifdef Pack_32
  1773. k = ka - kb + 32*(a->wds - b->wds);
  1774. #else
  1775. k = ka - kb + 16*(a->wds - b->wds);
  1776. #endif
  1777. #ifdef IBM
  1778. if (k > 0) {
  1779. word0(da) += (k >> 2)*Exp_msk1;
  1780. if (k &= 3)
  1781. dval(da) *= 1 << k;
  1782. }
  1783. else {
  1784. k = -k;
  1785. word0(db) += (k >> 2)*Exp_msk1;
  1786. if (k &= 3)
  1787. dval(db) *= 1 << k;
  1788. }
  1789. #else
  1790. if (k > 0)
  1791. word0(da) += k*Exp_msk1;
  1792. else {
  1793. k = -k;
  1794. word0(db) += k*Exp_msk1;
  1795. }
  1796. #endif
  1797. return dval(da) / dval(db);
  1798. }
  1799. static const double
  1800. tens[] = {
  1801. 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  1802. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
  1803. 1e20, 1e21, 1e22
  1804. #ifdef VAX
  1805. , 1e23, 1e24
  1806. #endif
  1807. };
  1808. static const double
  1809. #ifdef IEEE_Arith
  1810. bigtens[] = {

Large files files are truncated, but you can click here to view the full file