Coverage Report

Created: 2026-10-17 06:15

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
62
#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
4.62M
#define word0(x) (x)->L[1]
183
3.13M
#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
7.11M
#define dval(x) (x)->d
189
190
#ifndef STRTOD_DIGLIM
191
407k
#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
695k
#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
2.30M
#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
522k
#define Exp_shift  20
237
80.6k
#define Exp_shift1 20
238
2.78M
#define Exp_msk1    0x100000
239
#define Exp_msk11   0x100000
240
2.07M
#define Exp_mask  0x7ff00000
241
1.89M
#define P 53
242
#define Nbits 53
243
1.05M
#define Bias 1023
244
#define Emax 1023
245
#define Emin (-1022)
246
1.01M
#define Etiny (-1074)  /* smallest denormal is 2**Etiny */
247
572k
#define Exp_1  0x3ff00000
248
35.6k
#define Exp_11 0x3ff00000
249
1.77M
#define Ebits 11
250
496k
#define Frac_mask  0xfffff
251
38.0k
#define Frac_mask1 0xfffff
252
1.33M
#define Ten_pmax 22
253
65
#define Bletch 0x10
254
175k
#define Bndry_mask  0xfffff
255
9.27k
#define Bndry_mask1 0xfffff
256
55.3k
#define Sign_bit 0x80000000
257
10.3k
#define Log2P 1
258
#define Tiny0 0
259
441k
#define Tiny1 1
260
40.4k
#define Quick_max 14
261
24.1k
#define Int_max 14
262
263
#ifndef Flt_Rounds
264
#ifdef FLT_ROUNDS
265
733k
#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.80k
#define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
274
2.42k
#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
28.9M
#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
19.8M
#define freelist interp->dtoa.freelist
338
456
#define private_mem interp->dtoa.preallocated
339
1.24k
#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
4.96M
{
346
4.96M
    int x;
347
4.96M
    Bigint *rv;
348
4.96M
    unsigned int len;
349
4.96M
    PyInterpreterState *interp = _PyInterpreterState_GET();
350
351
4.96M
    if (k <= Bigint_Kmax && (rv = freelist[k]))
352
4.96M
        freelist[k] = rv->next;
353
456
    else {
354
456
        x = 1 << k;
355
456
        len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)
356
456
            /sizeof(double);
357
456
        if (k <= Bigint_Kmax &&
358
456
            pmem_next - private_mem + len <= (Py_ssize_t)Bigint_PREALLOC_SIZE
359
456
        ) {
360
394
            rv = (Bigint*)pmem_next;
361
394
            pmem_next += len;
362
394
        }
363
62
        else {
364
62
            rv = (Bigint*)MALLOC(len*sizeof(double));
365
62
            if (rv == NULL)
366
0
                return NULL;
367
62
        }
368
456
        rv->k = k;
369
456
        rv->maxwds = x;
370
456
    }
371
4.96M
    rv->sign = rv->wds = 0;
372
4.96M
    return rv;
