Coverage Report

Created: 2026-10-31 06:21

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