Debian Codegraph @

rpython/translator/c/src/dtoa.c

raw symbols SCIP
1 /****************************************************************
2 *
3 * The author of this software is David M. Gay.
4 *
5 * Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
6 *
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose without fee is hereby granted, provided that this entire notice
9 * is included in all copies of any software which is or includes a copy
10 * or modification of this software and in all copies of the supporting
11 * documentation for such software.
12 *
13 * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
14 * WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
15 * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
16 * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
17 *
18 ***************************************************************/
19
20 /****************************************************************
21 * This is dtoa.c by David M. Gay, downloaded from
22 * http://www.netlib.org/fp/dtoa.c on April 15, 2009 and modified for
23 * inclusion into the Python core by Mark E. T. Dickinson and Eric V. Smith.
24 *
25 * Please remember to check http://www.netlib.org/fp regularly (and especially
26 * before any Python release) for bugfixes and updates.
27 *
28 * The major modifications from Gay's original code are as follows:
29 *
30 * 0. The original code has been specialized to Python's needs by removing
31 * many of the #ifdef'd sections. In particular, code to support VAX and
32 * IBM floating-point formats, hex NaNs, hex floats, locale-aware
33 * treatment of the decimal point, and setting of the inexact flag have
34 * been removed.
35 *
36 * 1. We use PyMem_Malloc and PyMem_Free in place of malloc and free.
37 *
38 * 2. The public functions strtod, dtoa and freedtoa all now have
39 * a _Py_dg_ prefix.
40 *
41 * 3. Instead of assuming that PyMem_Malloc always succeeds, we thread
42 * PyMem_Malloc failures through the code. The functions
43 *
44 * Balloc, multadd, s2b, i2b, mult, pow5mult, lshift, diff, d2b
45 *
46 * of return type *Bigint all return NULL to indicate a malloc failure.
47 * Similarly, rv_alloc and nrv_alloc (return type char *) return NULL on
48 * failure. bigcomp now has return type int (it used to be void) and
49 * returns -1 on failure and 0 otherwise. __Py_dg_dtoa returns NULL
50 * on failure. __Py_dg_strtod indicates failure due to malloc failure
51 * by returning -1.0, setting errno=ENOMEM and *se to s00.
52 *
53 * 4. The static variable dtoa_result has been removed. Callers of
54 * __Py_dg_dtoa are expected to call __Py_dg_freedtoa to free
55 * the memory allocated by __Py_dg_dtoa.
56 *
57 * 5. The code has been reformatted to better fit with Python's
58 * C style guide (PEP 7).
59 *
60 * 6. A bug in the memory allocation has been fixed: to avoid FREEing memory
61 * that hasn't been MALLOC'ed, private_mem should only be used when k <=
62 * Kmax.
63 *
64 * 7. __Py_dg_strtod has been modified so that it doesn't accept strings with
65 * leading whitespace.
66 *
67 * 8. A corner case where __Py_dg_dtoa didn't strip trailing zeros has been
68 * fixed. (bugs.python.org/issue40780)
69 *
70 ***************************************************************/
71
72 /* Please send bug reports for the original dtoa.c code to David M. Gay (dmg
73 * at acm dot org, with " at " changed at "@" and " dot " changed to ".").
74 * Please report bugs for this modified version using the Python issue tracker
75 * (http://bugs.python.org). */
76
77 /* On a machine with IEEE extended-precision registers, it is
78 * necessary to specify double-precision (53-bit) rounding precision
79 * before invoking strtod or dtoa. If the machine uses (the equivalent
80 * of) Intel 80x87 arithmetic, the call
81 * _control87(PC_53, MCW_PC);
82 * does this with many compilers. Whether this or another call is
83 * appropriate depends on the compiler; for this to work, it may be
84 * necessary to #include "float.h" or another system-dependent header
85 * file.
86 */
87
88 /* strtod for IEEE-, VAX-, and IBM-arithmetic machines.
89 *
90 * This strtod returns a nearest machine number to the input decimal
91 * string (or sets errno to ERANGE). With IEEE arithmetic, ties are
92 * broken by the IEEE round-even rule. Otherwise ties are broken by
93 * biased rounding (add half and chop).
94 *
95 * Inspired loosely by William D. Clinger's paper "How to Read Floating
96 * Point Numbers Accurately" [Proc. ACM SIGPLAN '90, pp. 92-101].
97 *
98 * Modifications:
99 *
100 * 1. We only require IEEE, IBM, or VAX double-precision
101 * arithmetic (not IEEE double-extended).
102 * 2. We get by with floating-point arithmetic in a case that
103 * Clinger missed -- when we're computing d * 10^n
104 * for a small integer d and the integer n is not too
105 * much larger than 22 (the maximum integer k for which
106 * we can represent 10^k exactly), we may be able to
107 * compute (d*10^k) * 10^(e-k) with just one roundoff.
108 * 3. Rather than a bit-at-a-time adjustment of the binary
109 * result in the hard case, we use floating-point
110 * arithmetic to determine the adjustment to within
111 * one bit; only in really hard cases do we need to
112 * compute a second residual.
113 * 4. Because of 3., we don't need a large table of powers of 10
114 * for ten-to-e (just some small tables, e.g. of 10^k
115 * for 0 <= k <= 22).
116 */
117
118 /* Linking of Python's #defines to Gay's #defines starts here. */
119
120 /* Begin PYPY hacks */
121 /* #include "Python.h" */
122 #define HAVE_UINT32_T
123 #define HAVE_INT32_T
124 #define HAVE_UINT64_T
125 #ifndef PY_UINT32_T
126 #define PY_UINT32_T unsigned int
127 #endif
128 #ifndef PY_INT32_T
129 #define PY_INT32_T int
130 #endif
131 #ifndef PY_UINT64_T
132 #define PY_UINT64_T unsigned long long
133 #endif
134 #include <limits.h>
135 #include <stdlib.h>
136 #include <errno.h>
137 #include <assert.h>
138 #include <stdio.h>
139 #include <string.h>
140 #include "src/asm.h"
141 /* End PYPY hacks */
142
143
144 /* if PY_NO_SHORT_FLOAT_REPR is defined, then don't even try to compile
145 the following code */
146 #ifndef PY_NO_SHORT_FLOAT_REPR
147
148 #include <float.h>
149
150 #define MALLOC malloc
151 #define FREE free
152
153 /* This code should also work for ARM mixed-endian format on little-endian
154 machines, where doubles have byte order 45670123 (in increasing address
155 order, 0 being the least significant byte). */
156 #ifdef DOUBLE_IS_LITTLE_ENDIAN_IEEE754
157 # define IEEE_8087
158 #endif
159 #if defined(DOUBLE_IS_BIG_ENDIAN_IEEE754) || \
160 defined(DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754)
161 # define IEEE_MC68k
162 #endif
163 #if defined(IEEE_8087) + defined(IEEE_MC68k) != 1
164 #error "Exactly one of IEEE_8087 or IEEE_MC68k should be defined."
165 #endif
166
167 /* The code below assumes that the endianness of integers matches the
168 endianness of the two 32-bit words of a double. Check this. */
169 #if defined(WORDS_BIGENDIAN) && (defined(DOUBLE_IS_LITTLE_ENDIAN_IEEE754) || \
170 defined(DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754))
171 #error "doubles and ints have incompatible endianness"
172 #endif
173
174 #if !defined(WORDS_BIGENDIAN) && defined(DOUBLE_IS_BIG_ENDIAN_IEEE754)
175 #error "doubles and ints have incompatible endianness"
176 #endif
177
178
179 #if defined(HAVE_UINT32_T) && defined(HAVE_INT32_T)
180 typedef PY_UINT32_T ULong;
181 typedef PY_INT32_T Long;
182 #else
183 #error "Failed to find an exact-width 32-bit integer type"
184 #endif
185
186 #if defined(HAVE_UINT64_T)
187 #define ULLong PY_UINT64_T
188 #else
189 #undef ULLong
190 #endif
191
192 #undef DEBUG
193 #ifdef Py_DEBUG
194 #define DEBUG
195 #endif
196
197 /* End Python #define linking */
198
199 #ifdef DEBUG
200 #define Bug(x) {fprintf(stderr, "%s\n", x); exit(1);}
201 #endif
202
203 #ifndef PRIVATE_MEM
204 #define PRIVATE_MEM 2304
205 #endif
206 #define PRIVATE_mem ((PRIVATE_MEM+sizeof(double)-1)/sizeof(double))
207 static double private_mem[PRIVATE_mem], *pmem_next = private_mem;
208
209 #ifdef __cplusplus
210 extern "C" {
211 #endif
212
213 typedef union { double d; ULong L[2]; } U;
214
215 #ifdef IEEE_8087
216 #define word0(x) (x)->L[1]
217 #define word1(x) (x)->L[0]
218 #else
219 #define word0(x) (x)->L[0]
220 #define word1(x) (x)->L[1]
221 #endif
222 #define dval(x) (x)->d
223
224 #ifndef STRTOD_DIGLIM
225 #define STRTOD_DIGLIM 40
226 #endif
227
228 /* maximum permitted exponent value for strtod; exponents larger than
229 MAX_ABS_EXP in absolute value get truncated to +-MAX_ABS_EXP. MAX_ABS_EXP
230 should fit into an int. */
231 #ifndef MAX_ABS_EXP
232 #define MAX_ABS_EXP 1100000000U
233 #endif
234 /* Bound on length of pieces of input strings in _Py_dg_strtod; specifically,
235 this is used to bound the total number of digits ignoring leading zeros and
236 the number of digits that follow the decimal point. Ideally, MAX_DIGITS
237 should satisfy MAX_DIGITS + 400 < MAX_ABS_EXP; that ensures that the
238 exponent clipping in _Py_dg_strtod can't affect the value of the output. */
239 #ifndef MAX_DIGITS
240 #define MAX_DIGITS 1000000000U
241 #endif
242
243 /* Guard against trying to use the above values on unusual platforms with ints
244 * of width less than 32 bits. */
245 #if MAX_ABS_EXP > INT_MAX
246 #error "MAX_ABS_EXP should fit in an int"
247 #endif
248 #if MAX_DIGITS > INT_MAX
249 #error "MAX_DIGITS should fit in an int"
250 #endif
251
252 /* The following definition of Storeinc is appropriate for MIPS processors.
253 * An alternative that might be better on some machines is
254 * #define Storeinc(a,b,c) (*a++ = b << 16 | c & 0xffff)
255 */
256 #if defined(IEEE_8087)
257 #define Storeinc(a,b,c) (((unsigned short *)a)[1] = (unsigned short)b, \
258 ((unsigned short *)a)[0] = (unsigned short)c, a++)
259 #else
260 #define Storeinc(a,b,c) (((unsigned short *)a)[0] = (unsigned short)b, \
261 ((unsigned short *)a)[1] = (unsigned short)c, a++)
262 #endif
263
264 /* #define P DBL_MANT_DIG */
265 /* Ten_pmax = floor(P*log(2)/log(5)) */
266 /* Bletch = (highest power of 2 < DBL_MAX_10_EXP) / 16 */
267 /* Quick_max = floor((P-1)*log(FLT_RADIX)/log(10) - 1) */
268 /* Int_max = floor(P*log(FLT_RADIX)/log(10) - 1) */
269
270 #define Exp_shift 20
271 #define Exp_shift1 20
272 #define Exp_msk1 0x100000
273 #define Exp_msk11 0x100000
274 #define Exp_mask 0x7ff00000
275 #define P 53
276 #define Nbits 53
277 #define Bias 1023
278 #define Emax 1023
279 #define Emin (-1022)
280 #define Etiny (-1074) /* smallest denormal is 2**Etiny */
281 #define Exp_1 0x3ff00000
282 #define Exp_11 0x3ff00000
283 #define Ebits 11
284 #define Frac_mask 0xfffff
285 #define Frac_mask1 0xfffff
286 #define Ten_pmax 22
287 #define Bletch 0x10
288 #define Bndry_mask 0xfffff
289 #define Bndry_mask1 0xfffff
290 #define Sign_bit 0x80000000
291 #define Log2P 1
292 #define Tiny0 0
293 #define Tiny1 1
294 #define Quick_max 14
295 #define Int_max 14
296
297 #ifndef Flt_Rounds
298 #ifdef FLT_ROUNDS
299 #define Flt_Rounds FLT_ROUNDS
300 #else
301 #define Flt_Rounds 1
302 #endif
303 #endif /*Flt_Rounds*/
304
305 #define Rounding Flt_Rounds
306
307 #define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
308 #define Big1 0xffffffff
309
310 /* struct BCinfo is used to pass information from __Py_dg_strtod to bigcomp */
311
312 typedef struct BCinfo BCinfo;
313 struct
314 BCinfo {
315 int e0, nd, nd0, scale;
316 };
317
318 #define FFFFFFFF 0xffffffffUL
319
320 #define Kmax 7
321
322 /* struct Bigint is used to represent arbitrary-precision integers. These
323 integers are stored in sign-magnitude format, with the magnitude stored as
324 an array of base 2**32 digits. Bigints are always normalized: if x is a
325 Bigint then x->wds >= 1, and either x->wds == 1 or x[wds-1] is nonzero.
326
327 The Bigint fields are as follows:
328
329 - next is a header used by Balloc and Bfree to keep track of lists
330 of freed Bigints; it's also used for the linked list of
331 powers of 5 of the form 5**2**i used by pow5mult.
332 - k indicates which pool this Bigint was allocated from
333 - maxwds is the maximum number of words space was allocated for
334 (usually maxwds == 2**k)
335 - sign is 1 for negative Bigints, 0 for positive. The sign is unused
336 (ignored on inputs, set to 0 on outputs) in almost all operations
337 involving Bigints: a notable exception is the diff function, which
338 ignores signs on inputs but sets the sign of the output correctly.
339 - wds is the actual number of significant words
340 - x contains the vector of words (digits) for this Bigint, from least
341 significant (x[0]) to most significant (x[wds-1]).
342 */
343
344 struct
345 Bigint {
346 struct Bigint *next;
347 int k, maxwds, sign, wds;
348 ULong x[1];
349 };
350
351 typedef struct Bigint Bigint;
352
353 #ifndef Py_USING_MEMORY_DEBUGGER
354
355 /* Memory management: memory is allocated from, and returned to, Kmax+1 pools
356 of memory, where pool k (0 <= k <= Kmax) is for Bigints b with b->maxwds ==
357 1 << k. These pools are maintained as linked lists, with freelist[k]
358 pointing to the head of the list for pool k.
359
360 On allocation, if there's no free slot in the appropriate pool, MALLOC is
361 called to get more memory. This memory is not returned to the system until
362 Python quits. There's also a private memory pool that's allocated from
363 in preference to using MALLOC.
364
365 For Bigints with more than (1 << Kmax) digits (which implies at least 1233
366 decimal digits), memory is directly allocated using MALLOC, and freed using
367 FREE.
368
369 XXX: it would be easy to bypass this memory-management system and
370 translate each call to Balloc into a call to PyMem_Malloc, and each
371 Bfree to PyMem_Free. Investigate whether this has any significant
372 performance on impact. */
373
374 static Bigint *freelist[Kmax+1];
375
376 /* Allocate space for a Bigint with up to 1<<k digits */
377
378 static Bigint *
379 Balloc(int k)
380 {
381 int x;
382 Bigint *rv;
383 unsigned int len;
384
385 if (k <= Kmax && (rv = freelist[k]))
386 freelist[k] = rv->next;
387 else {
388 x = 1 << k;
389 len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)
390 /sizeof(double);
391 if (k <= Kmax && pmem_next - private_mem + len <= PRIVATE_mem) {
392 rv = (Bigint*)pmem_next;
393 pmem_next += len;
394 }
395 else {
396 rv = (Bigint*)MALLOC(len*sizeof(double));
397 if (rv == NULL)
398 return NULL;
399 }
400 rv->k = k;
401 rv->maxwds = x;
402 }
403 rv->sign = rv->wds = 0;
404 return rv;
405 }
406
407 /* Free a Bigint allocated with Balloc */
408
409 static void
410 Bfree(Bigint *v)
411 {
412 if (v) {
413 if (v->k > Kmax)
414 FREE((void*)v);
415 else {
416 v->next = freelist[v->k];
417 freelist[v->k] = v;
418 }
419 }
420 }
421
422 #else
423
424 /* Alternative versions of Balloc and Bfree that use PyMem_Malloc and
425 PyMem_Free directly in place of the custom memory allocation scheme above.
426 These are provided for the benefit of memory debugging tools like
427 Valgrind. */
428
429 /* Allocate space for a Bigint with up to 1<<k digits */
430
431 static Bigint *
432 Balloc(int k)
433 {
434 int x;
435 Bigint *rv;
436 unsigned int len;
437
438 x = 1 << k;
439 len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)
440 /sizeof(double);
441
442 rv = (Bigint*)MALLOC(len*sizeof(double));
443 if (rv == NULL)
444 return NULL;
445
446 rv->k = k;
447 rv->maxwds = x;
448 rv->sign = rv->wds = 0;
449 return rv;
450 }
451
452 /* Free a Bigint allocated with Balloc */
453
454 static void
455 Bfree(Bigint *v)
456 {
457 if (v) {
458 FREE((void*)v);
459 }
460 }
461
462 #endif /* Py_USING_MEMORY_DEBUGGER */
463
464 #define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign, \
465 y->wds*sizeof(Long) + 2*sizeof(int))
466
467 /* Multiply a Bigint b by m and add a. Either modifies b in place and returns
468 a pointer to the modified b, or Bfrees b and returns a pointer to a copy.
469 On failure, return NULL. In this case, b will have been already freed. */
470
471 static Bigint *
472 multadd(Bigint *b, int m, int a) /* multiply by m and add a */
473 {
474 int i, wds;
475 #ifdef ULLong
476 ULong *x;
477 ULLong carry, y;
478 #else
479 ULong carry, *x, y;
480 ULong xi, z;
481 #endif
482 Bigint *b1;
483
484 wds = b->wds;
485 x = b->x;
486 i = 0;
487 carry = a;
488 do {
489 #ifdef ULLong
490 y = *x * (ULLong)m + carry;
491 carry = y >> 32;
492 *x++ = (ULong)(y & FFFFFFFF);
493 #else
494 xi = *x;
495 y = (xi & 0xffff) * m + carry;
496 z = (xi >> 16) * m + (y >> 16);
497 carry = z >> 16;
498 *x++ = (z << 16) + (y & 0xffff);
499 #endif
500 }
501 while(++i < wds);
502 if (carry) {
503 if (wds >= b->maxwds) {
504 b1 = Balloc(b->k+1);
505 if (b1 == NULL){
506 Bfree(b);
507 return NULL;
508 }
509 Bcopy(b1, b);
510 Bfree(b);
511 b = b1;
512 }
513 b->x[wds++] = (ULong)carry;
514 b->wds = wds;
515 }
516 return b;
517 }
518
519 /* convert a string s containing nd decimal digits (possibly containing a
520 decimal separator at position nd0, which is ignored) to a Bigint. This
521 function carries on where the parsing code in __Py_dg_strtod leaves off: on
522 entry, y9 contains the result of converting the first 9 digits. Returns
523 NULL on failure. */
524
525 static Bigint *
526 s2b(const char *s, int nd0, int nd, ULong y9)
527 {
528 Bigint *b;
529 int i, k;
530 Long x, y;
531
532 x = (nd + 8) / 9;
533 for(k = 0, y = 1; x > y; y <<= 1, k++) ;
534 b = Balloc(k);
535 if (b == NULL)
536 return NULL;
537 b->x[0] = y9;
538 b->wds = 1;
539
540 if (nd <= 9)
541 return b;
542
543 s += 9;
544 for (i = 9; i < nd0; i++) {
545 b = multadd(b, 10, *s++ - '0');
546 if (b == NULL)
547 return NULL;
548 }
549 s++;
550 for(; i < nd; i++) {
551 b = multadd(b, 10, *s++ - '0');
552 if (b == NULL)
553 return NULL;
554 }
555 return b;
556 }
557
558 /* count leading 0 bits in the 32-bit integer x. */
559
560 static int
561 hi0bits(ULong x)
562 {
563 int k = 0;
564
565 if (!(x & 0xffff0000)) {
566 k = 16;
567 x <<= 16;
568 }
569 if (!(x & 0xff000000)) {
570 k += 8;
571 x <<= 8;
572 }
573 if (!(x & 0xf0000000)) {
574 k += 4;
575 x <<= 4;
576 }
577 if (!(x & 0xc0000000)) {
578 k += 2;
579 x <<= 2;
580 }
581 if (!(x & 0x80000000)) {
582 k++;
583 if (!(x & 0x40000000))
584 return 32;
585 }
586 return k;
587 }
588
589 /* count trailing 0 bits in the 32-bit integer y, and shift y right by that
590 number of bits. */
591
592 static int
593 lo0bits(ULong *y)
594 {
595 int k;
596 ULong x = *y;
597
598 if (x & 7) {
599 if (x & 1)
600 return 0;
601 if (x & 2) {
602 *y = x >> 1;
603 return 1;
604 }
605 *y = x >> 2;
606 return 2;
607 }
608 k = 0;
609 if (!(x & 0xffff)) {
610 k = 16;
611 x >>= 16;
612 }
613 if (!(x & 0xff)) {
614 k += 8;
615 x >>= 8;
616 }
617 if (!(x & 0xf)) {
618 k += 4;
619 x >>= 4;
620 }
621 if (!(x & 0x3)) {
622 k += 2;
623 x >>= 2;
624 }
625 if (!(x & 1)) {
626 k++;
627 x >>= 1;
628 if (!x)
629 return 32;
630 }
631 *y = x;
632 return k;
633 }
634
635 /* convert a small nonnegative integer to a Bigint */
636
637 static Bigint *
638 i2b(int i)
639 {
640 Bigint *b;
641
642 b = Balloc(1);
643 if (b == NULL)
644 return NULL;
645 b->x[0] = i;
646 b->wds = 1;
647 return b;
648 }
649
650 /* multiply two Bigints. Returns a new Bigint, or NULL on failure. Ignores
651 the signs of a and b. */
652
653 static Bigint *
654 mult(Bigint *a, Bigint *b)
655 {
656 Bigint *c;
657 int k, wa, wb, wc;
658 ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
659 ULong y;
660 #ifdef ULLong
661 ULLong carry, z;
662 #else
663 ULong carry, z;
664 ULong z2;
665 #endif
666
667 if ((!a->x[0] && a->wds == 1) || (!b->x[0] && b->wds == 1)) {
668 c = Balloc(0);
669 if (c == NULL)
670 return NULL;
671 c->wds = 1;
672 c->x[0] = 0;
673 return c;
674 }
675
676 if (a->wds < b->wds) {
677 c = a;
678 a = b;
679 b = c;
680 }
681 k = a->k;
682 wa = a->wds;
683 wb = b->wds;
684 wc = wa + wb;
685 if (wc > a->maxwds)
686 k++;
687 c = Balloc(k);
688 if (c == NULL)
689 return NULL;
690 for(x = c->x, xa = x + wc; x < xa; x++)
691 *x = 0;
692 xa = a->x;
693 xae = xa + wa;
694 xb = b->x;
695 xbe = xb + wb;
696 xc0 = c->x;
697 #ifdef ULLong
698 for(; xb < xbe; xc0++) {
699 if ((y = *xb++)) {
700 x = xa;
701 xc = xc0;
702 carry = 0;
703 do {
704 z = *x++ * (ULLong)y + *xc + carry;
705 carry = z >> 32;
706 *xc++ = (ULong)(z & FFFFFFFF);
707 }
708 while(x < xae);
709 *xc = (ULong)carry;
710 }
711 }
712 #else
713 for(; xb < xbe; xb++, xc0++) {
714 if (y = *xb & 0xffff) {
715 x = xa;
716 xc = xc0;
717 carry = 0;
718 do {
719 z = (*x & 0xffff) * y + (*xc & 0xffff) + carry;
720 carry = z >> 16;
721 z2 = (*x++ >> 16) * y + (*xc >> 16) + carry;
722 carry = z2 >> 16;
723 Storeinc(xc, z2, z);
724 }
725 while(x < xae);
726 *xc = carry;
727 }
728 if (y = *xb >> 16) {
729 x = xa;
730 xc = xc0;
731 carry = 0;
732 z2 = *xc;
733 do {
734 z = (*x & 0xffff) * y + (*xc >> 16) + carry;
735 carry = z >> 16;
736 Storeinc(xc, z, z2);
737 z2 = (*x++ >> 16) * y + (*xc & 0xffff) + carry;
738 carry = z2 >> 16;
739 }
740 while(x < xae);
741 *xc = z2;
742 }
743 }
744 #endif
745 for(xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ;
746 c->wds = wc;
747 return c;
748 }
749
750 #ifndef Py_USING_MEMORY_DEBUGGER
751
752 /* p5s is a linked list of powers of 5 of the form 5**(2**i), i >= 2 */
753
754 static Bigint *p5s;
755
756 /* multiply the Bigint b by 5**k. Returns a pointer to the result, or NULL on
757 failure; if the returned pointer is distinct from b then the original
758 Bigint b will have been Bfree'd. Ignores the sign of b. */
759
760 static Bigint *
761 pow5mult(Bigint *b, int k)
762 {
763 Bigint *b1, *p5, *p51;
764 int i;
765 static const int p05[3] = { 5, 25, 125 };
766
767 if ((i = k & 3)) {
768 b = multadd(b, p05[i-1], 0);
769 if (b == NULL)
770 return NULL;
771 }
772
773 if (!(k >>= 2))
774 return b;
775 p5 = p5s;
776 if (!p5) {
777 /* first time */
778 p5 = i2b(625);
779 if (p5 == NULL) {
780 Bfree(b);
781 return NULL;
782 }
783 p5s = p5;
784 p5->next = 0;
785 }
786 for(;;) {
787 if (k & 1) {
788 b1 = mult(b, p5);
789 Bfree(b);
790 b = b1;
791 if (b == NULL)
792 return NULL;
793 }
794 if (!(k >>= 1))
795 break;
796 p51 = p5->next;
797 if (!p51) {
798 p51 = mult(p5,p5);
799 if (p51 == NULL) {
800 Bfree(b);
801 return NULL;
802 }
803 p51->next = 0;
804 p5->next = p51;
805 }
806 p5 = p51;
807 }
808 return b;
809 }
810
811 #else
812
813 /* Version of pow5mult that doesn't cache powers of 5. Provided for
814 the benefit of memory debugging tools like Valgrind. */
815
816 static Bigint *
817 pow5mult(Bigint *b, int k)
818 {
819 Bigint *b1, *p5, *p51;
820 int i;
821 static const int p05[3] = { 5, 25, 125 };
822
823 if ((i = k & 3)) {
824 b = multadd(b, p05[i-1], 0);
825 if (b == NULL)
826 return NULL;
827 }
828
829 if (!(k >>= 2))
830 return b;
831 p5 = i2b(625);
832 if (p5 == NULL) {
833 Bfree(b);
834 return NULL;
835 }
836
837 for(;;) {
838 if (k & 1) {
839 b1 = mult(b, p5);
840 Bfree(b);
841 b = b1;
842 if (b == NULL) {
843 Bfree(p5);
844 return NULL;
845 }
846 }
847 if (!(k >>= 1))
848 break;
849 p51 = mult(p5, p5);
850 Bfree(p5);
851 p5 = p51;
852 if (p5 == NULL) {
853 Bfree(b);
854 return NULL;
855 }
856 }
857 Bfree(p5);
858 return b;
859 }
860
861 #endif /* Py_USING_MEMORY_DEBUGGER */
862
863 /* shift a Bigint b left by k bits. Return a pointer to the shifted result,
864 or NULL on failure. If the returned pointer is distinct from b then the
865 original b will have been Bfree'd. Ignores the sign of b. */
866
867 static Bigint *
868 lshift(Bigint *b, int k)
869 {
870 int i, k1, n, n1;
871 Bigint *b1;
872 ULong *x, *x1, *xe, z;
873
874 if (!k || (!b->x[0] && b->wds == 1))
875 return b;
876
877 n = k >> 5;
878 k1 = b->k;
879 n1 = n + b->wds + 1;
880 for(i = b->maxwds; n1 > i; i <<= 1)
881 k1++;
882 b1 = Balloc(k1);
883 if (b1 == NULL) {
884 Bfree(b);
885 return NULL;
886 }
887 x1 = b1->x;
888 for(i = 0; i < n; i++)
889 *x1++ = 0;
890 x = b->x;
891 xe = x + b->wds;
892 if (k &= 0x1f) {
893 k1 = 32 - k;
894 z = 0;
895 do {
896 *x1++ = *x << k | z;
897 z = *x++ >> k1;
898 }
899 while(x < xe);
900 if ((*x1 = z))
901 ++n1;
902 }
903 else do
904 *x1++ = *x++;
905 while(x < xe);
906 b1->wds = n1 - 1;
907 Bfree(b);
908 return b1;
909 }
910
911 /* Do a three-way compare of a and b, returning -1 if a < b, 0 if a == b and
912 1 if a > b. Ignores signs of a and b. */
913
914 static int
915 cmp(Bigint *a, Bigint *b)
916 {
917 ULong *xa, *xa0, *xb, *xb0;
918 int i, j;
919
920 i = a->wds;
921 j = b->wds;
922 #ifdef DEBUG
923 if (i > 1 && !a->x[i-1])
924 Bug("cmp called with a->x[a->wds-1] == 0");
925 if (j > 1 && !b->x[j-1])
926 Bug("cmp called with b->x[b->wds-1] == 0");
927 #endif
928 if (i -= j)
929 return i;
930 xa0 = a->x;
931 xa = xa0 + j;
932 xb0 = b->x;
933 xb = xb0 + j;
934 for(;;) {
935 if (*--xa != *--xb)
936 return *xa < *xb ? -1 : 1;
937 if (xa <= xa0)
938 break;
939 }
940 return 0;
941 }
942
943 /* Take the difference of Bigints a and b, returning a new Bigint. Returns
944 NULL on failure. The signs of a and b are ignored, but the sign of the
945 result is set appropriately. */
946
947 static Bigint *
948 diff(Bigint *a, Bigint *b)
949 {
950 Bigint *c;
951 int i, wa, wb;
952 ULong *xa, *xae, *xb, *xbe, *xc;
953 #ifdef ULLong
954 ULLong borrow, y;
955 #else
956 ULong borrow, y;
957 ULong z;
958 #endif
959
960 i = cmp(a,b);
961 if (!i) {
962 c = Balloc(0);
963 if (c == NULL)
964 return NULL;
965 c->wds = 1;
966 c->x[0] = 0;
967 return c;
968 }
969 if (i < 0) {
970 c = a;
971 a = b;
972 b = c;
973 i = 1;
974 }
975 else
976 i = 0;
977 c = Balloc(a->k);
978 if (c == NULL)
979 return NULL;
980 c->sign = i;
981 wa = a->wds;
982 xa = a->x;
983 xae = xa + wa;
984 wb = b->wds;
985 xb = b->x;
986 xbe = xb + wb;
987 xc = c->x;
988 borrow = 0;
989 #ifdef ULLong
990 do {
991 y = (ULLong)*xa++ - *xb++ - borrow;
992 borrow = y >> 32 & (ULong)1;
993 *xc++ = (ULong)(y & FFFFFFFF);
994 }
995 while(xb < xbe);
996 while(xa < xae) {
997 y = *xa++ - borrow;
998 borrow = y >> 32 & (ULong)1;
999 *xc++ = (ULong)(y & FFFFFFFF);
1000 }
1001 #else
1002 do {
1003 y = (*xa & 0xffff) - (*xb & 0xffff) - borrow;
1004 borrow = (y & 0x10000) >> 16;
1005 z = (*xa++ >> 16) - (*xb++ >> 16) - borrow;
1006 borrow = (z & 0x10000) >> 16;
1007 Storeinc(xc, z, y);
1008 }
1009 while(xb < xbe);
1010 while(xa < xae) {
1011 y = (*xa & 0xffff) - borrow;
1012 borrow = (y & 0x10000) >> 16;
1013 z = (*xa++ >> 16) - borrow;
1014 borrow = (z & 0x10000) >> 16;
1015 Storeinc(xc, z, y);
1016 }
1017 #endif
1018 while(!*--xc)
1019 wa--;
1020 c->wds = wa;
1021 return c;
1022 }
1023
1024 /* Given a positive normal double x, return the difference between x and the
1025 next double up. Doesn't give correct results for subnormals. */
1026
1027 static double
1028 ulp(U *x)
1029 {
1030 Long L;
1031 U u;
1032
1033 L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1;
1034 word0(&u) = L;
1035 word1(&u) = 0;
1036 return dval(&u);
1037 }
1038
1039 /* Convert a Bigint to a double plus an exponent */
1040
1041 static double
1042 b2d(Bigint *a, int *e)
1043 {
1044 ULong *xa, *xa0, w, y, z;
1045 int k;
1046 U d;
1047
1048 xa0 = a->x;
1049 xa = xa0 + a->wds;
1050 y = *--xa;
1051 #ifdef DEBUG
1052 if (!y) Bug("zero y in b2d");
1053 #endif
1054 k = hi0bits(y);
1055 *e = 32 - k;
1056 if (k < Ebits) {
1057 word0(&d) = Exp_1 | y >> (Ebits - k);
1058 w = xa > xa0 ? *--xa : 0;
1059 word1(&d) = y << ((32-Ebits) + k) | w >> (Ebits - k);
1060 goto ret_d;
1061 }
1062 z = xa > xa0 ? *--xa : 0;
1063 if (k -= Ebits) {
1064 word0(&d) = Exp_1 | y << k | z >> (32 - k);
1065 y = xa > xa0 ? *--xa : 0;
1066 word1(&d) = z << k | y >> (32 - k);
1067 }
1068 else {
1069 word0(&d) = Exp_1 | y;
1070 word1(&d) = z;
1071 }
1072 ret_d:
1073 return dval(&d);
1074 }
1075
1076 /* Convert a scaled double to a Bigint plus an exponent. Similar to d2b,
1077 except that it accepts the scale parameter used in __Py_dg_strtod (which
1078 should be either 0 or 2*P), and the normalization for the return value is
1079 different (see below). On input, d should be finite and nonnegative, and d
1080 / 2**scale should be exactly representable as an IEEE 754 double.
1081
1082 Returns a Bigint b and an integer e such that
1083
1084 dval(d) / 2**scale = b * 2**e.
1085
1086 Unlike d2b, b is not necessarily odd: b and e are normalized so
1087 that either 2**(P-1) <= b < 2**P and e >= Etiny, or b < 2**P
1088 and e == Etiny. This applies equally to an input of 0.0: in that
1089 case the return values are b = 0 and e = Etiny.
1090
1091 The above normalization ensures that for all possible inputs d,
1092 2**e gives ulp(d/2**scale).
1093
1094 Returns NULL on failure.
1095 */
1096
1097 static Bigint *
1098 sd2b(U *d, int scale, int *e)
1099 {
1100 Bigint *b;
1101
1102 b = Balloc(1);
1103 if (b == NULL)
1104 return NULL;
1105
1106 /* First construct b and e assuming that scale == 0. */
1107 b->wds = 2;
1108 b->x[0] = word1(d);
1109 b->x[1] = word0(d) & Frac_mask;
1110 *e = Etiny - 1 + (int)((word0(d) & Exp_mask) >> Exp_shift);
1111 if (*e < Etiny)
1112 *e = Etiny;
1113 else
1114 b->x[1] |= Exp_msk1;
1115
1116 /* Now adjust for scale, provided that b != 0. */
1117 if (scale && (b->x[0] || b->x[1])) {
1118 *e -= scale;
1119 if (*e < Etiny) {
1120 scale = Etiny - *e;
1121 *e = Etiny;
1122 /* We can't shift more than P-1 bits without shifting out a 1. */
1123 assert(0 < scale && scale <= P - 1);
1124 if (scale >= 32) {
1125 /* The bits shifted out should all be zero. */
1126 assert(b->x[0] == 0);
1127 b->x[0] = b->x[1];
1128 b->x[1] = 0;
1129 scale -= 32;
1130 }
1131 if (scale) {
1132 /* The bits shifted out should all be zero. */
1133 assert(b->x[0] << (32 - scale) == 0);
1134 b->x[0] = (b->x[0] >> scale) | (b->x[1] << (32 - scale));
1135 b->x[1] >>= scale;
1136 }
1137 }
1138 }
1139 /* Ensure b is normalized. */
1140 if (!b->x[1])
1141 b->wds = 1;
1142
1143 return b;
1144 }
1145
1146 /* Convert a double to a Bigint plus an exponent. Return NULL on failure.
1147
1148 Given a finite nonzero double d, return an odd Bigint b and exponent *e
1149 such that fabs(d) = b * 2**e. On return, *bbits gives the number of
1150 significant bits of b; that is, 2**(*bbits-1) <= b < 2**(*bbits).
1151
1152 If d is zero, then b == 0, *e == -1010, *bbits = 0.
1153 */
1154
1155 static Bigint *
1156 d2b(U *d, int *e, int *bits)
1157 {
1158 Bigint *b;
1159 int de, k;
1160 ULong *x, y, z;
1161 int i;
1162
1163 b = Balloc(1);
1164 if (b == NULL)
1165 return NULL;
1166 x = b->x;
1167
1168 z = word0(d) & Frac_mask;
1169 word0(d) &= 0x7fffffff; /* clear sign bit, which we ignore */
1170 if ((de = (int)(word0(d) >> Exp_shift)))
1171 z |= Exp_msk1;
1172 if ((y = word1(d))) {
1173 if ((k = lo0bits(&y))) {
1174 x[0] = y | z << (32 - k);
1175 z >>= k;
1176 }
1177 else
1178 x[0] = y;
1179 i =
1180 b->wds = (x[1] = z) ? 2 : 1;
1181 }
1182 else {
1183 k = lo0bits(&z);
1184 x[0] = z;
1185 i =
1186 b->wds = 1;
1187 k += 32;
1188 }
1189 if (de) {
1190 *e = de - Bias - (P-1) + k;
1191 *bits = P - k;
1192 }
1193 else {
1194 *e = de - Bias - (P-1) + 1 + k;
1195 *bits = 32*i - hi0bits(x[i-1]);
1196 }
1197 return b;
1198 }
1199
1200 /* Compute the ratio of two Bigints, as a double. The result may have an
1201 error of up to 2.5 ulps. */
1202
1203 static double
1204 ratio(Bigint *a, Bigint *b)
1205 {
1206 U da, db;
1207 int k, ka, kb;
1208
1209 dval(&da) = b2d(a, &ka);
1210 dval(&db) = b2d(b, &kb);
1211 k = ka - kb + 32*(a->wds - b->wds);
1212 if (k > 0)
1213 word0(&da) += k*Exp_msk1;
1214 else {
1215 k = -k;
1216 word0(&db) += k*Exp_msk1;
1217 }
1218 return dval(&da) / dval(&db);
1219 }
1220
1221 static const double
1222 tens[] = {
1223 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
1224 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
1225 1e20, 1e21, 1e22
1226 };
1227
1228 static const double
1229 bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 };
1230 static const double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128,
1231 9007199254740992.*9007199254740992.e-256
1232 /* = 2^106 * 1e-256 */
1233 };
1234 /* The factor of 2^53 in tinytens[4] helps us avoid setting the underflow */
1235 /* flag unnecessarily. It leads to a song and dance at the end of strtod. */
1236 #define Scale_Bit 0x10
1237 #define n_bigtens 5
1238
1239 #define ULbits 32
1240 #define kshift 5
1241 #define kmask 31
1242
1243
1244 static int
1245 dshift(Bigint *b, int p2)
1246 {
1247 int rv = hi0bits(b->x[b->wds-1]) - 4;
1248 if (p2 > 0)
1249 rv -= p2;
1250 return rv & kmask;
1251 }
1252
1253 /* special case of Bigint division. The quotient is always in the range 0 <=
1254 quotient < 10, and on entry the divisor S is normalized so that its top 4
1255 bits (28--31) are zero and bit 27 is set. */
1256
1257 static int
1258 quorem(Bigint *b, Bigint *S)
1259 {
1260 int n;
1261 ULong *bx, *bxe, q, *sx, *sxe;
1262 #ifdef ULLong
1263 ULLong borrow, carry, y, ys;
1264 #else
1265 ULong borrow, carry, y, ys;
1266 ULong si, z, zs;
1267 #endif
1268
1269 n = S->wds;
1270 #ifdef DEBUG
1271 /*debug*/ if (b->wds > n)
1272 /*debug*/ Bug("oversize b in quorem");
1273 #endif
1274 if (b->wds < n)
1275 return 0;
1276 sx = S->x;
1277 sxe = sx + --n;
1278 bx = b->x;
1279 bxe = bx + n;
1280 q = *bxe / (*sxe + 1); /* ensure q <= true quotient */
1281 #ifdef DEBUG
1282 /*debug*/ if (q > 9)
1283 /*debug*/ Bug("oversized quotient in quorem");
1284 #endif
1285 if (q) {
1286 borrow = 0;
1287 carry = 0;
1288 do {
1289 #ifdef ULLong
1290 ys = *sx++ * (ULLong)q + carry;
1291 carry = ys >> 32;
1292 y = *bx - (ys & FFFFFFFF) - borrow;
1293 borrow = y >> 32 & (ULong)1;
1294 *bx++ = (ULong)(y & FFFFFFFF);
1295 #else
1296 si = *sx++;
1297 ys = (si & 0xffff) * q + carry;
1298 zs = (si >> 16) * q + (ys >> 16);
1299 carry = zs >> 16;
1300 y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
1301 borrow = (y & 0x10000) >> 16;
1302 z = (*bx >> 16) - (zs & 0xffff) - borrow;
1303 borrow = (z & 0x10000) >> 16;
1304 Storeinc(bx, z, y);
1305 #endif
1306 }
1307 while(sx <= sxe);
1308 if (!*bxe) {
1309 bx = b->x;
1310 while(--bxe > bx && !*bxe)
1311 --n;
1312 b->wds = n;
1313 }
1314 }
1315 if (cmp(b, S) >= 0) {
1316 q++;
1317 borrow = 0;
1318 carry = 0;
1319 bx = b->x;
1320 sx = S->x;
1321 do {
1322 #ifdef ULLong
1323 ys = *sx++ + carry;
1324 carry = ys >> 32;
1325 y = *bx - (ys & FFFFFFFF) - borrow;
1326 borrow = y >> 32 & (ULong)1;
1327 *bx++ = (ULong)(y & FFFFFFFF);
1328 #else
1329 si = *sx++;
1330 ys = (si & 0xffff) + carry;
1331 zs = (si >> 16) + (ys >> 16);
1332 carry = zs >> 16;
1333 y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
1334 borrow = (y & 0x10000) >> 16;
1335 z = (*bx >> 16) - (zs & 0xffff) - borrow;
1336 borrow = (z & 0x10000) >> 16;
1337 Storeinc(bx, z, y);
1338 #endif
1339 }
1340 while(sx <= sxe);
1341 bx = b->x;
1342 bxe = bx + n;
1343 if (!*bxe) {
1344 while(--bxe > bx && !*bxe)
1345 --n;
1346 b->wds = n;
1347 }
1348 }
1349 return q;
1350 }
1351
1352 /* sulp(x) is a version of ulp(x) that takes bc.scale into account.
1353
1354 Assuming that x is finite and nonnegative (positive zero is fine
1355 here) and x / 2^bc.scale is exactly representable as a double,
1356 sulp(x) is equivalent to 2^bc.scale * ulp(x / 2^bc.scale). */
1357
1358 static double
1359 sulp(U *x, BCinfo *bc)
1360 {
1361 U u;
1362
1363 if (bc->scale && 2*P + 1 > (int)((word0(x) & Exp_mask) >> Exp_shift)) {
1364 /* rv/2^bc->scale is subnormal */
1365 word0(&u) = (P+2)*Exp_msk1;
1366 word1(&u) = 0;
1367 return u.d;
1368 }
1369 else {
1370 assert(word0(x) || word1(x)); /* x != 0.0 */
1371 return ulp(x);
1372 }
1373 }
1374
1375 /* The bigcomp function handles some hard cases for strtod, for inputs
1376 with more than STRTOD_DIGLIM digits. It's called once an initial
1377 estimate for the double corresponding to the input string has
1378 already been obtained by the code in __Py_dg_strtod.
1379
1380 The bigcomp function is only called after __Py_dg_strtod has found a
1381 double value rv such that either rv or rv + 1ulp represents the
1382 correctly rounded value corresponding to the original string. It
1383 determines which of these two values is the correct one by
1384 computing the decimal digits of rv + 0.5ulp and comparing them with
1385 the corresponding digits of s0.
1386
1387 In the following, write dv for the absolute value of the number represented
1388 by the input string.
1389
1390 Inputs:
1391
1392 s0 points to the first significant digit of the input string.
1393
1394 rv is a (possibly scaled) estimate for the closest double value to the
1395 value represented by the original input to __Py_dg_strtod. If
1396 bc->scale is nonzero, then rv/2^(bc->scale) is the approximation to
1397 the input value.
1398
1399 bc is a struct containing information gathered during the parsing and
1400 estimation steps of __Py_dg_strtod. Description of fields follows:
1401
1402 bc->e0 gives the exponent of the input value, such that dv = (integer
1403 given by the bd->nd digits of s0) * 10**e0
1404
1405 bc->nd gives the total number of significant digits of s0. It will
1406 be at least 1.
1407
1408 bc->nd0 gives the number of significant digits of s0 before the
1409 decimal separator. If there's no decimal separator, bc->nd0 ==
1410 bc->nd.
1411
1412 bc->scale is the value used to scale rv to avoid doing arithmetic with
1413 subnormal values. It's either 0 or 2*P (=106).
1414
1415 Outputs:
1416
1417 On successful exit, rv/2^(bc->scale) is the closest double to dv.
1418
1419 Returns 0 on success, -1 on failure (e.g., due to a failed malloc call). */
1420
1421 static int
1422 bigcomp(U *rv, const char *s0, BCinfo *bc)
1423 {
1424 Bigint *b, *d;
1425 int b2, d2, dd, i, nd, nd0, odd, p2, p5;
1426
1427 nd = bc->nd;
1428 nd0 = bc->nd0;
1429 p5 = nd + bc->e0;
1430 b = sd2b(rv, bc->scale, &p2);
1431 if (b == NULL)
1432 return -1;
1433
1434 /* record whether the lsb of rv/2^(bc->scale) is odd: in the exact halfway
1435 case, this is used for round to even. */
1436 odd = b->x[0] & 1;
1437
1438 /* left shift b by 1 bit and or a 1 into the least significant bit;
1439 this gives us b * 2**p2 = rv/2^(bc->scale) + 0.5 ulp. */
1440 b = lshift(b, 1);
1441 if (b == NULL)
1442 return -1;
1443 b->x[0] |= 1;
1444 p2--;
1445
1446 p2 -= p5;
1447 d = i2b(1);
1448 if (d == NULL) {
1449 Bfree(b);
1450 return -1;
1451 }
1452 /* Arrange for convenient computation of quotients:
1453 * shift left if necessary so divisor has 4 leading 0 bits.
1454 */
1455 if (p5 > 0) {
1456 d = pow5mult(d, p5);
1457 if (d == NULL) {
1458 Bfree(b);
1459 return -1;
1460 }
1461 }
1462 else if (p5 < 0) {
1463 b = pow5mult(b, -p5);
1464 if (b == NULL) {
1465 Bfree(d);
1466 return -1;
1467 }
1468 }
1469 if (p2 > 0) {
1470 b2 = p2;
1471 d2 = 0;
1472 }
1473 else {
1474 b2 = 0;
1475 d2 = -p2;
1476 }
1477 i = dshift(d, d2);
1478 if ((b2 += i) > 0) {
1479 b = lshift(b, b2);
1480 if (b == NULL) {
1481 Bfree(d);
1482 return -1;
1483 }
1484 }
1485 if ((d2 += i) > 0) {
1486 d = lshift(d, d2);
1487 if (d == NULL) {
1488 Bfree(b);
1489 return -1;
1490 }
1491 }
1492
1493 /* Compare s0 with b/d: set dd to -1, 0, or 1 according as s0 < b/d, s0 ==
1494 * b/d, or s0 > b/d. Here the digits of s0 are thought of as representing
1495 * a number in the range [0.1, 1). */
1496 if (cmp(b, d) >= 0)
1497 /* b/d >= 1 */
1498 dd = -1;
1499 else {
1500 i = 0;
1501 for(;;) {
1502 b = multadd(b, 10, 0);
1503 if (b == NULL) {
1504 Bfree(d);
1505 return -1;
1506 }
1507 dd = s0[i < nd0 ? i : i+1] - '0' - quorem(b, d);
1508 i++;
1509
1510 if (dd)
1511 break;
1512 if (!b->x[0] && b->wds == 1) {
1513 /* b/d == 0 */
1514 dd = i < nd;
1515 break;
1516 }
1517 if (!(i < nd)) {
1518 /* b/d != 0, but digits of s0 exhausted */
1519 dd = -1;
1520 break;
1521 }
1522 }
1523 }
1524 Bfree(b);
1525 Bfree(d);
1526 if (dd > 0 || (dd == 0 && odd))
1527 dval(rv) += sulp(rv, bc);
1528 return 0;
1529 }
1530
1531 static double
1532 __Py_dg_strtod(const char *s00, char **se)
1533 {
1534 int bb2, bb5, bbe, bd2, bd5, bs2, c, dsign, e, e1, error;
1535 int esign, i, j, k, lz, nd, nd0, odd, sign;
1536 const char *s, *s0, *s1;
1537 double aadj, aadj1;
1538 U aadj2, adj, rv, rv0;
1539 ULong y, z, abs_exp;
1540 Long L;
1541 BCinfo bc;
1542 Bigint *bb, *bb1, *bd, *bd0, *bs, *delta;
1543 size_t ndigits, fraclen;
1544
1545 dval(&rv) = 0.;
1546
1547 /* Start parsing. */
1548 c = *(s = s00);
1549
1550 /* Parse optional sign, if present. */
1551 sign = 0;
1552 switch (c) {
1553 case '-':
1554 sign = 1;
1555 /* no break */
1556 case '+':
1557 c = *++s;
1558 }
1559
1560 /* Skip leading zeros: lz is true iff there were leading zeros. */
1561 s1 = s;
1562 while (c == '0')
1563 c = *++s;
1564 lz = s != s1;
1565
1566 /* Point s0 at the first nonzero digit (if any). fraclen will be the
1567 number of digits between the decimal point and the end of the
1568 digit string. ndigits will be the total number of digits ignoring
1569 leading zeros. */
1570 s0 = s1 = s;
1571 while ('0' <= c && c <= '9')
1572 c = *++s;
1573 ndigits = s - s1;
1574 fraclen = 0;
1575
1576 /* Parse decimal point and following digits. */
1577 if (c == '.') {
1578 c = *++s;
1579 if (!ndigits) {
1580 s1 = s;
1581 while (c == '0')
1582 c = *++s;
1583 lz = lz || s != s1;
1584 fraclen += (s - s1);
1585 s0 = s;
1586 }
1587 s1 = s;
1588 while ('0' <= c && c <= '9')
1589 c = *++s;
1590 ndigits += s - s1;
1591 fraclen += s - s1;
1592 }
1593
1594 /* Now lz is true if and only if there were leading zero digits, and
1595 ndigits gives the total number of digits ignoring leading zeros. A
1596 valid input must have at least one digit. */
1597 if (!ndigits && !lz) {
1598 if (se)
1599 *se = (char *)s00;
1600 goto parse_error;
1601 }
1602
1603 /* Range check ndigits and fraclen to make sure that they, and values
1604 computed with them, can safely fit in an int. */
1605 if (ndigits > MAX_DIGITS || fraclen > MAX_DIGITS) {
1606 if (se)
1607 *se = (char *)s00;
1608 goto parse_error;
1609 }
1610 nd = (int)ndigits;
1611 nd0 = (int)ndigits - (int)fraclen;
1612
1613 /* Parse exponent. */
1614 e = 0;
1615 if (c == 'e' || c == 'E') {
1616 s00 = s;
1617 c = *++s;
1618
1619 /* Exponent sign. */
1620 esign = 0;
1621 switch (c) {
1622 case '-':
1623 esign = 1;
1624 /* no break */
1625 case '+':
1626 c = *++s;
1627 }
1628
1629 /* Skip zeros. lz is true iff there are leading zeros. */
1630 s1 = s;
1631 while (c == '0')
1632 c = *++s;
1633 lz = s != s1;
1634
1635 /* Get absolute value of the exponent. */
1636 s1 = s;
1637 abs_exp = 0;
1638 while ('0' <= c && c <= '9') {
1639 abs_exp = 10*abs_exp + (c - '0');
1640 c = *++s;
1641 }
1642
1643 /* abs_exp will be correct modulo 2**32. But 10**9 < 2**32, so if
1644 there are at most 9 significant exponent digits then overflow is
1645 impossible. */
1646 if (s - s1 > 9 || abs_exp > MAX_ABS_EXP)
1647 e = (int)MAX_ABS_EXP;
1648 else
1649 e = (int)abs_exp;
1650 if (esign)
1651 e = -e;
1652
1653 /* A valid exponent must have at least one digit. */
1654 if (s == s1 && !lz)
1655 s = s00;
1656 }
1657
1658 /* Adjust exponent to take into account position of the point. */
1659 e -= nd - nd0;
1660 if (nd0 <= 0)
1661 nd0 = nd;
1662
1663 /* Finished parsing. Set se to indicate how far we parsed */
1664 if (se)
1665 *se = (char *)s;
1666
1667 /* If all digits were zero, exit with return value +-0.0. Otherwise,
1668 strip trailing zeros: scan back until we hit a nonzero digit. */
1669 if (!nd)
1670 goto ret;
1671 for (i = nd; i > 0; ) {
1672 --i;
1673 if (s0[i < nd0 ? i : i+1] != '0') {
1674 ++i;
1675 break;
1676 }
1677 }
1678 e += nd - i;
1679 nd = i;
1680 if (nd0 > nd)
1681 nd0 = nd;
1682
1683 /* Summary of parsing results. After parsing, and dealing with zero
1684 * inputs, we have values s0, nd0, nd, e, sign, where:
1685 *
1686 * - s0 points to the first significant digit of the input string
1687 *
1688 * - nd is the total number of significant digits (here, and
1689 * below, 'significant digits' means the set of digits of the
1690 * significand of the input that remain after ignoring leading
1691 * and trailing zeros).
1692 *
1693 * - nd0 indicates the position of the decimal point, if present; it
1694 * satisfies 1 <= nd0 <= nd. The nd significant digits are in
1695 * s0[0:nd0] and s0[nd0+1:nd+1] using the usual Python half-open slice
1696 * notation. (If nd0 < nd, then s0[nd0] contains a '.' character; if
1697 * nd0 == nd, then s0[nd0] could be any non-digit character.)
1698 *
1699 * - e is the adjusted exponent: the absolute value of the number
1700 * represented by the original input string is n * 10**e, where
1701 * n is the integer represented by the concatenation of
1702 * s0[0:nd0] and s0[nd0+1:nd+1]
1703 *
1704 * - sign gives the sign of the input: 1 for negative, 0 for positive
1705 *
1706 * - the first and last significant digits are nonzero
1707 */
1708
1709 /* put first DBL_DIG+1 digits into integer y and z.
1710 *
1711 * - y contains the value represented by the first min(9, nd)
1712 * significant digits
1713 *
1714 * - if nd > 9, z contains the value represented by significant digits
1715 * with indices in [9, min(16, nd)). So y * 10**(min(16, nd) - 9) + z
1716 * gives the value represented by the first min(16, nd) sig. digits.
1717 */
1718
1719 bc.e0 = e1 = e;
1720 y = z = 0;
1721 for (i = 0; i < nd; i++) {
1722 if (i < 9)
1723 y = 10*y + s0[i < nd0 ? i : i+1] - '0';
1724 else if (i < DBL_DIG+1)
1725 z = 10*z + s0[i < nd0 ? i : i+1] - '0';
1726 else
1727 break;
1728 }
1729
1730 k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;
1731 dval(&rv) = y;
1732 if (k > 9) {
1733 dval(&rv) = tens[k - 9] * dval(&rv) + z;
1734 }
1735 bd0 = 0;
1736 if (nd <= DBL_DIG
1737 && Flt_Rounds == 1
1738 ) {
1739 if (!e)
1740 goto ret;
1741 if (e > 0) {
1742 if (e <= Ten_pmax) {
1743 dval(&rv) *= tens[e];
1744 goto ret;
1745 }
1746 i = DBL_DIG - nd;
1747 if (e <= Ten_pmax + i) {
1748 /* A fancier test would sometimes let us do
1749 * this for larger i values.
1750 */
1751 e -= i;
1752 dval(&rv) *= tens[i];
1753 dval(&rv) *= tens[e];
1754 goto ret;
1755 }
1756 }
1757 else if (e >= -Ten_pmax) {
1758 dval(&rv) /= tens[-e];
1759 goto ret;
1760 }
1761 }
1762 e1 += nd - k;
1763
1764 bc.scale = 0;
1765
1766 /* Get starting approximation = rv * 10**e1 */
1767
1768 if (e1 > 0) {
1769 if ((i = e1 & 15))
1770 dval(&rv) *= tens[i];
1771 if (e1 &= ~15) {
1772 if (e1 > DBL_MAX_10_EXP)
1773 goto ovfl;
1774 e1 >>= 4;
1775 for(j = 0; e1 > 1; j++, e1 >>= 1)
1776 if (e1 & 1)
1777 dval(&rv) *= bigtens[j];
1778 /* The last multiplication could overflow. */
1779 word0(&rv) -= P*Exp_msk1;
1780 dval(&rv) *= bigtens[j];
1781 if ((z = word0(&rv) & Exp_mask)
1782 > Exp_msk1*(DBL_MAX_EXP+Bias-P))
1783 goto ovfl;
1784 if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) {
1785 /* set to largest number */
1786 /* (Can't trust DBL_MAX) */
1787 word0(&rv) = Big0;
1788 word1(&rv) = Big1;
1789 }
1790 else
1791 word0(&rv) += P*Exp_msk1;
1792 }
1793 }
1794 else if (e1 < 0) {
1795 /* The input decimal value lies in [10**e1, 10**(e1+16)).
1796
1797 If e1 <= -512, underflow immediately.
1798 If e1 <= -256, set bc.scale to 2*P.
1799
1800 So for input value < 1e-256, bc.scale is always set;
1801 for input value >= 1e-240, bc.scale is never set.
1802 For input values in [1e-256, 1e-240), bc.scale may or may
1803 not be set. */
1804
1805 e1 = -e1;
1806 if ((i = e1 & 15))
1807 dval(&rv) /= tens[i];
1808 if (e1 >>= 4) {
1809 if (e1 >= 1 << n_bigtens)
1810 goto undfl;
1811 if (e1 & Scale_Bit)
1812 bc.scale = 2*P;
1813 for(j = 0; e1 > 0; j++, e1 >>= 1)
1814 if (e1 & 1)
1815 dval(&rv) *= tinytens[j];
1816 if (bc.scale && (j = 2*P + 1 - ((word0(&rv) & Exp_mask)
1817 >> Exp_shift)) > 0) {
1818 /* scaled rv is denormal; clear j low bits */
1819 if (j >= 32) {
1820 word1(&rv) = 0;
1821 if (j >= 53)
1822 word0(&rv) = (P+2)*Exp_msk1;
1823 else
1824 word0(&rv) &= 0xffffffff << (j-32);
1825 }
1826 else
1827 word1(&rv) &= 0xffffffff << j;
1828 }
1829 if (!dval(&rv))
1830 goto undfl;
1831 }
1832 }
1833
1834 /* Now the hard part -- adjusting rv to the correct value.*/
1835
1836 /* Put digits into bd: true value = bd * 10^e */
1837
1838 bc.nd = nd;
1839 bc.nd0 = nd0; /* Only needed if nd > STRTOD_DIGLIM, but done here */
1840 /* to silence an erroneous warning about bc.nd0 */
1841 /* possibly not being initialized. */
1842 if (nd > STRTOD_DIGLIM) {
1843 /* ASSERT(STRTOD_DIGLIM >= 18); 18 == one more than the */
1844 /* minimum number of decimal digits to distinguish double values */
1845 /* in IEEE arithmetic. */
1846
1847 /* Truncate input to 18 significant digits, then discard any trailing
1848 zeros on the result by updating nd, nd0, e and y suitably. (There's
1849 no need to update z; it's not reused beyond this point.) */
1850 for (i = 18; i > 0; ) {
1851 /* scan back until we hit a nonzero digit. significant digit 'i'
1852 is s0[i] if i < nd0, s0[i+1] if i >= nd0. */
1853 --i;
1854 if (s0[i < nd0 ? i : i+1] != '0') {
1855 ++i;
1856 break;
1857 }
1858 }
1859 e += nd - i;
1860 nd = i;
1861 if (nd0 > nd)
1862 nd0 = nd;
1863 if (nd < 9) { /* must recompute y */
1864 y = 0;
1865 for(i = 0; i < nd0; ++i)
1866 y = 10*y + s0[i] - '0';
1867 for(; i < nd; ++i)
1868 y = 10*y + s0[i+1] - '0';
1869 }
1870 }
1871 bd0 = s2b(s0, nd0, nd, y);
1872 if (bd0 == NULL)
1873 goto failed_malloc;
1874
1875 /* Notation for the comments below. Write:
1876
1877 - dv for the absolute value of the number represented by the original
1878 decimal input string.
1879
1880 - if we've truncated dv, write tdv for the truncated value.
1881 Otherwise, set tdv == dv.
1882
1883 - srv for the quantity rv/2^bc.scale; so srv is the current binary
1884 approximation to tdv (and dv). It should be exactly representable
1885 in an IEEE 754 double.
1886 */
1887
1888 for(;;) {
1889
1890 /* This is the main correction loop for __Py_dg_strtod.
1891
1892 We've got a decimal value tdv, and a floating-point approximation
1893 srv=rv/2^bc.scale to tdv. The aim is to determine whether srv is
1894 close enough (i.e., within 0.5 ulps) to tdv, and to compute a new
1895 approximation if not.
1896
1897 To determine whether srv is close enough to tdv, compute integers
1898 bd, bb and bs proportional to tdv, srv and 0.5 ulp(srv)
1899 respectively, and then use integer arithmetic to determine whether
1900 |tdv - srv| is less than, equal to, or greater than 0.5 ulp(srv).
1901 */
1902
1903 bd = Balloc(bd0->k);
1904 if (bd == NULL) {
1905 Bfree(bd0);
1906 goto failed_malloc;
1907 }
1908 Bcopy(bd, bd0);
1909 bb = sd2b(&rv, bc.scale, &bbe); /* srv = bb * 2^bbe */
1910 if (bb == NULL) {
1911 Bfree(bd);
1912 Bfree(bd0);
1913 goto failed_malloc;
1914 }
1915 /* Record whether lsb of bb is odd, in case we need this
1916 for the round-to-even step later. */
1917 odd = bb->x[0] & 1;
1918
1919 /* tdv = bd * 10**e; srv = bb * 2**bbe */
1920 bs = i2b(1);
1921 if (bs == NULL) {
1922 Bfree(bb);
1923 Bfree(bd);
1924 Bfree(bd0);
1925 goto failed_malloc;
1926 }
1927
1928 if (e >= 0) {
1929 bb2 = bb5 = 0;
1930 bd2 = bd5 = e;
1931 }
1932 else {
1933 bb2 = bb5 = -e;
1934 bd2 = bd5 = 0;
1935 }
1936 if (bbe >= 0)
1937 bb2 += bbe;
1938 else
1939 bd2 -= bbe;
1940 bs2 = bb2;
1941 bb2++;
1942 bd2++;
1943
1944 /* At this stage bd5 - bb5 == e == bd2 - bb2 + bbe, bb2 - bs2 == 1,
1945 and bs == 1, so:
1946
1947 tdv == bd * 10**e = bd * 2**(bbe - bb2 + bd2) * 5**(bd5 - bb5)
1948 srv == bb * 2**bbe = bb * 2**(bbe - bb2 + bb2)
1949 0.5 ulp(srv) == 2**(bbe-1) = bs * 2**(bbe - bb2 + bs2)
1950
1951 It follows that:
1952
1953 M * tdv = bd * 2**bd2 * 5**bd5
1954 M * srv = bb * 2**bb2 * 5**bb5
1955 M * 0.5 ulp(srv) = bs * 2**bs2 * 5**bb5
1956
1957 for some constant M. (Actually, M == 2**(bb2 - bbe) * 5**bb5, but
1958 this fact is not needed below.)
1959 */
1960
1961 /* Remove factor of 2**i, where i = min(bb2, bd2, bs2). */
1962 i = bb2 < bd2 ? bb2 : bd2;
1963 if (i > bs2)
1964 i = bs2;
1965 if (i > 0) {
1966 bb2 -= i;
1967 bd2 -= i;
1968 bs2 -= i;
1969 }
1970
1971 /* Scale bb, bd, bs by the appropriate powers of 2 and 5. */
1972 if (bb5 > 0) {
1973 bs = pow5mult(bs, bb5);
1974 if (bs == NULL) {
1975 Bfree(bb);
1976 Bfree(bd);
1977 Bfree(bd0);
1978 goto failed_malloc;
1979 }
1980 bb1 = mult(bs, bb);
1981 Bfree(bb);
1982 bb = bb1;
1983 if (bb == NULL) {
1984 Bfree(bs);
1985 Bfree(bd);
1986 Bfree(bd0);
1987 goto failed_malloc;
1988 }
1989 }
1990 if (bb2 > 0) {
1991 bb = lshift(bb, bb2);
1992 if (bb == NULL) {
1993 Bfree(bs);
1994 Bfree(bd);
1995 Bfree(bd0);
1996 goto failed_malloc;
1997 }
1998 }
1999 if (bd5 > 0) {
2000 bd = pow5mult(bd, bd5);
2001 if (bd == NULL) {
2002 Bfree(bb);
2003 Bfree(bs);
2004 Bfree(bd0);
2005 goto failed_malloc;
2006 }
2007 }
2008 if (bd2 > 0) {
2009 bd = lshift(bd, bd2);
2010 if (bd == NULL) {
2011 Bfree(bb);
2012 Bfree(bs);
2013 Bfree(bd0);
2014 goto failed_malloc;
2015 }
2016 }
2017 if (bs2 > 0) {
2018 bs = lshift(bs, bs2);
2019 if (bs == NULL) {
2020 Bfree(bb);
2021 Bfree(bd);
2022 Bfree(bd0);
2023 goto failed_malloc;
2024 }
2025 }
2026
2027 /* Now bd, bb and bs are scaled versions of tdv, srv and 0.5 ulp(srv),
2028 respectively. Compute the difference |tdv - srv|, and compare
2029 with 0.5 ulp(srv). */
2030
2031 delta = diff(bb, bd);
2032 if (delta == NULL) {
2033 Bfree(bb);
2034 Bfree(bs);
2035 Bfree(bd);
2036 Bfree(bd0);
2037 goto failed_malloc;
2038 }
2039 dsign = delta->sign;
2040 delta->sign = 0;
2041 i = cmp(delta, bs);
2042 if (bc.nd > nd && i <= 0) {
2043 if (dsign)
2044 break; /* Must use bigcomp(). */
2045
2046 /* Here rv overestimates the truncated decimal value by at most
2047 0.5 ulp(rv). Hence rv either overestimates the true decimal
2048 value by <= 0.5 ulp(rv), or underestimates it by some small
2049 amount (< 0.1 ulp(rv)); either way, rv is within 0.5 ulps of
2050 the true decimal value, so it's possible to exit.
2051
2052 Exception: if scaled rv is a normal exact power of 2, but not
2053 DBL_MIN, then rv - 0.5 ulp(rv) takes us all the way down to the
2054 next double, so the correctly rounded result is either rv - 0.5
2055 ulp(rv) or rv; in this case, use bigcomp to distinguish. */
2056
2057 if (!word1(&rv) && !(word0(&rv) & Bndry_mask)) {
2058 /* rv can't be 0, since it's an overestimate for some
2059 nonzero value. So rv is a normal power of 2. */
2060 j = (int)(word0(&rv) & Exp_mask) >> Exp_shift;
2061 /* rv / 2^bc.scale = 2^(j - 1023 - bc.scale); use bigcomp if
2062 rv / 2^bc.scale >= 2^-1021. */
2063 if (j - bc.scale >= 2) {
2064 dval(&rv) -= 0.5 * sulp(&rv, &bc);
2065 break; /* Use bigcomp. */
2066 }
2067 }
2068
2069 {
2070 bc.nd = nd;
2071 i = -1; /* Discarded digits make delta smaller. */
2072 }
2073 }
2074
2075 if (i < 0) {
2076 /* Error is less than half an ulp -- check for
2077 * special case of mantissa a power of two.
2078 */
2079 if (dsign || word1(&rv) || word0(&rv) & Bndry_mask
2080 || (word0(&rv) & Exp_mask) <= (2*P+1)*Exp_msk1
2081 ) {
2082 break;
2083 }
2084 if (!delta->x[0] && delta->wds <= 1) {
2085 /* exact result */
2086 break;
2087 }
2088 delta = lshift(delta,Log2P);
2089 if (delta == NULL) {
2090 Bfree(bb);
2091 Bfree(bs);
2092 Bfree(bd);
2093 Bfree(bd0);
2094 goto failed_malloc;
2095 }
2096 if (cmp(delta, bs) > 0)
2097 goto drop_down;
2098 break;
2099 }
2100 if (i == 0) {
2101 /* exactly half-way between */
2102 if (dsign) {
2103 if ((word0(&rv) & Bndry_mask1) == Bndry_mask1
2104 && word1(&rv) == (
2105 (bc.scale &&
2106 (y = word0(&rv) & Exp_mask) <= 2*P*Exp_msk1) ?
2107 (0xffffffff & (0xffffffff << (2*P+1-(y>>Exp_shift)))) :
2108 0xffffffff)) {
2109 /*boundary case -- increment exponent*/
2110 word0(&rv) = (word0(&rv) & Exp_mask)
2111 + Exp_msk1
2112 ;
2113 word1(&rv) = 0;
2114 dsign = 0;
2115 break;
2116 }
2117 }
2118 else if (!(word0(&rv) & Bndry_mask) && !word1(&rv)) {
2119 drop_down:
2120 /* boundary case -- decrement exponent */
2121 if (bc.scale) {
2122 L = word0(&rv) & Exp_mask;
2123 if (L <= (2*P+1)*Exp_msk1) {
2124 if (L > (P+2)*Exp_msk1)
2125 /* round even ==> */
2126 /* accept rv */
2127 break;
2128 /* rv = smallest denormal */
2129 if (bc.nd > nd)
2130 break;
2131 goto undfl;
2132 }
2133 }
2134 L = (word0(&rv) & Exp_mask) - Exp_msk1;
2135 word0(&rv) = L | Bndry_mask1;
2136 word1(&rv) = 0xffffffff;
2137 break;
2138 }
2139 if (!odd)
2140 break;
2141 if (dsign)
2142 dval(&rv) += sulp(&rv, &bc);
2143 else {
2144 dval(&rv) -= sulp(&rv, &bc);
2145 if (!dval(&rv)) {
2146 if (bc.nd >nd)
2147 break;
2148 goto undfl;
2149 }
2150 }
2151 dsign = 1 - dsign;
2152 break;
2153 }
2154 if ((aadj = ratio(delta, bs)) <= 2.) {
2155 if (dsign)
2156 aadj = aadj1 = 1.;
2157 else if (word1(&rv) || word0(&rv) & Bndry_mask) {
2158 if (word1(&rv) == Tiny1 && !word0(&rv)) {
2159 if (bc.nd >nd)
2160 break;
2161 goto undfl;
2162 }
2163 aadj = 1.;
2164 aadj1 = -1.;
2165 }
2166 else {
2167 /* special case -- power of FLT_RADIX to be */
2168 /* rounded down... */
2169
2170 if (aadj < 2./FLT_RADIX)
2171 aadj = 1./FLT_RADIX;
2172 else
2173 aadj *= 0.5;
2174 aadj1 = -aadj;
2175 }
2176 }
2177 else {
2178 aadj *= 0.5;
2179 aadj1 = dsign ? aadj : -aadj;
2180 if (Flt_Rounds == 0)
2181 aadj1 += 0.5;
2182 }
2183 y = word0(&rv) & Exp_mask;
2184
2185 /* Check for overflow */
2186
2187 if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) {
2188 dval(&rv0) = dval(&rv);
2189 word0(&rv) -= P*Exp_msk1;
2190 adj.d = aadj1 * ulp(&rv);
2191 dval(&rv) += adj.d;
2192 if ((word0(&rv) & Exp_mask) >=
2193 Exp_msk1*(DBL_MAX_EXP+Bias-P)) {
2194 if (word0(&rv0) == Big0 && word1(&rv0) == Big1) {
2195 Bfree(bb);
2196 Bfree(bd);
2197 Bfree(bs);
2198 Bfree(bd0);
2199 Bfree(delta);
2200 goto ovfl;
2201 }
2202 word0(&rv) = Big0;
2203 word1(&rv) = Big1;
2204 goto cont;
2205 }
2206 else
2207 word0(&rv) += P*Exp_msk1;
2208 }
2209 else {
2210 if (bc.scale && y <= 2*P*Exp_msk1) {
2211 if (aadj <= 0x7fffffff) {
2212 if ((z = (ULong)aadj) <= 0)
2213 z = 1;
2214 aadj = z;
2215 aadj1 = dsign ? aadj : -aadj;
2216 }
2217 dval(&aadj2) = aadj1;
2218 word0(&aadj2) += (2*P+1)*Exp_msk1 - y;
2219 aadj1 = dval(&aadj2);
2220 }
2221 adj.d = aadj1 * ulp(&rv);
2222 dval(&rv) += adj.d;
2223 }
2224 z = word0(&rv) & Exp_mask;
2225 if (bc.nd == nd) {
2226 if (!bc.scale)
2227 if (y == z) {
2228 /* Can we stop now? */
2229 L = (Long)aadj;
2230 aadj -= L;
2231 /* The tolerances below are conservative. */
2232 if (dsign || word1(&rv) || word0(&rv) & Bndry_mask) {
2233 if (aadj < .4999999 || aadj > .5000001)
2234 break;
2235 }
2236 else if (aadj < .4999999/FLT_RADIX)
2237 break;
2238 }
2239 }
2240 cont:
2241 Bfree(bb);
2242 Bfree(bd);
2243 Bfree(bs);
2244 Bfree(delta);
2245 }
2246 Bfree(bb);
2247 Bfree(bd);
2248 Bfree(bs);
2249 Bfree(bd0);
2250 Bfree(delta);
2251 if (bc.nd > nd) {
2252 error = bigcomp(&rv, s0, &bc);
2253 if (error)
2254 goto failed_malloc;
2255 }
2256
2257 if (bc.scale) {
2258 word0(&rv0) = Exp_1 - 2*P*Exp_msk1;
2259 word1(&rv0) = 0;
2260 dval(&rv) *= dval(&rv0);
2261 }
2262
2263 ret:
2264 return sign ? -dval(&rv) : dval(&rv);
2265
2266 parse_error:
2267 return 0.0;
2268
2269 failed_malloc:
2270 errno = ENOMEM;
2271 return -1.0;
2272
2273 undfl:
2274 return sign ? -0.0 : 0.0;
2275
2276 ovfl:
2277 errno = ERANGE;
2278 /* Can't trust HUGE_VAL */
2279 word0(&rv) = Exp_mask;
2280 word1(&rv) = 0;
2281 return sign ? -dval(&rv) : dval(&rv);
2282
2283 }
2284
2285 static char *
2286 rv_alloc(int i)
2287 {
2288 int j, k, *r;
2289
2290 j = sizeof(ULong);
2291 for(k = 0;
2292 sizeof(Bigint) - sizeof(ULong) - sizeof(int) + j <= (unsigned)i;
2293 j <<= 1)
2294 k++;
2295 r = (int*)Balloc(k);
2296 if (r == NULL)
2297 return NULL;
2298 *r = k;
2299 return (char *)(r+1);
2300 }
2301
2302 static char *
2303 nrv_alloc(const char *s, char **rve, int n)
2304 {
2305 char *rv, *t;
2306
2307 rv = rv_alloc(n);
2308 if (rv == NULL)
2309 return NULL;
2310 t = rv;
2311 while((*t = *s++)) t++;
2312 if (rve)
2313 *rve = t;
2314 return rv;
2315 }
2316
2317 /* freedtoa(s) must be used to free values s returned by dtoa
2318 * when MULTIPLE_THREADS is #defined. It should be used in all cases,
2319 * but for consistency with earlier versions of dtoa, it is optional
2320 * when MULTIPLE_THREADS is not defined.
2321 */
2322
2323 static void
2324 __Py_dg_freedtoa(char *s)
2325 {
2326 Bigint *b = (Bigint *)((int *)s - 1);
2327 b->maxwds = 1 << (b->k = *(int*)b);
2328 Bfree(b);
2329 }
2330
2331 /* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
2332 *
2333 * Inspired by "How to Print Floating-Point Numbers Accurately" by
2334 * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 112-126].
2335 *
2336 * Modifications:
2337 * 1. Rather than iterating, we use a simple numeric overestimate
2338 * to determine k = floor(log10(d)). We scale relevant
2339 * quantities using O(log2(k)) rather than O(k) multiplications.
2340 * 2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
2341 * try to generate digits strictly left to right. Instead, we
2342 * compute with fewer bits and propagate the carry if necessary
2343 * when rounding the final digit up. This is often faster.
2344 * 3. Under the assumption that input will be rounded nearest,
2345 * mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
2346 * That is, we allow equality in stopping tests when the
2347 * round-nearest rule will give the same floating-point value
2348 * as would satisfaction of the stopping test with strict
2349 * inequality.
2350 * 4. We remove common factors of powers of 2 from relevant
2351 * quantities.
2352 * 5. When converting floating-point integers less than 1e16,
2353 * we use floating-point arithmetic rather than resorting
2354 * to multiple-precision integers.
2355 * 6. When asked to produce fewer than 15 digits, we first try
2356 * to get by with floating-point arithmetic; we resort to
2357 * multiple-precision integer arithmetic only if we cannot
2358 * guarantee that the floating-point calculation has given
2359 * the correctly rounded result. For k requested digits and
2360 * "uniformly" distributed input, the probability is
2361 * something like 10^(k-15) that we must resort to the Long
2362 * calculation.
2363 */
2364
2365 /* Additional notes (METD): (1) returns NULL on failure. (2) to avoid memory
2366 leakage, a successful call to __Py_dg_dtoa should always be matched by a
2367 call to __Py_dg_freedtoa. */
2368
2369 static char *
2370 __Py_dg_dtoa(double dd, int mode, int ndigits,
2371 int *decpt, int *sign, char **rve)
2372 {
2373 /* Arguments ndigits, decpt, sign are similar to those
2374 of ecvt and fcvt; trailing zeros are suppressed from
2375 the returned string. If not null, *rve is set to point
2376 to the end of the return value. If d is +-Infinity or NaN,
2377 then *decpt is set to 9999.
2378
2379 mode:
2380 0 ==> shortest string that yields d when read in
2381 and rounded to nearest.
2382 1 ==> like 0, but with Steele & White stopping rule;
2383 e.g. with IEEE P754 arithmetic , mode 0 gives
2384 1e23 whereas mode 1 gives 9.999999999999999e22.
2385 2 ==> max(1,ndigits) significant digits. This gives a
2386 return value similar to that of ecvt, except
2387 that trailing zeros are suppressed.
2388 3 ==> through ndigits past the decimal point. This
2389 gives a return value similar to that from fcvt,
2390 except that trailing zeros are suppressed, and
2391 ndigits can be negative.
2392 4,5 ==> similar to 2 and 3, respectively, but (in
2393 round-nearest mode) with the tests of mode 0 to
2394 possibly return a shorter string that rounds to d.
2395 With IEEE arithmetic and compilation with
2396 -DHonor_FLT_ROUNDS, modes 4 and 5 behave the same
2397 as modes 2 and 3 when FLT_ROUNDS != 1.
2398 6-9 ==> Debugging modes similar to mode - 4: don't try
2399 fast floating-point estimate (if applicable).
2400
2401 Values of mode other than 0-9 are treated as mode 0.
2402
2403 Sufficient space is allocated to the return value
2404 to hold the suppressed trailing zeros.
2405 */
2406
2407 int bbits, b2, b5, be, dig, i, ieps, ilim, ilim0, ilim1,
2408 j, j1, k, k0, k_check, leftright, m2, m5, s2, s5,
2409 spec_case, try_quick;
2410 Long L;
2411 int denorm;
2412 ULong x;
2413 Bigint *b, *b1, *delta, *mlo, *mhi, *S;
2414 U d2, eps, u;
2415 double ds;
2416 char *s, *s0;
2417
2418 /* set pointers to NULL, to silence gcc compiler warnings and make
2419 cleanup easier on error */
2420 mlo = mhi = S = 0;
2421 s0 = 0;
2422
2423 u.d = dd;
2424 if (word0(&u) & Sign_bit) {
2425 /* set sign for everything, including 0's and NaNs */
2426 *sign = 1;
2427 word0(&u) &= ~Sign_bit; /* clear sign bit */
2428 }
2429 else
2430 *sign = 0;
2431
2432 /* quick return for Infinities, NaNs and zeros */
2433 if ((word0(&u) & Exp_mask) == Exp_mask)
2434 {
2435 /* Infinity or NaN */
2436 *decpt = 9999;
2437 if (!word1(&u) && !(word0(&u) & 0xfffff))
2438 return nrv_alloc("Infinity", rve, 8);
2439 return nrv_alloc("NaN", rve, 3);
2440 }
2441 if (!dval(&u)) {
2442 *decpt = 1;
2443 return nrv_alloc("0", rve, 1);
2444 }
2445
2446 /* compute k = floor(log10(d)). The computation may leave k
2447 one too large, but should never leave k too small. */
2448 b = d2b(&u, &be, &bbits);
2449 if (b == NULL)
2450 goto failed_malloc;
2451 if ((i = (int)(word0(&u) >> Exp_shift1 & (Exp_mask>>Exp_shift1)))) {
2452 dval(&d2) = dval(&u);
2453 word0(&d2) &= Frac_mask1;
2454 word0(&d2) |= Exp_11;
2455
2456 /* log(x) ~=~ log(1.5) + (x-1.5)/1.5
2457 * log10(x) = log(x) / log(10)
2458 * ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
2459 * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2)
2460 *
2461 * This suggests computing an approximation k to log10(d) by
2462 *
2463 * k = (i - Bias)*0.301029995663981
2464 * + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
2465 *
2466 * We want k to be too large rather than too small.
2467 * The error in the first-order Taylor series approximation
2468 * is in our favor, so we just round up the constant enough
2469 * to compensate for any error in the multiplication of
2470 * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
2471 * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
2472 * adding 1e-13 to the constant term more than suffices.
2473 * Hence we adjust the constant term to 0.1760912590558.
2474 * (We could get a more accurate k by invoking log10,
2475 * but this is probably not worthwhile.)
2476 */
2477
2478 i -= Bias;
2479 denorm = 0;
2480 }
2481 else {
2482 /* d is denormalized */
2483
2484 i = bbits + be + (Bias + (P-1) - 1);
2485 x = i > 32 ? word0(&u) << (64 - i) | word1(&u) >> (i - 32)
2486 : word1(&u) << (32 - i);
2487 dval(&d2) = x;
2488 word0(&d2) -= 31*Exp_msk1; /* adjust exponent */
2489 i -= (Bias + (P-1) - 1) + 1;
2490 denorm = 1;
2491 }
2492 ds = (dval(&d2)-1.5)*0.289529654602168 + 0.1760912590558 +
2493 i*0.301029995663981;
2494 k = (int)ds;
2495 if (ds < 0. && ds != k)
2496 k--; /* want k = floor(ds) */
2497 k_check = 1;
2498 if (k >= 0 && k <= Ten_pmax) {
2499 if (dval(&u) < tens[k])
2500 k--;
2501 k_check = 0;
2502 }
2503 j = bbits - i - 1;
2504 if (j >= 0) {
2505 b2 = 0;
2506 s2 = j;
2507 }
2508 else {
2509 b2 = -j;
2510 s2 = 0;
2511 }
2512 if (k >= 0) {
2513 b5 = 0;
2514 s5 = k;
2515 s2 += k;
2516 }
2517 else {
2518 b2 -= k;
2519 b5 = -k;
2520 s5 = 0;
2521 }
2522 if (mode < 0 || mode > 9)
2523 mode = 0;
2524
2525 try_quick = 1;
2526
2527 if (mode > 5) {
2528 mode -= 4;
2529 try_quick = 0;
2530 }
2531 leftright = 1;
2532 ilim = ilim1 = -1; /* Values for cases 0 and 1; done here to */
2533 /* silence erroneous "gcc -Wall" warning. */
2534 switch(mode) {
2535 case 0:
2536 case 1:
2537 i = 18;
2538 ndigits = 0;
2539 break;
2540 case 2:
2541 leftright = 0;
2542 /* no break */
2543 case 4:
2544 if (ndigits <= 0)
2545 ndigits = 1;
2546 ilim = ilim1 = i = ndigits;
2547 break;
2548 case 3:
2549 leftright = 0;
2550 /* no break */
2551 case 5:
2552 i = ndigits + k + 1;
2553 ilim = i;
2554 ilim1 = i - 1;
2555 if (i <= 0)
2556 i = 1;
2557 }
2558 s0 = rv_alloc(i);
2559 if (s0 == NULL)
2560 goto failed_malloc;
2561 s = s0;
2562
2563
2564 if (ilim >= 0 && ilim <= Quick_max && try_quick) {
2565
2566 /* Try to get by with floating-point arithmetic. */
2567
2568 i = 0;
2569 dval(&d2) = dval(&u);
2570 k0 = k;
2571 ilim0 = ilim;
2572 ieps = 2; /* conservative */
2573 if (k > 0) {
2574 ds = tens[k&0xf];
2575 j = k >> 4;
2576 if (j & Bletch) {
2577 /* prevent overflows */
2578 j &= Bletch - 1;
2579 dval(&u) /= bigtens[n_bigtens-1];
2580 ieps++;
2581 }
2582 for(; j; j >>= 1, i++)
2583 if (j & 1) {
2584 ieps++;
2585 ds *= bigtens[i];
2586 }
2587 dval(&u) /= ds;
2588 }
2589 else if ((j1 = -k)) {
2590 dval(&u) *= tens[j1 & 0xf];
2591 for(j = j1 >> 4; j; j >>= 1, i++)
2592 if (j & 1) {
2593 ieps++;
2594 dval(&u) *= bigtens[i];
2595 }
2596 }
2597 if (k_check && dval(&u) < 1. && ilim > 0) {
2598 if (ilim1 <= 0)
2599 goto fast_failed;
2600 ilim = ilim1;
2601 k--;
2602 dval(&u) *= 10.;
2603 ieps++;
2604 }
2605 dval(&eps) = ieps*dval(&u) + 7.;
2606 word0(&eps) -= (P-1)*Exp_msk1;
2607 if (ilim == 0) {
2608 S = mhi = 0;
2609 dval(&u) -= 5.;
2610 if (dval(&u) > dval(&eps))
2611 goto one_digit;
2612 if (dval(&u) < -dval(&eps))
2613 goto no_digits;
2614 goto fast_failed;
2615 }
2616 if (leftright) {
2617 /* Use Steele & White method of only
2618 * generating digits needed.
2619 */
2620 dval(&eps) = 0.5/tens[ilim-1] - dval(&eps);
2621 for(i = 0;;) {
2622 L = (Long)dval(&u);
2623 dval(&u) -= L;
2624 *s++ = '0' + (int)L;
2625 if (dval(&u) < dval(&eps))
2626 goto ret1;
2627 if (1. - dval(&u) < dval(&eps))
2628 goto bump_up;
2629 if (++i >= ilim)
2630 break;
2631 dval(&eps) *= 10.;
2632 dval(&u) *= 10.;
2633 }
2634 }
2635 else {
2636 /* Generate ilim digits, then fix them up. */
2637 dval(&eps) *= tens[ilim-1];
2638 for(i = 1;; i++, dval(&u) *= 10.) {
2639 L = (Long)(dval(&u));
2640 if (!(dval(&u) -= L))
2641 ilim = i;
2642 *s++ = '0' + (int)L;
2643 if (i == ilim) {
2644 if (dval(&u) > 0.5 + dval(&eps))
2645 goto bump_up;
2646 else if (dval(&u) < 0.5 - dval(&eps)) {
2647 while(*--s == '0');
2648 s++;
2649 goto ret1;
2650 }
2651 break;
2652 }
2653 }
2654 }
2655 fast_failed:
2656 s = s0;
2657 dval(&u) = dval(&d2);
2658 k = k0;
2659 ilim = ilim0;
2660 }
2661
2662 /* Do we have a "small" integer? */
2663
2664 if (be >= 0 && k <= Int_max) {
2665 /* Yes. */
2666 ds = tens[k];
2667 if (ndigits < 0 && ilim <= 0) {
2668 S = mhi = 0;
2669 if (ilim < 0 || dval(&u) <= 5*ds)
2670 goto no_digits;
2671 goto one_digit;
2672 }
2673 for(i = 1;; i++, dval(&u) *= 10.) {
2674 L = (Long)(dval(&u) / ds);
2675 dval(&u) -= L*ds;
2676 *s++ = '0' + (int)L;
2677 if (!dval(&u)) {
2678 break;
2679 }
2680 if (i == ilim) {
2681 dval(&u) += dval(&u);
2682 if (dval(&u) > ds || (dval(&u) == ds && L & 1)) {
2683 bump_up:
2684 while(*--s == '9')
2685 if (s == s0) {
2686 k++;
2687 *s = '0';
2688 break;
2689 }
2690 ++*s++;
2691 }
2692 else {
2693 /* Strip trailing zeros. This branch was missing from the
2694 original dtoa.c, leading to surplus trailing zeros in
2695 some cases. See bugs.python.org/issue40780. */
2696 while (s > s0 && s[-1] == '0') {
2697 --s;
2698 }
2699 }
2700 break;
2701 }
2702 }
2703 goto ret1;
2704 }
2705
2706 m2 = b2;
2707 m5 = b5;
2708 if (leftright) {
2709 i =
2710 denorm ? be + (Bias + (P-1) - 1 + 1) :
2711 1 + P - bbits;
2712 b2 += i;
2713 s2 += i;
2714 mhi = i2b(1);
2715 if (mhi == NULL)
2716 goto failed_malloc;
2717 }
2718 if (m2 > 0 && s2 > 0) {
2719 i = m2 < s2 ? m2 : s2;
2720 b2 -= i;
2721 m2 -= i;
2722 s2 -= i;
2723 }
2724 if (b5 > 0) {
2725 if (leftright) {
2726 if (m5 > 0) {
2727 mhi = pow5mult(mhi, m5);
2728 if (mhi == NULL)
2729 goto failed_malloc;
2730 b1 = mult(mhi, b);
2731 Bfree(b);
2732 b = b1;
2733 if (b == NULL)
2734 goto failed_malloc;
2735 }
2736 if ((j = b5 - m5)) {
2737 b = pow5mult(b, j);
2738 if (b == NULL)
2739 goto failed_malloc;
2740 }
2741 }
2742 else {
2743 b = pow5mult(b, b5);
2744 if (b == NULL)
2745 goto failed_malloc;
2746 }
2747 }
2748 S = i2b(1);
2749 if (S == NULL)
2750 goto failed_malloc;
2751 if (s5 > 0) {
2752 S = pow5mult(S, s5);
2753 if (S == NULL)
2754 goto failed_malloc;
2755 }
2756
2757 /* Check for special case that d is a normalized power of 2. */
2758
2759 spec_case = 0;
2760 if ((mode < 2 || leftright)
2761 ) {
2762 if (!word1(&u) && !(word0(&u) & Bndry_mask)
2763 && word0(&u) & (Exp_mask & ~Exp_msk1)
2764 ) {
2765 /* The special case */
2766 b2 += Log2P;
2767 s2 += Log2P;
2768 spec_case = 1;
2769 }
2770 }
2771
2772 /* Arrange for convenient computation of quotients:
2773 * shift left if necessary so divisor has 4 leading 0 bits.
2774 *
2775 * Perhaps we should just compute leading 28 bits of S once
2776 * and for all and pass them and a shift to quorem, so it
2777 * can do shifts and ors to compute the numerator for q.
2778 */
2779 #define iInc 28
2780 i = dshift(S, s2);
2781 b2 += i;
2782 m2 += i;
2783 s2 += i;
2784 if (b2 > 0) {
2785 b = lshift(b, b2);
2786 if (b == NULL)
2787 goto failed_malloc;
2788 }
2789 if (s2 > 0) {
2790 S = lshift(S, s2);
2791 if (S == NULL)
2792 goto failed_malloc;
2793 }
2794 if (k_check) {
2795 if (cmp(b,S) < 0) {
2796 k--;
2797 b = multadd(b, 10, 0); /* we botched the k estimate */
2798 if (b == NULL)
2799 goto failed_malloc;
2800 if (leftright) {
2801 mhi = multadd(mhi, 10, 0);
2802 if (mhi == NULL)
2803 goto failed_malloc;
2804 }
2805 ilim = ilim1;
2806 }
2807 }
2808 if (ilim <= 0 && (mode == 3 || mode == 5)) {
2809 if (ilim < 0) {
2810 /* no digits, fcvt style */
2811 no_digits:
2812 k = -1 - ndigits;
2813 goto ret;
2814 }
2815 else {
2816 S = multadd(S, 5, 0);
2817 if (S == NULL)
2818 goto failed_malloc;
2819 if (cmp(b, S) <= 0)
2820 goto no_digits;
2821 }
2822 one_digit:
2823 *s++ = '1';
2824 k++;
2825 goto ret;
2826 }
2827 if (leftright) {
2828 if (m2 > 0) {
2829 mhi = lshift(mhi, m2);
2830 if (mhi == NULL)
2831 goto failed_malloc;
2832 }
2833
2834 /* Compute mlo -- check for special case
2835 * that d is a normalized power of 2.
2836 */
2837
2838 mlo = mhi;
2839 if (spec_case) {
2840 mhi = Balloc(mhi->k);
2841 if (mhi == NULL)
2842 goto failed_malloc;
2843 Bcopy(mhi, mlo);
2844 mhi = lshift(mhi, Log2P);
2845 if (mhi == NULL)
2846 goto failed_malloc;
2847 }
2848
2849 for(i = 1;;i++) {
2850 dig = quorem(b,S) + '0';
2851 /* Do we yet have the shortest decimal string
2852 * that will round to d?
2853 */
2854 j = cmp(b, mlo);
2855 delta = diff(S, mhi);
2856 if (delta == NULL)
2857 goto failed_malloc;
2858 j1 = delta->sign ? 1 : cmp(b, delta);
2859 Bfree(delta);
2860 if (j1 == 0 && mode != 1 && !(word1(&u) & 1)
2861 ) {
2862 if (dig == '9')
2863 goto round_9_up;
2864 if (j > 0)
2865 dig++;
2866 *s++ = dig;
2867 goto ret;
2868 }
2869 if (j < 0 || (j == 0 && mode != 1
2870 && !(word1(&u) & 1)
2871 )) {
2872 if (!b->x[0] && b->wds <= 1) {
2873 goto accept_dig;
2874 }
2875 if (j1 > 0) {
2876 b = lshift(b, 1);
2877 if (b == NULL)
2878 goto failed_malloc;
2879 j1 = cmp(b, S);
2880 if ((j1 > 0 || (j1 == 0 && dig & 1))
2881 && dig++ == '9')
2882 goto round_9_up;
2883 }
2884 accept_dig:
2885 *s++ = dig;
2886 goto ret;
2887 }
2888 if (j1 > 0) {
2889 if (dig == '9') { /* possible if i == 1 */
2890 round_9_up:
2891 *s++ = '9';
2892 goto roundoff;
2893 }
2894 *s++ = dig + 1;
2895 goto ret;
2896 }
2897 *s++ = dig;
2898 if (i == ilim)
2899 break;
2900 b = multadd(b, 10, 0);
2901 if (b == NULL)
2902 goto failed_malloc;
2903 if (mlo == mhi) {
2904 mlo = mhi = multadd(mhi, 10, 0);
2905 if (mlo == NULL)
2906 goto failed_malloc;
2907 }
2908 else {
2909 mlo = multadd(mlo, 10, 0);
2910 if (mlo == NULL)
2911 goto failed_malloc;
2912 mhi = multadd(mhi, 10, 0);
2913 if (mhi == NULL)
2914 goto failed_malloc;
2915 }
2916 }
2917 }
2918 else
2919 for(i = 1;; i++) {
2920 *s++ = dig = quorem(b,S) + '0';
2921 if (!b->x[0] && b->wds <= 1) {
2922 goto ret;
2923 }
2924 if (i >= ilim)
2925 break;
2926 b = multadd(b, 10, 0);
2927 if (b == NULL)
2928 goto failed_malloc;
2929 }
2930
2931 /* Round off last digit */
2932
2933 b = lshift(b, 1);
2934 if (b == NULL)
2935 goto failed_malloc;
2936 j = cmp(b, S);
2937 if (j > 0 || (j == 0 && dig & 1)) {
2938 roundoff:
2939 while(*--s == '9')
2940 if (s == s0) {
2941 k++;
2942 *s++ = '1';
2943 goto ret;
2944 }
2945 ++*s++;
2946 }
2947 else {
2948 while(*--s == '0');
2949 s++;
2950 }
2951 ret:
2952 Bfree(S);
2953 if (mhi) {
2954 if (mlo && mlo != mhi)
2955 Bfree(mlo);
2956 Bfree(mhi);
2957 }
2958 ret1:
2959 Bfree(b);
2960 *s = 0;
2961 *decpt = k + 1;
2962 if (rve)
2963 *rve = s;
2964 return s0;
2965 failed_malloc:
2966 if (S)
2967 Bfree(S);
2968 if (mlo && mlo != mhi)
2969 Bfree(mlo);
2970 if (mhi)
2971 Bfree(mhi);
2972 if (b)
2973 Bfree(b);
2974 if (s0)
2975 __Py_dg_freedtoa(s0);
2976 return NULL;
2977 }
2978
2979
2980 /* Begin PYPY hacks */
2981 #ifndef _PyPy_SET_53BIT_PRECISION_HEADER
2982 # define _PyPy_SET_53BIT_PRECISION_HEADER /* nothing */
2983 #endif
2984 #ifndef _PyPy_SET_53BIT_PRECISION_START
2985 # define _PyPy_SET_53BIT_PRECISION_START /* nothing */
2986 #endif
2987 #ifndef _PyPy_SET_53BIT_PRECISION_END
2988 # define _PyPy_SET_53BIT_PRECISION_END /* nothing */
2989 #endif
2990 double _PyPy_dg_strtod(const char *s00, char **se)
2991 {
2992 double result;
2993 _PyPy_SET_53BIT_PRECISION_HEADER;
2994
2995 _PyPy_SET_53BIT_PRECISION_START;
2996 result = __Py_dg_strtod(s00, se);
2997 _PyPy_SET_53BIT_PRECISION_END;
2998 return result;
2999 }
3000
3001 char * _PyPy_dg_dtoa(double dd, int mode, int ndigits,
3002 int *decpt, int *sign, char **rve)
3003 {
3004 char* result;
3005 _PyPy_SET_53BIT_PRECISION_HEADER;
3006
3007 _PyPy_SET_53BIT_PRECISION_START;
3008 result = __Py_dg_dtoa(dd, mode, ndigits, decpt, sign, rve);
3009 _PyPy_SET_53BIT_PRECISION_END;
3010 return result;
3011 }
3012
3013 void _PyPy_dg_freedtoa(char *s)
3014 {
3015 __Py_dg_freedtoa(s);
3016 }
3017 /* End PYPY hacks */
3018
3019 #ifdef __cplusplus
3020 }
3021 #endif
3022
3023 #endif /* PY_NO_SHORT_FLOAT_REPR */