373
4.96M
}
374
375
/* Free a Bigint allocated with Balloc */
376
377
static void
378
Bfree(Bigint *v)
379
6.90M
{
380
6.90M
    if (v) {
381
4.96M
        if (v->k > Bigint_Kmax)
382
0
            FREE((void*)v);
383
4.96M
        else {
384
4.96M
            PyInterpreterState *interp = _PyInterpreterState_GET();
385
4.96M
            v->next = freelist[v->k];
386
4.96M
            freelist[v->k] = v;
387
4.96M
        }
388
4.96M
    }
389
6.90M
}
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
444k
#define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign,   \
438
444k
                          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.04M
{
447
1.04M
    int i, wds;
448
1.04M
    ULong *x;
449
1.04M
    ULLong carry, y;
450
1.04M
    Bigint *b1;
451
452
1.04M
    wds = b->wds;
453
1.04M
    x = b->x;
454
1.04M
    i = 0;
455
1.04M
    carry = a;
456
3.67M
    do {
457
3.67M
        y = *x * (ULLong)m + carry;
458
3.67M
        carry = y >> 32;
459
3.67M
        *x++ = (ULong)(y & FFFFFFFF);
460
3.67M
    }
461
3.67M
    while(++i < wds);
462
1.04M
    if (carry) {
463
76.8k
        if (wds >= b->maxwds) {
464
1.98k
            b1 = Balloc(b->k+1);
465
1.98k
            if (b1 == NULL){
466
0
                Bfree(b);
467
0
                return NULL;
468
0
            }
469
1.98k
            Bcopy(b1, b);
470
1.98k
            Bfree(b);
471
1.98k
            b = b1;
472
1.98k
        }
473
76.8k
        b->x[wds++] = (ULong)carry;
474
76.8k
        b->wds = wds;
475
76.8k
    }
476
1.04M
    return b;
477
1.04M
}
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
407k
{
488
407k
    Bigint *b;
489
407k
    int i, k;
490
407k
    Long x, y;
491
492
407k
    x = (nd + 8) / 9;
493
471k
    for(k = 0, y = 1; x > y; y <<= 1, k++) ;
494
407k
    b = Balloc(k);
495
407k
    if (b == NULL)
496
0
        return NULL;
497
407k
    b->x[0] = y9;
498
407k
    b->wds = 1;
499
500
407k
    if (nd <= 9)
501
361k
      return b;
502
503
46.4k
    s += 9;
504
384k
    for (i = 9; i < nd0; i++) {
505
337k
        b = multadd(b, 10, *s++ - '0');
506
337k
        if (b == NULL)
507
0
            return NULL;
508
337k
    }
509
46.4k
    s++;
510
183k
    for(; i < nd; i++) {
511
136k
        b = multadd(b, 10, *s++ - '0');
512
136k
        if (b == NULL)
513
0
            return NULL;
514
136k
    }
515
46.4k
    return b;
516
46.4k
}
517
518
/* count leading 0 bits in the 32-bit integer x. */
519
520
static int
521
hi0bits(ULong x)
522
601k
{
523
601k
    int k = 0;
524
525
601k
    if (!(x & 0xffff0000)) {
526
215k
        k = 16;
527
215k
        x <<= 16;
528
215k
    }
529
601k
    if (!(x & 0xff000000)) {
530
226k
        k += 8;
531
226k
        x <<= 8;
532
226k
    }
533
601k
    if (!(x & 0xf0000000)) {
534
453k
        k += 4;
535
453k
        x <<= 4;
536
453k
    }
537
601k
    if (!(x & 0xc0000000)) {
538
267k
        k += 2;
539
267k
        x <<= 2;
540
267k
    }
541
601k
    if (!(x & 0x80000000)) {
542
128k
        k++;
543
128k
        if (!(x & 0x40000000))
544
0
            return 32;
545
128k
    }
546
601k
    return k;
547
601k
}
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
40.3k
{
555
40.3k
    int k;
556
40.3k
    ULong x = *y;
557
558
40.3k
    if (x & 7) {
559
25.7k
        if (x & 1)
560
11.2k
            return 0;
561
14.5k
        if (x & 2) {
562
7.31k
            *y = x >> 1;
563
7.31k
            return 1;
564
7.31k
        }
565
7.26k
        *y = x >> 2;
566
7.26k
        return 2;
567
14.5k
    }
568
14.5k
    k = 0;
569
14.5k
    if (!(x & 0xffff)) {
570
6.78k
        k = 16;
571
6.78k
        x >>= 16;
572
6.78k
    }
573
14.5k
    if (!(x & 0xff)) {
574
3.44k
        k += 8;
575
3.44k
        x >>= 8;
576
3.44k
    }
577
14.5k
    if (!(x & 0xf)) {
578
8.12k
        k += 4;
579
8.12k
        x >>= 4;
580
8.12k
    }
581
14.5k
    if (!(x & 0x3)) {
582
7.65k
        k += 2;
583
7.65k
        x >>= 2;
584
7.65k
    }
585
14.5k
    if (!(x & 1)) {
586
8.69k
        k++;
587
8.69k
        x >>= 1;
588
8.69k
        if (!x)
589
0
            return 32;
590
8.69k
    }
591
14.5k
    *y = x;
592
14.5k
    return k;
593
14.5k
}
594
595
/* convert a small nonnegative integer to a Bigint */
596
597
static Bigint *
598
i2b(int i)
599
519k
{
600
519k
    Bigint *b;
601
602
519k
    b = Balloc(1);
603
519k
    if (b == NULL)
604
0
        return NULL;
605
519k
    b->x[0] = i;
606
519k
    b->wds = 1;
607
519k
    return b;
608
519k
}
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
1.47M
{
616
1.47M
    Bigint *c;
617
1.47M
    int k, wa, wb, wc;
618
1.47M
    ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
619
1.47M
    ULong y;
620
1.47M
    ULLong carry, z;
621
622
1.47M
    if ((!a->x[0] && a->wds == 1) || (!b->x[0] && b->wds == 1)) {
623
5.91k
        c = Balloc(0);
624
5.91k
        if (c == NULL)
625
0
            return NULL;
626
5.91k
        c->wds = 1;
627
5.91k
        c->x[0] = 0;
628
5.91k
        return c;
629
5.91k
    }
630
631
1.46M
    if (a->wds < b->wds) {
632
797k
        c = a;
633
797k
        a = b;
634
797k
        b = c;
635
797k
    }
636
1.46M
    k = a->k;
637
1.46M
    wa = a->wds;
638
1.46M
    wb = b->wds;
639
1.46M
    wc = wa + wb;
640
1.46M
    if (wc > a->maxwds)
641
911k
        k++;
642
1.46M
    c = Balloc(k);
643
1.46M
    if (c == NULL)
644
0
        return NULL;
645
9.86M
    for(x = c->x, xa = x + wc; x < xa; x++)
646
8.39M
        *x = 0;
647
1.46M
    xa = a->x;
648
1.46M
    xae = xa + wa;
649
1.46M
    xb = b->x;
650
1.46M
    xbe = xb + wb;
651
1.46M
    xc0 = c->x;
652
4.27M
    for(; xb < xbe; xc0++) {
653
2.81M
        if ((y = *xb++)) {
654
2.80M
            x = xa;
655
2.80M
            xc = xc0;
656
2.80M
            carry = 0;
657
17.1M
            do {
658
17.1M
                z = *x++ * (ULLong)y + *xc + carry;
659
17.1M
                carry = z >> 32;
660
17.1M
                *xc++ = (ULong)(z & FFFFFFFF);
661
17.1M
            }
662
17.1M
            while(x < xae);
663
2.80M
            *xc = (ULong)carry;
664
2.80M
        }
665
2.81M
    }
666
2.46M
    for(xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ;
667
1.46M
    c->wds = wc;
668
1.46M
    return c;
669
1.46M
}
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
473k
{
680
473k
    Bigint *b1, *p5, **p5s;
681
473k
    int i;
682
473k
    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
473k
    assert(0 <= k && k < 1024);
690
691
473k
    if ((i = k & 3)) {
692
136k
        b = multadd(b, p05[i-1], 0);
693
136k
        if (b == NULL)
694
0
            return NULL;
695
136k
    }
696
697
473k
    if (!(k >>= 2))
698
13.1k
        return b;
699
460k
    PyInterpreterState *interp = _PyInterpreterState_GET();
700
460k
    p5s = interp->dtoa.p5s;
701
2.14M
    for(;;) {
702
2.14M
        assert(p5s != interp->dtoa.p5s + Bigint_Pow5size);
703
2.14M
        p5 = *p5s;
704
2.14M
        p5s++;
705
2.14M
        if (k & 1) {
706
1.38M
            b1 = mult(b, p5);
707
1.38M
            Bfree(b);
708
1.38M
            b = b1;
709
1.38M
            if (b == NULL)
710
0
                return NULL;
711
1.38M
        }
712
2.14M
        if (!(k >>= 1))
713
460k
            break;
714
2.14M
    }
715
460k
    return b;
716
460k
}
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.02M
{
777
1.02M
    int i, k1, n, n1;
778
1.02M
    Bigint *b1;
779
1.02M
    ULong *x, *x1, *xe, z;
780
781
1.02M
    if (!k || (!b->x[0] && b->wds == 1))
782
7.16k
        return b;
783
784
1.01M
    n = k >> 5;
785
1.01M
    k1 = b->k;
786
1.01M
    n1 = n + b->wds + 1;
787
2.71M
    for(i = b->maxwds; n1 > i; i <<= 1)
788
1.70M
        k1++;
789
1.01M
    b1 = Balloc(k1);
790
1.01M
    if (b1 == NULL) {
791
0
        Bfree(b);
792
0
        return NULL;
793
0
    }
794
1.01M
    x1 = b1->x;
795
5.37M
    for(i = 0; i < n; i++)
796
4.35M
        *x1++ = 0;
797
1.01M
    x = b->x;
798
1.01M
    xe = x + b->wds;
799
1.01M
    if (k &= 0x1f) {
800
1.00M
        k1 = 32 - k;
801
1.00M
        z = 0;
802
2.90M
        do {
803
2.90M
            *x1++ = *x << k | z;
804
2.90M
            z = *x++ >> k1;
805
2.90M
        }
806
2.90M
        while(x < xe);
807
1.00M
        if ((*x1 = z))
808
282k
            ++n1;
809
1.00M
    }
810
15.6k
    else do
811
28.9k
             *x1++ = *x++;
812
28.9k
        while(x < xe);
813
1.01M
    b1->wds = n1 - 1;
814
1.01M
    Bfree(b);
815
1.01M
    return b1;
816
1.01M
}
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
1.65M
{
824
1.65M
    ULong *xa, *xa0, *xb, *xb0;
825
1.65M
    int i, j;
826
827
1.65M
    i = a->wds;
828
1.65M
    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
1.65M
    if (i -= j)
836
184k
        return i;
837
1.47M
    xa0 = a->x;
838
1.47M
    xa = xa0 + j;
839
1.47M
    xb0 = b->x;
840
1.47M
    xb = xb0 + j;
841
2.23M
    for(;;) {
842
2.23M
        if (*--xa != *--xb)
843
1.44M
            return *xa < *xb ? -1 : 1;
844
788k
        if (xa <= xa0)
845
21.4k
            break;
846
788k
    }
847
21.4k
    return 0;
848
1.47M
}
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
565k
{
857
565k
    Bigint *c;
858
565k
    int i, wa, wb;
859
565k
    ULong *xa, *xae, *xb, *xbe, *xc;
860
565k
    ULLong borrow, y;
861
862
565k
    i = cmp(a,b);
863
565k
    if (!i) {
864
4.84k
        c = Balloc(0);
865
4.84k
        if (c == NULL)
866
0
            return NULL;
867
4.84k
        c->wds = 1;
868
4.84k
        c->x[0] = 0;
869
4.84k
        return c;
870
4.84k
    }
871
560k
    if (i < 0) {
872
83.9k
        c = a;
873
83.9k
        a = b;
874
83.9k
        b = c;
875
83.9k
        i = 1;
876
83.9k
    }
877
476k
    else
878
476k
        i = 0;
879
560k
    c = Balloc(a->k);
880
560k
    if (c == NULL)
881
0
        return NULL;
882
560k
    c->sign = i;
883
560k
    wa = a->wds;
884
560k
    xa = a->x;
885
560k
    xae = xa + wa;
886
560k
    wb = b->wds;
887
560k
    xb = b->x;
888
560k
    xbe = xb + wb;
889
560k
    xc = c->x;
890
560k
    borrow = 0;
891
4.10M
    do {
892
4.10M
        y = (ULLong)*xa++ - *xb++ - borrow;
893
4.10M
        borrow = y >> 32 & (ULong)1;
894
4.10M
        *xc++ = (ULong)(y & FFFFFFFF);
895
4.10M
    }
896
4.10M
    while(xb < xbe);
897
808k
    while(xa < xae) {
898
248k
        y = *xa++ - borrow;
899
248k
        borrow = y >> 32 & (ULong)1;
900
248k
        *xc++ = (ULong)(y & FFFFFFFF);
901
248k
    }
902
1.26M
    while(!*--xc)
903
705k
        wa--;
904
560k
    c->wds = wa;
905
560k
    return c;
906
560k
}
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
279k
{
914
279k
    Long L;
915
279k
    U u;
916
917
279k
    L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1;
918
279k
    word0(&u) = L;
919
279k
    word1(&u) = 0;
920
279k
    return dval(&u);
921
279k
}
922
923
/* Convert a Bigint to a double plus an exponent */
924
925
static double
926
b2d(Bigint *a, int *e)
927
549k
{
928
549k
    ULong *xa, *xa0, w, y, z;
929
549k
    int k;
930
549k
    U d;
931
932
549k
    xa0 = a->x;
933
549k
    xa = xa0 + a->wds;
934
549k
    y = *--xa;
935
#ifdef DEBUG
936
    if (!y) Bug("zero y in b2d");
937
#endif
938
549k
    k = hi0bits(y);
939
549k
    *e = 32 - k;
940
549k
    if (k < Ebits) {
941
337k
        word0(&d) = Exp_1 | y >> (Ebits - k);
942
337k
        w = xa > xa0 ? *--xa : 0;
943
337k
        word1(&d) = y << ((32-Ebits) + k) | w >> (Ebits - k);
944
337k
        goto ret_d;
945
337k
    }
946
212k
    z = xa > xa0 ? *--xa : 0;
947
212k
    if (k -= Ebits) {
948
206k
        word0(&d) = Exp_1 | y << k | z >> (32 - k);
949
206k
        y = xa > xa0 ? *--xa : 0;
950
206k
        word1(&d) = z << k | y >> (32 - k);
951
206k
    }
952
5.33k
    else {
953
5.33k
        word0(&d) = Exp_1 | y;
954
5.33k
        word1(&d) = z;
955
5.33k
    }
956
549k
  ret_d:
957
549k
    return dval(&d);
958
212k
}
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
456k
{
984
456k
    Bigint *b;
985
986
456k
    b = Balloc(1);
987
456k
    if (b == NULL)
988
0
        return NULL;
989
990
    /* First construct b and e assuming that scale == 0. */
991
456k
    b->wds = 2;
992
456k
    b->x[0] = word1(d);
993
456k
    b->x[1] = word0(d) & Frac_mask;
994
456k
    *e = Etiny - 1 + (int)((word0(d) & Exp_mask) >> Exp_shift);
995
456k
    if (*e < Etiny)
996
7.16k
        *e = Etiny;
997
448k
    else
998
448k
        b->x[1] |= Exp_msk1;
999
1000
    /* Now adjust for scale, provided that b != 0. */
1001
456k
    if (scale && (b->x[0] || b->x[1])) {
1002
36.0k
        *e -= scale;
1003
36.0k
        if (*e < Etiny) {
1004
29.4k
            scale = Etiny - *e;
1005
29.4k
            *e = Etiny;
1006
            /* We can't shift more than P-1 bits without shifting out a 1. */
1007
29.4k
            assert(0 < scale && scale <= P - 1);
1008
29.4k
            if (scale >= 32) {
1009
                /* The bits shifted out should all be zero. */
1010
17.7k
                assert(b->x[0] == 0);
1011
17.7k
                b->x[0] = b->x[1];
1012
17.7k
                b->x[1] = 0;
1013
17.7k
                scale -= 32;
1014
17.7k
            }
1015
29.4k
            if (scale) {
1016
                /* The bits shifted out should all be zero. */
1017
27.2k
                assert(b->x[0] << (32 - scale) == 0);
1018
27.2k
                b->x[0] = (b->x[0] >> scale) | (b->x[1] << (32 - scale));
1019
27.2k
                b->x[1] >>= scale;
1020
27.2k
            }
1021
29.4k
        }
1022
36.0k
    }
1023
    /* Ensure b is normalized. */
1024
456k
    if (!b->x[1])
1025
27.9k
        b->wds = 1;
1026
1027
456k
    return b;
1028
456k
}
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
40.3k
{
1042
40.3k
    Bigint *b;
1043
40.3k
    int de, k;
1044
40.3k
    ULong *x, y, z;
1045
40.3k
    int i;
1046
1047
40.3k
    b = Balloc(1);
1048
40.3k
    if (b == NULL)
1049
0
        return NULL;
1050
40.3k
    x = b->x;
1051
1052
40.3k
    z = word0(d) & Frac_mask;
1053
40.3k
    word0(d) &= 0x7fffffff;   /* clear sign bit, which we ignore */
1054
40.3k
    if ((de = (int)(word0(d) >> Exp_shift)))
1055
35.6k
        z |= Exp_msk1;
1056
40.3k
    if ((y = word1(d))) {
1057
30.5k
        if ((k = lo0bits(&y))) {
1058
19.9k
            x[0] = y | z << (32 - k);
1059
19.9k
            z >>= k;
1060
19.9k
        }
1061
10.5k
        else
1062
10.5k
            x[0] = y;
1063
30.5k
        i =
1064
30.5k
            b->wds = (x[1] = z) ? 2 : 1;
1065
30.5k
    }
1066
9.82k
    else {
1067
9.82k
        k = lo0bits(&z);
1068
9.82k
        x[0] = z;
1069
9.82k
        i =
1070
9.82k
            b->wds = 1;
1071
9.82k
        k += 32;
1072
9.82k
    }
1073
40.3k
    if (de) {
1074
35.6k
        *e = de - Bias - (P-1) + k;
1075
35.6k
        *bits = P - k;
1076
35.6k
    }
1077
4.67k
    else {
1078
4.67k
        *e = de - Bias - (P-1) + 1 + k;
1079
4.67k
        *bits = 32*i - hi0bits(x[i-1]);
1080
4.67k
    }
1081
40.3k
    return b;
1082
40.3k
}
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
274k
{
1090
274k
    U da, db;
1091
274k
    int k, ka, kb;
1092
1093
274k
    dval(&da) = b2d(a, &ka);
1094
274k
    dval(&db) = b2d(b, &kb);
1095
274k
    k = ka - kb + 32*(a->wds - b->wds);
1096
274k
    if (k > 0)
1097
40.7k
        word0(&da) += k*Exp_msk1;
1098
234k
    else {
1099
234k
        k = -k;
1100
234k
        word0(&db) += k*Exp_msk1;
1101
234k
    }
1102
274k
    return dval(&da) / dval(&db);
1103
274k
}
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
39.3k
#define Scale_Bit 0x10
1121
45.1k
#define n_bigtens 5
1122
1123
#define ULbits 32
1124
#define kshift 5
1125
46.7k
#define kmask 31
1126
1127
1128
static int
1129
dshift(Bigint *b, int p2)
1130
46.7k
{
1131
46.7k
    int rv = hi0bits(b->x[b->wds-1]) - 4;
1132
46.7k
    if (p2 > 0)
1133
25.7k
        rv -= p2;
1134
46.7k
    return rv & kmask;
1135
46.7k
}
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
364k
{
1144
364k
    int n;
1145
364k
    ULong *bx, *bxe, q, *sx, *sxe;
1146
364k
    ULLong borrow, carry, y, ys;
1147
1148
364k
    n = S->wds;
1149
#ifdef DEBUG
1150
    /*debug*/ if (b->wds > n)
1151
        /*debug*/       Bug("oversize b in quorem");
1152
#endif
1153
364k
    if (b->wds < n)
1154
9.26k
        return 0;
1155
355k
    sx = S->x;
1156
355k
    sxe = sx + --n;
1157
355k
    bx = b->x;
1158
355k
    bxe = bx + n;
1159
355k
    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
355k
    if (q) {
1165
261k
        borrow = 0;
1166
261k
        carry = 0;
1167
1.72M
        do {
1168
1.72M
            ys = *sx++ * (ULLong)q + carry;
1169
1.72M
            carry = ys >> 32;
1170
1.72M
            y = *bx - (ys & FFFFFFFF) - borrow;
1171
1.72M
            borrow = y >> 32 & (ULong)1;
1172
1.72M
            *bx++ = (ULong)(y & FFFFFFFF);
1173
1.72M
        }
1174
1.72M
        while(sx <= sxe);
1175
261k
        if (!*bxe) {
1176
1.81k
            bx = b->x;
1177
1.81k
            while(--bxe > bx && !*bxe)
1178
0
                --n;
1179
1.81k
            b->wds = n;
1180
1.81k
        }
1181
261k
    }
1182
355k
    if (cmp(b, S) >= 0) {
1183
21.2k
        q++;
1184
21.2k
        borrow = 0;
1185
21.2k
        carry = 0;
1186
21.2k
        bx = b->x;
1187
21.2k
        sx = S->x;
1188
138k
        do {
1189
138k
            ys = *sx++ + carry;
1190
138k
            carry = ys >> 32;
1191
138k
            y = *bx - (ys & FFFFFFFF) - borrow;
1192
138k
            borrow = y >> 32 & (ULong)1;
1193
138k
            *bx++ = (ULong)(y & FFFFFFFF);
1194
138k
        }
1195
138k
        while(sx <= sxe);
1196
21.2k
        bx = b->x;
1197
21.2k
        bxe = bx + n;
1198
21.2k
        if (!*bxe) {
1199
18.9k
            while(--bxe > bx && !*bxe)
1200
1.64k
                --n;
1201
17.2k
            b->wds = n;
1202
17.2k
        }
1203
21.2k
    }
1204
355k
    return q;
1205
364k
}
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.50k
{
1216
4.50k
    U u;
1217
1218
4.50k
    if (bc->scale && 2*P + 1 > (int)((word0(x) & Exp_mask) >> Exp_shift)) {
1219
        /* rv/2^bc->scale is subnormal */
1220
268
        word0(&u) = (P+2)*Exp_msk1;
1221
268
        word1(&u) = 0;
1222
268
        return u.d;
1223
268
    }
1224
4.23k
    else {
1225
4.23k
        assert(word0(x) || word1(x)); /* x != 0.0 */
1226
4.23k
        return ulp(x);
1227
4.23k
    }
1228
4.50k
}
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
14.9k
{
1279
14.9k
    Bigint *b, *d;
1280
14.9k
    int b2, d2, dd, i, nd, nd0, odd, p2, p5;
1281
1282
14.9k
    nd = bc->nd;
1283
14.9k
    nd0 = bc->nd0;
1284
14.9k
    p5 = nd + bc->e0;
1285
14.9k
    b = sd2b(rv, bc->scale, &p2);
1286
14.9k
    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
14.9k
    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
14.9k
    b = lshift(b, 1);
1296
14.9k
    if (b == NULL)
1297
0
        return -1;
1298
14.9k
    b->x[0] |= 1;
1299
14.9k
    p2--;
1300
1301
14.9k
    p2 -= p5;
1302
14.9k
    d = i2b(1);
1303
14.9k
    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
14.9k
    if (p5 > 0) {
1311
10.8k
        d = pow5mult(d, p5);
1312
10.8k
        if (d == NULL) {
1313
0
            Bfree(b);
1314
0
            return -1;
1315
0
        }
1316
10.8k
    }
1317
4.18k
    else if (p5 < 0) {
1318
3.47k
        b = pow5mult(b, -p5);
1319
3.47k
        if (b == NULL) {
1320
0
            Bfree(d);
1321
0
            return -1;
1322
0
        }
1323
3.47k
    }
1324
14.9k
    if (p2 > 0) {
1325
8.09k
        b2 = p2;
1326
8.09k
        d2 = 0;
1327
8.09k
    }
1328
6.89k
    else {
1329
6.89k
        b2 = 0;
1330
6.89k
        d2 = -p2;
1331
6.89k
    }
1332
14.9k
    i = dshift(d, d2);
1333
14.9k
    if ((b2 += i) > 0) {
1334
14.4k
        b = lshift(b, b2);
1335
14.4k
        if (b == NULL) {
1336
0
            Bfree(d);
1337
0
            return -1;
1338
0
        }
1339
14.4k
    }
1340
14.9k
    if ((d2 += i) > 0) {
1341
14.1k
        d = lshift(d, d2);
1342
14.1k
        if (d == NULL) {
1343
0
            Bfree(b);
1344
0
            return -1;
1345
0
        }
1346
14.1k
    }
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
14.9k
    if (cmp(b, d) >= 0)
1352
        /* b/d >= 1 */
1353
1.69k
        dd = -1;
1354
13.2k
    else {
1355
13.2k
        i = 0;
1356
240k
        for(;;) {
1357
240k
            b = multadd(b, 10, 0);
1358
240k
            if (b == NULL) {
1359
0
                Bfree(d);
1360
0
                return -1;
1361
0
            }
1362
240k
            dd = s0[i < nd0 ? i : i+1] - '0' - quorem(b, d);
1363
240k
            i++;
1364
1365
240k
            if (dd)
1366
11.6k
                break;
1367
228k
            if (!b->x[0] && b->wds == 1) {
1368
                /* b/d == 0 */
1369
1.24k
                dd = i < nd;
1370
1.24k
                break;
1371
1.24k
            }
1372
227k
            if (!(i < nd)) {
1373
                /* b/d != 0, but digits of s0 exhausted */
1374
435
                dd = -1;
1375
435
                break;
1376
435
            }
1377
227k
        }
1378
13.2k
    }
1379
14.9k
    Bfree(b);
1380
14.9k
    Bfree(d);
1381
14.9k
    if (dd > 0 || (dd == 0 && odd))
1382
2.46k
        dval(rv) += sulp(rv, bc);
1383
14.9k
    return 0;
1384
14.9k
}
1385
1386
1387
double
1388
_Py_dg_strtod(const char *s00, char **se)
1389
794k
{
1390
794k
    int bb2, bb5, bbe, bd2, bd5, bs2, c, dsign, e, e1, error;
1391
794k
    int esign, i, j, k, lz, nd, nd0, odd, sign;
1392
794k
    const char *s, *s0, *s1;
1393
794k
    double aadj, aadj1;
1394
794k
    U aadj2, adj, rv, rv0;
1395
794k
    ULong y, z, abs_exp;
1396
794k
    Long L;
1397
794k
    BCinfo bc;
1398
794k
    Bigint *bb = NULL, *bd = NULL, *bd0 = NULL, *bs = NULL, *delta = NULL;
1399
794k
    size_t ndigits, fraclen;
1400
794k
    double result;
1401
1402
794k
    dval(&rv) = 0.;
1403
1404
    /* Start parsing. */
1405
794k
    c = *(s = s00);
1406
1407
    /* Parse optional sign, if present. */
1408
794k
    sign = 0;
1409
794k
    switch (c) {
1410
236k
    case '-':
1411
236k
        sign = 1;
1412
236k
        _Py_FALLTHROUGH;
1413
236k
    case '+':
1414
236k
        c = *++s;
1415
794k
    }
1416
1417
    /* Skip leading zeros: lz is true iff there were leading zeros. */
1418
794k
    s1 = s;
1419
824k
    while (c == '0')
1420
29.9k
        c = *++s;
1421
794k
    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
794k
    s0 = s1 = s;
1428
7.47M
    while ('0' <= c && c <= '9')
1429
6.68M
        c = *++s;
1430
794k
    ndigits = s - s1;
1431
794k
    fraclen = 0;
1432
1433
    /* Parse decimal point and following digits. */
1434
794k
    if (c == '.') {
1435
73.7k
        c = *++s;
1436
73.7k
        if (!ndigits) {
1437
25.7k
            s1 = s;
1438
3.96M
            while (c == '0')
1439
3.93M
                c = *++s;
1440
25.7k
            lz = lz || s != s1;
1441
25.7k
            fraclen += (s - s1);
1442
25.7k
            s0 = s;
1443
25.7k
        }
1444
73.7k
        s1 = s;
1445
39.2M
        while ('0' <= c && c <= '9')
1446
39.1M
            c = *++s;
1447
73.7k
        ndigits += s - s1;
1448
73.7k
        fraclen += s - s1;
1449
73.7k
    }
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
794k
    if (!ndigits && !lz) {
1455
26.5k
        if (se)
1456
26.5k
            *se = (char *)s00;
1457
26.5k
        goto parse_error;
1458
26.5k
    }
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
768k
    if (ndigits > MAX_DIGITS || fraclen > MAX_DIGITS) {
1463
0
        if (se)
1464
0
            *se = (char *)s00;
1465
0
        goto parse_error;
1466
0
    }
1467
768k
    nd = (int)ndigits;
1468
768k
    nd0 = (int)ndigits - (int)fraclen;
1469
1470
    /* Parse exponent. */
1471
768k
    e = 0;
1472
768k
    if (c == 'e' || c == 'E') {
1473
695k
        s00 = s;
1474
695k
        c = *++s;
1475
1476
        /* Exponent sign. */
1477
695k
        esign = 0;
1478
695k
        switch (c) {
1479
40.5k
        case '-':
1480
40.5k
            esign = 1;
1481
40.5k
            _Py_FALLTHROUGH;
1482
53.5k
        case '+':
1483
53.5k
            c = *++s;
1484
695k
        }
1485
1486
        /* Skip zeros.  lz is true iff there are leading zeros. */
1487
695k
        s1 = s;
1488
1.45M
        while (c == '0')
1489
755k
            c = *++s;
1490
695k
        lz = s != s1;
1491
1492
        /* Get absolute value of the exponent. */
1493
695k
        s1 = s;
1494
695k
        abs_exp = 0;
1495
13.5M
        while ('0' <= c && c <= '9') {
1496
12.8M
            abs_exp = 10*abs_exp + (c - '0');
1497
12.8M
            c = *++s;
1498
12.8M
        }
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
695k
        if (s - s1 > 9 || abs_exp > MAX_ABS_EXP)
1504
8.90k
            e = (int)MAX_ABS_EXP;
1505
686k
        else
1506
686k
            e = (int)abs_exp;
1507
695k
        if (esign)
1508
40.5k
            e = -e;
1509
1510
        /* A valid exponent must have at least one digit. */
1511
695k
        if (s == s1 && !lz)
1512
8
            s = s00;
1513
695k
    }
1514
1515
    /* Adjust exponent to take into account position of the point. */
1516
768k
    e -= nd - nd0;
1517
768k
    if (nd0 <= 0)
1518
29.4k
        nd0 = nd;
1519
1520
    /* Finished parsing.  Set se to indicate how far we parsed */
1521
768k
    if (se)
1522
768k
        *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
768k
    if (!nd)
1527
9.11k
        goto ret;
1528
12.9M
    for (i = nd; i > 0; ) {
1529
12.9M
        --i;
1530
12.9M
        if (s0[i < nd0 ? i : i+1] != '0') {
1531
759k
            ++i;
1532
759k
            break;
1533
759k
        }
1534
12.9M
    }
1535
759k
    e += nd - i;
1536
759k
    nd = i;
1537
759k
    if (nd0 > nd)
1538
13.8k
        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
759k
    bc.e0 = e1 = e;
1577
759k
    y = z = 0;
1578
3.56M
    for (i = 0; i < nd; i++) {
1579
2.84M
        if (i < 9)
1580
2.41M
            y = 10*y + s0[i < nd0 ? i : i+1] - '0';
1581
434k
        else if (i < DBL_DIG+1)
1582
389k
            z = 10*z + s0[i < nd0 ? i : i+1] - '0';
1583
45.0k
        else
1584
45.0k
            break;
1585
2.84M
    }
1586
1587
759k
    k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;
1588
759k
    dval(&rv) = y;
1589
759k
    if (k > 9) {
1590
65.5k
        dval(&rv) = tens[k - 9] * dval(&rv) + z;
1591
65.5k
    }
1592
759k
    if (nd <= DBL_DIG
1593
707k
        && Flt_Rounds == 1
1594
759k
        ) {
1595
707k
        if (!e)
1596
11.5k
            goto ret;
1597
695k
        if (e > 0) {
1598
639k
            if (e <= Ten_pmax) {
1599
25.6k
                dval(&rv) *= tens[e];
1600
25.6k
                goto ret;
1601
25.6k
            }
1602
613k
            i = DBL_DIG - nd;
1603
613k
            if (e <= Ten_pmax + i) {
1604
                /* A fancier test would sometimes let us do
1605
                 * this for larger i values.
1606
                 */
1607
16.7k
                e -= i;
1608
16.7k
                dval(&rv) *= tens[i];
1609
16.7k
                dval(&rv) *= tens[e];
1610
16.7k
                goto ret;
1611
16.7k
            }
1612
613k
        }
1613
56.2k
        else if (e >= -Ten_pmax) {
1614
22.6k
            dval(&rv) /= tens[-e];
1615
22.6k
            goto ret;
1616
22.6k
        }
1617
695k
    }
1618
682k
    e1 += nd - k;
1619
1620
682k
    bc.scale = 0;
1621
1622
    /* Get starting approximation = rv * 10**e1 */
1623
1624
682k
    if (e1 > 0) {
1625
622k
        if ((i = e1 & 15))
1626
508k
            dval(&rv) *= tens[i];
1627
622k
        if (e1 &= ~15) {
1628
609k
            if (e1 > DBL_MAX_10_EXP)
1629
266k
                goto ovfl;
1630
342k
            e1 >>= 4;
1631
875k
            for(j = 0; e1 > 1; j++, e1 >>= 1)
1632
532k
                if (e1 & 1)
1633
285k
                    dval(&rv) *= bigtens[j];
1634
            /* The last multiplication could overflow. */
1635
342k
            word0(&rv) -= P*Exp_msk1;
1636
342k
            dval(&rv) *= bigtens[j];
1637
342k
            if ((z = word0(&rv) & Exp_mask)
1638
342k
                > Exp_msk1*(DBL_MAX_EXP+Bias-P))
1639
2.73k
                goto ovfl;
1640
340k
            if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) {
1641
                /* set to largest number */
1642
                /* (Can't trust DBL_MAX) */
1643
688
                word0(&rv) = Big0;
1644
688
                word1(&rv) = Big1;
1645
688
            }
1646
339k
            else
1647
339k
                word0(&rv) += P*Exp_msk1;
1648
340k
        }
1649
622k
    }
1650
59.8k
    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
56.0k
        e1 = -e1;
1662
56.0k
        if ((i = e1 & 15))
1663
44.5k
            dval(&rv) /= tens[i];
1664
56.0k
        if (e1 >>= 4) {
1665
45.1k
            if (e1 >= 1 << n_bigtens)
1666
5.71k
                goto undfl;
1667
39.3k
            if (e1 & Scale_Bit)
1668
22.3k
                bc.scale = 2*P;
1669
189k
            for(j = 0; e1 > 0; j++, e1 >>= 1)
1670
149k
                if (e1 & 1)
1671
87.9k
                    dval(&rv) *= tinytens[j];
1672
39.3k
            if (bc.scale && (j = 2*P + 1 - ((word0(&rv) & Exp_mask)
1673
22.3k
                                            >> Exp_shift)) > 0) {
1674
                /* scaled rv is denormal; clear j low bits */
1675
19.4k
                if (j >= 32) {
1676
13.1k
                    word1(&rv) = 0;
1677
13.1k
                    if (j >= 53)
1678
6.95k
                        word0(&rv) = (P+2)*Exp_msk1;
1679
6.18k
                    else
1680
6.18k
                        word0(&rv) &= 0xffffffff << (j-32);
1681
13.1k
                }
1682
6.33k
                else
1683
6.33k
                    word1(&rv) &= 0xffffffff << j;
1684
19.4k
            }
1685
39.3k
            if (!dval(&rv))
1686
0
                goto undfl;
1687
39.3k
        }
1688
56.0k
    }
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
407k
    bc.nd = nd;
1695
407k
    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
407k
    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
130k
        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
130k
            --i;
1710
130k
            if (s0[i < nd0 ? i : i+1] != '0') {
1711
20.9k
                ++i;
1712
20.9k
                break;
1713
20.9k
            }
1714
130k
        }
1715
20.9k
        e += nd - i;
1716
20.9k
        nd = i;
1717
20.9k
        if (nd0 > nd)
1718
15.9k
            nd0 = nd;
1719
20.9k
        if (nd < 9) { /* must recompute y */
1720
8.64k
            y = 0;
1721
55.4k
            for(i = 0; i < nd0; ++i)
1722
46.7k
                y = 10*y + s0[i] - '0';
1723
16.3k
            for(; i < nd; ++i)
1724
7.72k
                y = 10*y + s0[i+1] - '0';
1725
8.64k
        }
1726
20.9k
    }
1727
407k
    bd0 = s2b(s0, nd0, nd, y);
1728
407k
    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
441k
    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
441k
        bd = Balloc(bd0->k);
1760
441k
        if (bd == NULL) {
1761
0
            goto failed_malloc;
1762
0
        }
1763
441k
        Bcopy(bd, bd0);
1764
441k
        bb = sd2b(&rv, bc.scale, &bbe);   /* srv = bb * 2^bbe */
1765
441k
        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
441k
        odd = bb->x[0] & 1;
1771
1772
        /* tdv = bd * 10**e;  srv = bb * 2**bbe */
1773
441k
        bs = i2b(1);
1774
441k
        if (bs == NULL) {
1775
0
            goto failed_malloc;
1776
0
        }
1777
1778
441k
        if (e >= 0) {
1779
363k
            bb2 = bb5 = 0;
1780
363k
            bd2 = bd5 = e;
1781
363k
        }
1782
77.4k
        else {
1783
77.4k
            bb2 = bb5 = -e;
1784
77.4k
            bd2 = bd5 = 0;
1785
77.4k
        }
1786
441k
        if (bbe >= 0)
1787
367k
            bb2 += bbe;
1788
73.7k
        else
1789
73.7k
            bd2 -= bbe;
1790
441k
        bs2 = bb2;
1791
441k
        bb2++;
1792
441k
        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
441k
        i = bb2 < bd2 ? bb2 : bd2;
1813
441k
        if (i > bs2)
1814
72.9k
            i = bs2;
1815
441k
        if (i > 0) {
1816
439k
            bb2 -= i;
1817
439k
            bd2 -= i;
1818
439k
            bs2 -= i;
1819
439k
        }
1820
1821
        /* Scale bb, bd, bs by the appropriate powers of 2 and 5. */
1822
441k
        if (bb5 > 0) {
1823
77.4k
            bs = pow5mult(bs, bb5);
1824
77.4k
            if (bs == NULL) {
1825
0
                goto failed_malloc;
1826
0
            }
1827
77.4k
            Bigint *bb1 = mult(bs, bb);
1828
77.4k
            Bfree(bb);
1829
77.4k
            bb = bb1;
1830
77.4k
            if (bb == NULL) {
1831
0
                goto failed_malloc;
1832
0
            }
1833
77.4k
        }
1834
441k
        if (bb2 > 0) {
1835
441k
            bb = lshift(bb, bb2);
1836
441k
            if (bb == NULL) {
1837
0
                goto failed_malloc;
1838
0
            }
1839
441k
        }
1840
441k
        if (bd5 > 0) {
1841
352k
            bd = pow5mult(bd, bd5);
1842
352k
            if (bd == NULL) {
1843
0
                goto failed_malloc;
1844
0
            }
1845
352k
        }
1846
441k
        if (bd2 > 0) {
1847
72.9k
            bd = lshift(bd, bd2);
1848
72.9k
            if (bd == NULL) {
1849
0
                goto failed_malloc;
1850
0
            }
1851
72.9k
        }
1852
441k
        if (bs2 > 0) {
1853
364k
            bs = lshift(bs, bs2);
1854
364k
            if (bs == NULL) {
1855
0
                goto failed_malloc;
1856
0
            }
1857
364k
        }
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
441k
        delta = diff(bb, bd);
1864
441k
        if (delta == NULL) {
1865
0
            goto failed_malloc;
1866
0
        }
1867
441k
        dsign = delta->sign;
1868
441k
        delta->sign = 0;
1869
441k
        i = cmp(delta, bs);
1870
441k
        if (bc.nd > nd && i <= 0) {
1871
20.9k
            if (dsign)
1872
13.8k
                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
7.12k
            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
2.62k
                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
2.62k
                if (j - bc.scale >= 2) {
1892
1.17k
                    dval(&rv) -= 0.5 * sulp(&rv, &bc);
1893
1.17k
                    break; /* Use bigcomp. */
1894
1.17k
                }
1895
2.62k
            }
1896
1897
5.94k
            {
1898
5.94k
                bc.nd = nd;
1899
5.94k
                i = -1; /* Discarded digits make delta smaller. */
1900
5.94k
            }
1901
5.94k
        }
1902
1903
426k
        if (i < 0) {
1904
            /* Error is less than half an ulp -- check for
1905
             * special case of mantissa a power of two.
1906
             */
1907
146k
            if (dsign || word1(&rv) || word0(&rv) & Bndry_mask
1908
10.5k
                || (word0(&rv) & Exp_mask) <= (2*P+1)*Exp_msk1
1909
146k
                ) {
1910
138k
                break;
1911
138k
            }
1912
7.32k
            if (!delta->x[0] && delta->wds <= 1) {
1913
                /* exact result */
1914
1.19k
                break;
1915
1.19k
            }
1916
6.13k
            delta = lshift(delta,Log2P);
1917
6.13k
            if (delta == NULL) {
1918
0
                goto failed_malloc;
1919
0
            }
1920
6.13k
            if (cmp(delta, bs) > 0)
1921
2.07k
                goto drop_down;
1922
4.05k
            break;
1923
6.13k
        }
1924
279k
        if (i == 0) {
1925
            /* exactly half-way between */
1926
4.97k
            if (dsign) {
1927
2.39k
                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
558
                    word0(&rv) = (word0(&rv) & Exp_mask)
1935
558
                        + Exp_msk1
1936
558
                        ;
1937
558
                    word1(&rv) = 0;
1938
                    /* dsign = 0; */
1939
558
                    break;
1940
558
                }
1941
2.39k
            }
1942
2.58k
            else if (!(word0(&rv) & Bndry_mask) && !word1(&rv)) {
1943
2.07k
              drop_down:
1944
                /* boundary case -- decrement exponent */
1945
2.07k
                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
2.07k
                L = (word0(&rv) & Exp_mask) - Exp_msk1;
1959
2.07k
                word0(&rv) = L | Bndry_mask1;
1960
2.07k
                word1(&rv) = 0xffffffff;
1961
2.07k
                break;
1962
2.07k
            }
1963
4.42k
            if (!odd)
1964
3.56k
                break;
1965
861
            if (dsign)
1966
627
                dval(&rv) += sulp(&rv, &bc);
1967
234
            else {
1968
234
                dval(&rv) -= sulp(&rv, &bc);
1969
234
                if (!dval(&rv)) {
1970
0
                    if (bc.nd >nd)
1971
0
                        break;
1972
0
                    goto undfl;
1973
0
                }
1974
234
            }
1975
            /* dsign = 1 - dsign; */
1976
861
            break;
1977
861
        }
1978
274k
        if ((aadj = ratio(delta, bs)) <= 2.) {
1979
248k
            if (dsign)
1980
22.4k
                aadj = aadj1 = 1.;
1981
226k
            else if (word1(&rv) || word0(&rv) & Bndry_mask) {
1982
220k
                if (word1(&rv) == Tiny1 && !word0(&rv)) {
1983
0
                    if (bc.nd >nd)
1984
0
                        break;
1985
0
                    goto undfl;
1986
0
                }
1987
220k
                aadj = 1.;
1988
220k
                aadj1 = -1.;
1989
220k
            }
1990
5.91k
            else {
1991
                /* special case -- power of FLT_RADIX to be */
1992
                /* rounded down... */
1993
1994
5.91k
                if (aadj < 2./FLT_RADIX)
1995
0
                    aadj = 1./FLT_RADIX;
1996
5.91k
                else
1997
5.91k
                    aadj *= 0.5;
1998
5.91k
                aadj1 = -aadj;
1999
5.91k
            }
2000
248k
        }
2001
26.0k
        else {
2002
26.0k
            aadj *= 0.5;
2003
26.0k
            aadj1 = dsign ? aadj : -aadj;
2004
26.0k
            if (Flt_Rounds == 0)
2005
0
                aadj1 += 0.5;
2006
26.0k
        }
2007
274k
        y = word0(&rv) & Exp_mask;
2008
2009
        /* Check for overflow */
2010
2011
274k
        if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) {
2012
5.64k
            dval(&rv0) = dval(&rv);
2013
5.64k
            word0(&rv) -= P*Exp_msk1;
2014
5.64k
            adj.d = aadj1 * ulp(&rv);
2015
5.64k
            dval(&rv) += adj.d;
2016
5.64k
            if ((word0(&rv) & Exp_mask) >=
2017
5.64k
                Exp_msk1*(DBL_MAX_EXP+Bias-P)) {
2018
1.38k
                if (word0(&rv0) == Big0 && word1(&rv0) == Big1) {
2019
1.03k
                    goto ovfl;
2020
1.03k
                }
2021
348
                word0(&rv) = Big0;
2022
348
                word1(&rv) = Big1;
2023
348
                goto cont;
2024
1.38k
            }
2025
4.26k
            else
2026
4.26k
                word0(&rv) += P*Exp_msk1;
2027
5.64k
        }
2028
269k
        else {
2029
269k
            if (bc.scale && y <= 2*P*Exp_msk1) {
2030
16.0k
                if (aadj <= 0x7fffffff) {
2031
16.0k
                    if ((z = (ULong)aadj) <= 0)
2032
2.13k
                        z = 1;
2033
16.0k
                    aadj = z;
2034
16.0k
                    aadj1 = dsign ? aadj : -aadj;
2035
16.0k
                }
2036
16.0k
                dval(&aadj2) = aadj1;
2037
16.0k
                word0(&aadj2) += (2*P+1)*Exp_msk1 - y;
2038
16.0k
                aadj1 = dval(&aadj2);
2039
16.0k
            }
2040
269k
            adj.d = aadj1 * ulp(&rv);
2041
269k
            dval(&rv) += adj.d;
2042
269k
        }
2043
273k
        z = word0(&rv) & Exp_mask;
2044
273k
        if (bc.nd == nd) {
2045
260k
            if (!bc.scale)
2046
246k
                if (y == z) {
2047
                    /* Can we stop now? */
2048
242k
                    L = (Long)aadj;
2049
242k
                    aadj -= L;
2050
                    /* The tolerances below are conservative. */
2051
242k
                    if (dsign || word1(&rv) || word0(&rv) & Bndry_mask) {
2052
242k
                        if (aadj < .4999999 || aadj > .5000001)
2053
240k
                            break;
2054
242k
                    }
2055
93
                    else if (aadj < .4999999/FLT_RADIX)
2056
93
                        break;
2057
242k
                }
2058
260k
        }
2059
33.1k
      cont:
2060
33.1k
        Bfree(bb); bb = NULL;
2061
33.1k
        Bfree(bd); bd = NULL;
2062
33.1k
        Bfree(bs); bs = NULL;
2063
33.1k
        Bfree(delta); delta = NULL;
2064
33.1k
    }
2065
406k
    if (bc.nd > nd) {
2066
14.9k
        error = bigcomp(&rv, s0, &bc);
2067
14.9k
        if (error)
2068
0
            goto failed_malloc;
2069
14.9k
    }
2070
2071
406k
    if (bc.scale) {
2072
22.3k
        word0(&rv0) = Exp_1 - 2*P*Exp_msk1;
2073
22.3k
        word1(&rv0) = 0;
2074
22.3k
        dval(&rv) *= dval(&rv0);
2075
22.3k
    }
2076
2077
492k
  ret:
2078
492k
    result = sign ? -dval(&rv) : dval(&rv);
2079
492k
    goto done;
2080
2081
26.5k
  parse_error:
2082
26.5k
    result = 0.0;
2083
26.5k
    goto done;
2084
2085
0
  failed_malloc:
2086
0
    errno = ENOMEM;
2087
0
    result = -1.0;
2088
0
    goto done;
2089
2090
5.71k
  undfl:
2091
5.71k
    result = sign ? -0.0 : 0.0;
2092
5.71k
    goto done;
2093
2094
270k
  ovfl:
2095
270k
    errno = ERANGE;
2096
    /* Can't trust HUGE_VAL */
2097
270k
    word0(&rv) = Exp_mask;
2098
270k
    word1(&rv) = 0;
2099
270k
    result = sign ? -dval(&rv) : dval(&rv);
2100
270k
    goto done;
2101
2102
794k
  done:
2103
794k
    Bfree(bb);
2104
794k
    Bfree(bd);
2105
794k
    Bfree(bs);
2106
794k
    Bfree(bd0);
2107
794k
    Bfree(delta);
2108
794k
    return result;
2109
2110
406k
}
2111
2112
static char *
2113
rv_alloc(int i)
2114
44.5k
{
2115
44.5k
    int k, *r;
2116
44.5k
    size_t j;   /* size_t so that j <<= 1 cannot overflow for i near INT_MAX */
2117
2118
44.5k
    j = sizeof(ULong);
2119
44.5k
    for(k = 0;
2120
44.5k
        sizeof(Bigint) - sizeof(ULong) - sizeof(int) + j <= (unsigned)i;
2121
44.5k
        j <<= 1)
2122
0
        k++;
2123
44.5k
    r = (int*)Balloc(k);
2124
44.5k
    if (r == NULL)
2125
0
        return NULL;
2126
44.5k
    *r = k;
2127
44.5k
    return (char *)(r+1);
2128
44.5k
}
2129
2130
static char *
2131
nrv_alloc(const char *s, char **rve, int n)
2132
4.16k
{
2133
4.16k
    char *rv, *t;
2134
2135
4.16k
    rv = rv_alloc(n);
2136
4.16k
    if (rv == NULL)
2137
0
        return NULL;
2138
4.16k
    t = rv;
2139
13.1k
    while((*t = *s++)) t++;
2140
4.16k
    if (rve)
2141
4.16k
        *rve = t;
2142
4.16k
    return rv;
2143
4.16k
}
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
44.5k
{
2154
44.5k
    Bigint *b = (Bigint *)((int *)s - 1);
2155
44.5k
    b->maxwds = 1 << (b->k = *(int*)b);
2156
44.5k
    Bfree(b);
2157
44.5k
}
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
44.5k
{
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
44.5k
    int bbits, b2, b5, be, dig, i, ieps, ilim, ilim0, ilim1,
2236
44.5k
        j, j1, k, k0, k_check, leftright, m2, m5, s2, s5,
2237
44.5k
        spec_case, try_quick;
2238
44.5k
    Long L;
2239
44.5k
    int denorm;
2240
44.5k
    ULong x;
2241
44.5k
    Bigint *b, *b1, *delta, *mlo, *mhi, *S;
2242
44.5k
    U d2, eps, u;
2243
44.5k
    double ds;
2244
44.5k
    char *s, *s0;
2245
2246
    /* set pointers to NULL, to silence gcc compiler warnings and make
2247
       cleanup easier on error */
2248
44.5k
    mlo = mhi = S = 0;
2249
44.5k
    s0 = 0;
2250
2251
44.5k
    u.d = dd;
2252
44.5k
    if (word0(&u) & Sign_bit) {
2253
        /* set sign for everything, including 0's and NaNs */
2254
10.8k
        *sign = 1;
2255
10.8k
        word0(&u) &= ~Sign_bit; /* clear sign bit */
2256
10.8k
    }
2257
33.6k
    else
2258
33.6k
        *sign = 0;
2259
2260
    /* quick return for Infinities, NaNs and zeros */
2261
44.5k
    if ((word0(&u) & Exp_mask) == Exp_mask)
2262
688
    {
2263
        /* Infinity or NaN */
2264
688
        *decpt = 9999;
2265
688
        if (!word1(&u) && !(word0(&u) & 0xfffff))
2266
686
            return nrv_alloc("Infinity", rve, 8);
2267
2
        return nrv_alloc("NaN", rve, 3);
2268
688
    }
2269
43.8k
    if (!dval(&u)) {
2270
3.48k
        *decpt = 1;
2271
3.48k
        return nrv_alloc("0", rve, 1);
2272
3.48k
    }
2273
2274
    /* compute k = floor(log10(d)).  The computation may leave k
2275
       one too large, but should never leave k too small. */
2276
40.3k
    b = d2b(&u, &be, &bbits);
2277
40.3k
    if (b == NULL)
2278
0
        goto failed_malloc;
2279
40.3k
    if ((i = (int)(word0(&u) >> Exp_shift1 & (Exp_mask>>Exp_shift1)))) {
2280
35.6k
        dval(&d2) = dval(&u);
2281
35.6k
        word0(&d2) &= Frac_mask1;
2282
35.6k
        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
35.6k
        i -= Bias;
2307
35.6k
        denorm = 0;
2308
35.6k
    }
2309
4.67k
    else {
2310
        /* d is denormalized */
2311
2312
4.67k
        i = bbits + be + (Bias + (P-1) - 1);
2313
4.67k
        x = i > 32  ? word0(&u) << (64 - i) | word1(&u) >> (i - 32)
2314
4.67k
            : word1(&u) << (32 - i);
2315
4.67k
        dval(&d2) = x;
2316
4.67k
        word0(&d2) -= 31*Exp_msk1; /* adjust exponent */
2317
4.67k
        i -= (Bias + (P-1) - 1) + 1;
2318
4.67k
        denorm = 1;
2319
4.67k
    }
2320
40.3k
    ds = (dval(&d2)-1.5)*0.289529654602168 + 0.1760912590558 +
2321
40.3k
        i*0.301029995663981;
2322
40.3k
    k = (int)ds;
2323
40.3k
    if (ds < 0. && ds != k)
2324
11.8k
        k--;    /* want k = floor(ds) */
2325
40.3k
    k_check = 1;
2326
40.3k
    if (k >= 0 && k <= Ten_pmax) {
2327
16.3k
        if (dval(&u) < tens[k])
2328
1.89k
            k--;
2329
16.3k
        k_check = 0;
2330
16.3k
    }
2331
40.3k
    j = bbits - i - 1;
2332
40.3k
    if (j >= 0) {
2333
18.0k
        b2 = 0;
2334
18.0k
        s2 = j;
2335
18.0k
    }
2336
22.2k
    else {
2337
22.2k
        b2 = -j;
2338
22.2k
        s2 = 0;
2339
22.2k
    }
2340
40.3k
    if (k >= 0) {
2341
27.8k
        b5 = 0;
2342
27.8k
        s5 = k;
2343
27.8k
        s2 += k;
2344
27.8k
    }
2345
12.4k
    else {
2346
12.4k
        b2 -= k;
2347
12.4k
        b5 = -k;
2348
12.4k
        s5 = 0;
2349
12.4k
    }
2350
40.3k
    if (mode < 0 || mode > 9)
2351
0
        mode = 0;
2352
2353
40.3k
    try_quick = 1;
2354
2355
40.3k
    if (mode > 5) {
2356
0
        mode -= 4;
2357
0
        try_quick = 0;
2358
0
    }
2359
40.3k
    leftright = 1;
2360
40.3k
    ilim = ilim1 = -1;  /* Values for cases 0 and 1; done here to */
2361
    /* silence erroneous "gcc -Wall" warning. */
2362
40.3k
    switch(mode) {
2363
40.2k
    case 0:
2364
40.2k
    case 1:
2365
40.2k
        i = 18;
2366
40.2k
        ndigits = 0;
2367
40.2k
        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
90
    case 3:
2377
90
        leftright = 0;
2378
90
        _Py_FALLTHROUGH;
2379
90
    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
90
        if (ndigits > INT_MAX - 1024)
2386
0
            ndigits = INT_MAX - 1024;
2387
90
        else if (ndigits < -(INT_MAX - 1024))
2388
0
            ndigits = -(INT_MAX - 1024);
2389
90
        i = ndigits + k + 1;
2390
90
        ilim = i;
2391
90
        ilim1 = i - 1;
2392
90
        if (i <= 0)
2393
0
            i = 1;
2394
40.3k
    }
2395
40.3k
    s0 = rv_alloc(i);
2396
40.3k
    if (s0 == NULL)
2397
0
        goto failed_malloc;
2398
40.3k
    s = s0;
2399
2400
2401
40.3k
    if (ilim >= 0 && ilim <= Quick_max && try_quick) {
2402
2403
        /* Try to get by with floating-point arithmetic. */
2404
2405
90
        i = 0;
2406
90
        dval(&d2) = dval(&u);
2407
90
        k0 = k;
2408
90
        ilim0 = ilim;
2409
90
        ieps = 2; /* conservative */
2410
90
        if (k > 0) {
2411
65
            ds = tens[k&0xf];
2412
65
            j = k >> 4;
2413
65
            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
65
            for(; j; j >>= 1, i++)
2420
0
                if (j & 1) {
2421
0
                    ieps++;
2422
0
                    ds *= bigtens[i];
2423
0
                }
2424
65
            dval(&u) /= ds;
2425
65
        }
2426
25
        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
90
        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
90
        dval(&eps) = ieps*dval(&u) + 7.;
2443
90
        word0(&eps) -= (P-1)*Exp_msk1;
2444
90
        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
90
        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
90
        else {
2473
            /* Generate ilim digits, then fix them up. */
2474
90
            dval(&eps) *= tens[ilim-1];
2475
237
            for(i = 1;; i++, dval(&u) *= 10.) {
2476
237
                L = (Long)(dval(&u));
2477
237
                if (!(dval(&u) -= L))
2478
16
                    ilim = i;
2479
237
                *s++ = '0' + (int)L;
2480
237
                if (i == ilim) {
2481
90
                    if (dval(&u) > 0.5 + dval(&eps))
2482
41
                        goto bump_up;
2483
49
                    else if (dval(&u) < 0.5 - dval(&eps)) {
2484
54
                        while(*--s == '0');
2485
49
                        s++;
2486
49
                        goto ret1;
2487
49
                    }
2488
0
                    break;
2489
90
                }
2490
237
            }
2491
90
        }
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
40.2k
    if (be >= 0 && k <= Int_max) {
2502
        /* Yes. */
2503
8.54k
        ds = tens[k];
2504
8.54k
        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
11.5k
        for(i = 1;; i++, dval(&u) *= 10.) {
2511
11.5k
            L = (Long)(dval(&u) / ds);
2512
11.5k
            dval(&u) -= L*ds;
2513
11.5k
            *s++ = '0' + (int)L;
2514
11.5k
            if (!dval(&u)) {
2515
8.54k
                break;
2516
8.54k
            }
2517
2.99k
            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.99k
        }
2540
8.58k
        goto ret1;
2541
8.54k
    }
2542
2543
31.7k
    m2 = b2;
2544
31.7k
    m5 = b5;
2545
31.7k
    if (leftright) {
2546
31.7k
        i =
2547
31.7k
            denorm ? be + (Bias + (P-1) - 1 + 1) :
2548
31.7k
            1 + P - bbits;
2549
31.7k
        b2 += i;
2550
31.7k
        s2 += i;
2551
31.7k
        mhi = i2b(1);
2552
31.7k
        if (mhi == NULL)
2553
0
            goto failed_malloc;
2554
31.7k
    }
2555
31.7k
    if (m2 > 0 && s2 > 0) {
2556
28.0k
        i = m2 < s2 ? m2 : s2;
2557
28.0k
        b2 -= i;
2558
28.0k
        m2 -= i;
2559
28.0k
        s2 -= i;
2560
28.0k
    }
2561
31.7k
    if (b5 > 0) {
2562
12.4k
        if (leftright) {
2563
12.4k
            if (m5 > 0) {
2564
12.4k
                mhi = pow5mult(mhi, m5);
2565
12.4k
                if (mhi == NULL)
2566
0
                    goto failed_malloc;
2567
12.4k
                b1 = mult(mhi, b);
2568
12.4k
                Bfree(b);
2569
12.4k
                b = b1;
2570
12.4k
                if (b == NULL)
2571
0
                    goto failed_malloc;
2572
12.4k
            }
2573
12.4k
            if ((j = b5 - m5)) {
2574
0
                b = pow5mult(b, j);
2575
0
                if (b == NULL)
2576
0
                    goto failed_malloc;
2577
0
            }
2578
12.4k
        }
2579
0
        else {
2580
0
            b = pow5mult(b, b5);
2581
0
            if (b == NULL)
2582
0
                goto failed_malloc;
2583
0
        }
2584
12.4k
    }
2585
31.7k
    S = i2b(1);
2586
31.7k
    if (S == NULL)
2587
0
        goto failed_malloc;
2588
31.7k
    if (s5 > 0) {
2589
17.0k
        S = pow5mult(S, s5);
2590
17.0k
        if (S == NULL)
2591
0
            goto failed_malloc;
2592
17.0k
    }
2593
2594
    /* Check for special case that d is a normalized power of 2. */
2595
2596
31.7k
    spec_case = 0;
2597
31.7k
    if ((mode < 2 || leftright)
2598
31.7k
        ) {
2599
31.7k
        if (!word1(&u) && !(word0(&u) & Bndry_mask)
2600
1.65k
            && word0(&u) & (Exp_mask & ~Exp_msk1)
2601
31.7k
            ) {
2602
            /* The special case */
2603
1.39k
            b2 += Log2P;
2604
1.39k
            s2 += Log2P;
2605
1.39k
            spec_case = 1;
2606
1.39k
        }
2607
31.7k
    }
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
31.7k
#define iInc 28
2617
31.7k
    i = dshift(S, s2);
2618
31.7k
    b2 += i;
2619
31.7k
    m2 += i;
2620
31.7k
    s2 += i;
2621
31.7k
    if (b2 > 0) {
2622
31.7k
        b = lshift(b, b2);
2623
31.7k
        if (b == NULL)
2624
0
            goto failed_malloc;
2625
31.7k
    }
2626
31.7k
    if (s2 > 0) {
2627
30.9k
        S = lshift(S, s2);
2628
30.9k
        if (S == NULL)
2629
0
            goto failed_malloc;
2630
30.9k
    }
2631
31.7k
    if (k_check) {
2632
23.9k
        if (cmp(b,S) < 0) {
2633
4.33k
            k--;
2634
4.33k
            b = multadd(b, 10, 0);      /* we botched the k estimate */
2635
4.33k
            if (b == NULL)
2636
0
                goto failed_malloc;
2637
4.33k
            if (leftright) {
2638
4.33k
                mhi = multadd(mhi, 10, 0);
2639
4.33k
                if (mhi == NULL)
2640
0
                    goto failed_malloc;
2641
4.33k
            }
2642
4.33k
            ilim = ilim1;
2643
4.33k
        }
2644
23.9k
    }
2645
31.7k
    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
31.7k
    if (leftright) {
2665
31.7k
        if (m2 > 0) {
2666
29.9k
            mhi = lshift(mhi, m2);
2667
29.9k
            if (mhi == NULL)
2668
0
                goto failed_malloc;
2669
29.9k
        }
2670
2671
        /* Compute mlo -- check for special case
2672
         * that d is a normalized power of 2.
2673
         */
2674
2675
31.7k
        mlo = mhi;
2676
31.7k
        if (spec_case) {
2677
1.39k
            mhi = Balloc(mhi->k);
2678
1.39k
            if (mhi == NULL)
2679
0
                goto failed_malloc;
2680
1.39k
            Bcopy(mhi, mlo);
2681
1.39k
            mhi = lshift(mhi, Log2P);
2682
1.39k
            if (mhi == NULL)
2683
0
                goto failed_malloc;
2684
1.39k
        }
2685
2686
124k
        for(i = 1;;i++) {
2687
124k
            dig = quorem(b,S) + '0';
2688
            /* Do we yet have the shortest decimal string
2689
             * that will round to d?
2690
             */
2691
124k
            j = cmp(b, mlo);
2692
124k
            delta = diff(S, mhi);
2693
124k
            if (delta == NULL)
2694
0
                goto failed_malloc;
2695
124k
            j1 = delta->sign ? 1 : cmp(b, delta);
2696
124k
            Bfree(delta);
2697
124k
            if (j1 == 0 && mode != 1 && !(word1(&u) & 1)
2698
124k
                ) {
2699
2.08k
                if (dig == '9')
2700
396
                    goto round_9_up;
2701
1.68k
                if (j > 0)
2702
778
                    dig++;
2703
1.68k
                *s++ = dig;
2704
1.68k
                goto ret;
2705
2.08k
            }
2706
121k
            if (j < 0 || (j == 0 && mode != 1
2707
2.20k
                          && !(word1(&u) & 1)
2708
105k
                    )) {
2709
17.0k
                if (!b->x[0] && b->wds <= 1) {
2710
2.58k
                    goto accept_dig;
2711
2.58k
                }
2712
14.4k
                if (j1 > 0) {
2713
3.06k
                    b = lshift(b, 1);
2714
3.06k
                    if (b == NULL)
2715
0
                        goto failed_malloc;
2716
3.06k
                    j1 = cmp(b, S);
2717
3.06k
                    if ((j1 > 0 || (j1 == 0 && dig & 1))
2718
1.99k
                        && dig++ == '9')
2719
440
                        goto round_9_up;
2720
3.06k
                }
2721
16.5k
              accept_dig:
2722
16.5k
                *s++ = dig;
2723
16.5k
                goto ret;
2724
14.4k
            }
2725
104k
            if (j1 > 0) {
2726
12.6k
                if (dig == '9') { /* possible if i == 1 */
2727
4.27k
                  round_9_up:
2728
4.27k
                    *s++ = '9';
2729
4.27k
                    goto roundoff;
2730
3.44k
                }
2731
9.18k
                *s++ = dig + 1;
2732
9.18k
                goto ret;
2733
12.6k
            }
2734
92.3k
            *s++ = dig;
2735
92.3k
            if (i == ilim)
2736
0
                break;
2737
92.3k
            b = multadd(b, 10, 0);
2738
92.3k
            if (b == NULL)
2739
0
                goto failed_malloc;
2740
92.3k
            if (mlo == mhi) {
2741
87.6k
                mlo = mhi = multadd(mhi, 10, 0);
2742
87.6k
                if (mlo == NULL)
2743
0
                    goto failed_malloc;
2744
87.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
92.3k
        }
2754
31.7k
    }
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
4.27k
      roundoff:
2776
4.27k
        while(*--s == '9')
2777
4.27k
            if (s == s0) {
2778
4.27k
                k++;
2779
4.27k
                *s++ = '1';
2780
4.27k
                goto ret;
2781
4.27k
            }
2782
0
        ++*s++;
2783
0
    }
2784
0
    else {
2785
0
        while(*--s == '0');
2786
0
        s++;
2787
0
    }
2788
31.7k
  ret:
2789
31.7k
    Bfree(S);
2790
31.7k
    if (mhi) {
2791
31.7k
        if (mlo && mlo != mhi)
2792
1.39k
            Bfree(mlo);
2793
31.7k
        Bfree(mhi);
2794
31.7k
    }
2795
40.3k
  ret1:
2796
40.3k
    Bfree(b);
2797
40.3k
    *s = 0;
2798
40.3k
    *decpt = k + 1;
2799
40.3k
    if (rve)
2800
40.3k
        *rve = s;
2801
40.3k
    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
31.7k
}
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
}