Coverage Report

Created: 2026-12-01 06:09

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
71
#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.66M
#define word0(x) (x)->L[1]
183
3.15M
#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
6.98M
#define dval(x) (x)->d
189
190
#ifndef STRTOD_DIGLIM
191
417k
#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
649k
#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.20M
#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
540k
#define Exp_shift  20
237
83.5k
#define Exp_shift1 20
238
2.82M
#define Exp_msk1    0x100000
239
#define Exp_msk11   0x100000
240
2.06M
#define Exp_mask  0x7ff00000
241
1.92M
#define P 53
242
#define Nbits 53
243
1.07M
#define Bias 1023
244
#define Emax 1023
245
#define Emin (-1022)
246
1.04M
#define Etiny (-1074)  /* smallest denormal is 2**Etiny */
247
574k
#define Exp_1  0x3ff00000
248
37.1k
#define Exp_11 0x3ff00000
249
1.77M
#define Ebits 11
250
513k
#define Frac_mask  0xfffff
251
39.8k
#define Frac_mask1 0xfffff
252
1.25M
#define Ten_pmax 22
253
65
#define Bletch 0x10
254
187k
#define Bndry_mask  0xfffff
255
12.4k
#define Bndry_mask1 0xfffff
256
57.8k
#define Sign_bit 0x80000000
257
11.8k
#define Log2P 1
258
#define Tiny0 0
259
446k
#define Tiny1 1
260
41.8k
#define Quick_max 14
261
25.5k
#define Int_max 14
262
263
#ifndef Flt_Rounds
264
#ifdef FLT_ROUNDS
265
691k
#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
4.15k
#define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
274
2.64k
#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
30.1M
#define FFFFFFFF 0xffffffffUL
290
291
/* struct Bigint is used to represent arbitrary-precision integers.  These
292
   integers are stored in sign-magnitude format, with the magnitude stored as
293
   an array of base 2**32 digits.  Bigints are always normalized: if x is a
294
   Bigint then x->wds >= 1, and either x->wds == 1 or x[wds-1] is nonzero.
295
296
   The Bigint fields are as follows:
297
298
     - next is a header used by Balloc and Bfree to keep track of lists
299
         of freed Bigints;  it's also used for the linked list of
300
         powers of 5 of the form 5**2**i used by pow5mult.
301
     - k indicates which pool this Bigint was allocated from
302
     - maxwds is the maximum number of words space was allocated for
303
       (usually maxwds == 2**k)
304
     - sign is 1 for negative Bigints, 0 for positive.  The sign is unused
305
       (ignored on inputs, set to 0 on outputs) in almost all operations
306
       involving Bigints: a notable exception is the diff function, which
307
       ignores signs on inputs but sets the sign of the output correctly.
308
     - wds is the actual number of significant words
309
     - x contains the vector of words (digits) for this Bigint, from least
310
       significant (x[0]) to most significant (x[wds-1]).
311
*/
312
313
// struct Bigint is defined in pycore_dtoa.h.
314
typedef struct Bigint Bigint;
315
316
#if !defined(Py_GIL_DISABLED) && !defined(Py_USING_MEMORY_DEBUGGER)
317
318
/* Memory management: memory is allocated from, and returned to, Kmax+1 pools
319
   of memory, where pool k (0 <= k <= Kmax) is for Bigints b with b->maxwds ==
320
   1 << k.  These pools are maintained as linked lists, with freelist[k]
321
   pointing to the head of the list for pool k.
322
323
   On allocation, if there's no free slot in the appropriate pool, MALLOC is
324
   called to get more memory.  This memory is not returned to the system until
325
   Python quits.  There's also a private memory pool that's allocated from
326
   in preference to using MALLOC.
327
328
   For Bigints with more than (1 << Kmax) digits (which implies at least 1233
329
   decimal digits), memory is directly allocated using MALLOC, and freed using
330
   FREE.
331
332
   XXX: it would be easy to bypass this memory-management system and
333
   translate each call to Balloc into a call to PyMem_Malloc, and each
334
   Bfree to PyMem_Free.  Investigate whether this has any significant
335
   performance on impact. */
336
337
20.5M
#define freelist interp->dtoa.freelist
338
463
#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
5.13M
{
346
5.13M
    int x;
347
5.13M
    Bigint *rv;
348
5.13M
    unsigned int len;
349
5.13M
    PyInterpreterState *interp = _PyInterpreterState_GET();
350
351
5.13M
    if (k <= Bigint_Kmax && (rv = freelist[k]))
352
5.13M
        freelist[k] = rv->next;
353
463
    else {
354
463
        x = 1 << k;
355
463
        len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)
356
463
            /sizeof(double);
357
463
        if (k <= Bigint_Kmax &&
358
463
            pmem_next - private_mem + len <= (Py_ssize_t)Bigint_PREALLOC_SIZE
359
463
        ) {
360
392
            rv = (Bigint*)pmem_next;
361
392
            pmem_next += len;
362
392
        }
363
71
        else {
364
71
            rv = (Bigint*)MALLOC(len*sizeof(double));
365
71
            if (rv == NULL)
366
0
                return NULL;
367
71
        }
368
463
        rv->k = k;
369
463
        rv->maxwds = x;
370
463
    }
371
5.13M
    rv->sign = rv->wds = 0;
372
5.13M
    return rv;
373
5.13M
}
374
375
/* Free a Bigint allocated with Balloc */
376
377
static void
378
Bfree(Bigint *v)
379
6.89M
{
380
6.89M
    if (v) {
381
5.13M
        if (v->k > Bigint_Kmax)
382
0
            FREE((void*)v);
383
5.13M
        else {
384
5.13M
            PyInterpreterState *interp = _PyInterpreterState_GET();
385
5.13M
            v->next = freelist[v->k];
386
5.13M
            freelist[v->k] = v;
387
5.13M
        }
388
5.13M
    }
389
6.89M
}
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
457k
#define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign,   \
438
457k
                          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.17M
{
447
1.17M
    int i, wds;
448
1.17M
    ULong *x;
449
1.17M
    ULLong carry, y;
450
1.17M
    Bigint *b1;
451
452
1.17M
    wds = b->wds;
453
1.17M
    x = b->x;
454
1.17M
    i = 0;
455
1.17M
    carry = a;
456
4.38M
    do {
457
4.38M
        y = *x * (ULLong)m + carry;
458
4.38M
        carry = y >> 32;
459
4.38M
        *x++ = (ULong)(y & FFFFFFFF);
460
4.38M
    }
461
4.38M
    while(++i < wds);
462
1.17M
    if (carry) {
463
84.6k
        if (wds >= b->maxwds) {
464
2.36k
            b1 = Balloc(b->k+1);
465
2.36k
            if (b1 == NULL){
466
0
                Bfree(b);
467
0
                return NULL;
468
0
            }
469
2.36k
            Bcopy(b1, b);
470
2.36k
            Bfree(b);
471
2.36k
            b = b1;
472
2.36k
        }
473
84.6k
        b->x[wds++] = (ULong)carry;
474
84.6k
        b->wds = wds;
475
84.6k
    }
476
1.17M
    return b;
477
1.17M
}
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
417k
{
488
417k
    Bigint *b;
489
417k
    int i, k;
490
417k
    Long x, y;
491
492
417k
    x = (nd + 8) / 9;
493
487k
    for(k = 0, y = 1; x > y; y <<= 1, k++) ;
494
417k
    b = Balloc(k);
495
417k
    if (b == NULL)
496
0
        return NULL;
497
417k
    b->x[0] = y9;
498
417k
    b->wds = 1;
499
500
417k
    if (nd <= 9)
501
365k
      return b;
502
503
51.5k
    s += 9;
504
451k
    for (i = 9; i < nd0; i++) {
505
399k
        b = multadd(b, 10, *s++ - '0');
506
399k
        if (b == NULL)
507
0
            return NULL;
508
399k
    }
509
51.5k
    s++;
510
177k
    for(; i < nd; i++) {
511
126k
        b = multadd(b, 10, *s++ - '0');
512
126k
        if (b == NULL)
513
0
            return NULL;
514
126k
    }
515
51.5k
    return b;
516
51.5k
}
517
518
/* count leading 0 bits in the 32-bit integer x. */
519
520
static int
521
hi0bits(ULong x)
522
609k
{
523
609k
    int k = 0;
524
525
609k
    if (!(x & 0xffff0000)) {
526
221k
        k = 16;
527
221k
        x <<= 16;
528
221k
    }
529
609k
    if (!(x & 0xff000000)) {
530
228k
        k += 8;
531
228k
        x <<= 8;
532
228k
    }
533
609k
    if (!(x & 0xf0000000)) {
534
464k
        k += 4;
535
464k
        x <<= 4;
536
464k
    }
537
609k
    if (!(x & 0xc0000000)) {
538
267k
        k += 2;
539
267k
        x <<= 2;
540
267k
    }
541
609k
    if (!(x & 0x80000000)) {
542
132k
        k++;
543
132k
        if (!(x & 0x40000000))
544
0
            return 32;
545
132k
    }
546
609k
    return k;
547
609k
}
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
41.7k
{
555
41.7k
    int k;
556
41.7k
    ULong x = *y;
557
558
41.7k
    if (x & 7) {
559
28.2k
        if (x & 1)
560
11.6k
            return 0;
561
16.6k
        if (x & 2) {
562
7.65k
            *y = x >> 1;
563
7.65k
            return 1;
564
7.65k
        }
565
8.98k
        *y = x >> 2;
566
8.98k
        return 2;
567
16.6k
    }
568
13.5k
    k = 0;
569
13.5k
    if (!(x & 0xffff)) {
570
6.95k
        k = 16;
571
6.95k
        x >>= 16;
572
6.95k
    }
573
13.5k
    if (!(x & 0xff)) {
574
3.12k
        k += 8;
575
3.12k
        x >>= 8;
576
3.12k
    }
577
13.5k
    if (!(x & 0xf)) {
578
7.21k
        k += 4;
579
7.21k
        x >>= 4;
580
7.21k
    }
581
13.5k
    if (!(x & 0x3)) {
582
7.00k
        k += 2;
583
7.00k
        x >>= 2;
584
7.00k
    }
585
13.5k
    if (!(x & 1)) {
586
7.84k
        k++;
587
7.84k
        x >>= 1;
588
7.84k
        if (!x)
589
0
            return 32;
590
7.84k
    }
591
13.5k
    *y = x;
592
13.5k
    return k;
593
13.5k
}
594
595
/* convert a small nonnegative integer to a Bigint */
596
597
static Bigint *
598
i2b(int i)
599
539k
{
600
539k
    Bigint *b;
601
602
539k
    b = Balloc(1);
603
539k
    if (b == NULL)
604
0
        return NULL;
605
539k
    b->x[0] = i;
606
539k
    b->wds = 1;
607
539k
    return b;
608
539k
}
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.51M
{
616
1.51M
    Bigint *c;
617
1.51M
    int k, wa, wb, wc;
618
1.51M
    ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
619
1.51M
    ULong y;
620
1.51M
    ULLong carry, z;
621
622
1.51M
    if ((!a->x[0] && a->wds == 1) || (!b->x[0] && b->wds == 1)) {
623
5.43k
        c = Balloc(0);
624
5.43k
        if (c == NULL)
625
0
            return NULL;
626
5.43k
        c->wds = 1;
627
5.43k
        c->x[0] = 0;
628
5.43k
        return c;
629
5.43k
    }
630
631
1.51M
    if (a->wds < b->wds) {
632
821k
        c = a;
633
821k
        a = b;
634
821k
        b = c;
635
821k
    }
636
1.51M
    k = a->k;
637
1.51M
    wa = a->wds;
638
1.51M
    wb = b->wds;
639
1.51M
    wc = wa + wb;
640
1.51M
    if (wc > a->maxwds)
641
936k
        k++;
642
1.51M
    c = Balloc(k);
643
1.51M
    if (c == NULL)
644
0
        return NULL;
645
10.0M
    for(x = c->x, xa = x + wc; x < xa; x++)
646
8.58M
        *x = 0;
647
1.51M
    xa = a->x;
648
1.51M
    xae = xa + wa;
649
1.51M
    xb = b->x;
650
1.51M
    xbe = xb + wb;
651
1.51M
    xc0 = c->x;
652
4.37M
    for(; xb < xbe; xc0++) {
653
2.86M
        if ((y = *xb++)) {
654
2.85M
            x = xa;
655
2.85M
            xc = xc0;
656
2.85M
            carry = 0;
657
17.2M
            do {
658
17.2M
                z = *x++ * (ULLong)y + *xc + carry;
659
17.2M
                carry = z >> 32;
660
17.2M
                *xc++ = (ULong)(z & FFFFFFFF);
661
17.2M
            }
662
17.2M
            while(x < xae);
663
2.85M
            *xc = (ULong)carry;
664
2.85M
        }
665
2.86M
    }
666
2.53M
    for(xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ;
667
1.51M
    c->wds = wc;
668
1.51M
    return c;
669
1.51M
}
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
489k
{
680
489k
    Bigint *b1, *p5, **p5s;
681
489k
    int i;
682
489k
    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
489k
    assert(0 <= k && k < 1024);
690
691
489k
    if ((i = k & 3)) {
692
155k
        b = multadd(b, p05[i-1], 0);
693
155k
        if (b == NULL)
694
0
            return NULL;
695
155k
    }
696
697
489k
    if (!(k >>= 2))
698
14.5k
        return b;
699
475k
    PyInterpreterState *interp = _PyInterpreterState_GET();
700
475k
    p5s = interp->dtoa.p5s;
701
2.20M
    for(;;) {
702
2.20M
        assert(p5s != interp->dtoa.p5s + Bigint_Pow5size);
703
2.20M
        p5 = *p5s;
704
2.20M
        p5s++;
705
2.20M
        if (k & 1) {
706
1.42M
            b1 = mult(b, p5);
707
1.42M
            Bfree(b);
708
1.42M
            b = b1;
709
1.42M
            if (b == NULL)
710
0
                return NULL;
711
1.42M
        }
712
2.20M
        if (!(k >>= 1))
713
475k
            break;
714
2.20M
    }
715
475k
    return b;
716
475k
}
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.06M
{
777
1.06M
    int i, k1, n, n1;
778
1.06M
    Bigint *b1;
779
1.06M
    ULong *x, *x1, *xe, z;
780
781
1.06M
    if (!k || (!b->x[0] && b->wds == 1))
782
6.90k
        return b;
783
784
1.05M
    n = k >> 5;
785
1.05M
    k1 = b->k;
786
1.05M
    n1 = n + b->wds + 1;
787
2.80M
    for(i = b->maxwds; n1 > i; i <<= 1)
788
1.74M
        k1++;
789
1.05M
    b1 = Balloc(k1);
790
1.05M
    if (b1 == NULL) {
791
0
        Bfree(b);
792
0
        return NULL;
793
0
    }
794
1.05M
    x1 = b1->x;
795
5.49M
    for(i = 0; i < n; i++)
796
4.43M
        *x1++ = 0;
797
1.05M
    x = b->x;
798
1.05M
    xe = x + b->wds;
799
1.05M
    if (k &= 0x1f) {
800
1.04M
        k1 = 32 - k;
801
1.04M
        z = 0;
802
3.05M
        do {
803
3.05M
            *x1++ = *x << k | z;
804
3.05M
            z = *x++ >> k1;
805
3.05M
        }
806
3.05M
        while(x < xe);
807
1.04M
        if ((*x1 = z))
808
296k
            ++n1;
809
1.04M
    }
810
15.0k
    else do
811
28.3k
             *x1++ = *x++;
812
28.3k
        while(x < xe);
813
1.05M
    b1->wds = n1 - 1;
814
1.05M
    Bfree(b);
815
1.05M
    return b1;
816
1.05M
}
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.73M
{
824
1.73M
    ULong *xa, *xa0, *xb, *xb0;
825
1.73M
    int i, j;
826
827
1.73M
    i = a->wds;
828
1.73M
    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.73M
    if (i -= j)
836
190k
        return i;
837
1.54M
    xa0 = a->x;
838
1.54M
    xa = xa0 + j;
839
1.54M
    xb0 = b->x;
840
1.54M
    xb = xb0 + j;
841
2.34M
    for(;;) {
842
2.34M
        if (*--xa != *--xb)
843
1.52M
            return *xa < *xb ? -1 : 1;
844
819k
        if (xa <= xa0)
845
21.0k
            break;
846
819k
    }
847
21.0k
    return 0;
848
1.54M
}
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
581k
{
857
581k
    Bigint *c;
858
581k
    int i, wa, wb;
859
581k
    ULong *xa, *xae, *xb, *xbe, *xc;
860
581k
    ULLong borrow, y;
861
862
581k
    i = cmp(a,b);
863
581k
    if (!i) {
864
4.56k
        c = Balloc(0);
865
4.56k
        if (c == NULL)
866
0
            return NULL;
867
4.56k
        c->wds = 1;
868
4.56k
        c->x[0] = 0;
869
4.56k
        return c;
870
4.56k
    }
871
577k
    if (i < 0) {
872
89.7k
        c = a;
873
89.7k
        a = b;
874
89.7k
        b = c;
875
89.7k
        i = 1;
876
89.7k
    }
877
487k
    else
878
487k
        i = 0;
879
577k
    c = Balloc(a->k);
880
577k
    if (c == NULL)
881
0
        return NULL;
882
577k
    c->sign = i;
883
577k
    wa = a->wds;
884
577k
    xa = a->x;
885
577k
    xae = xa + wa;
886
577k
    wb = b->wds;
887
577k
    xb = b->x;
888
577k
    xbe = xb + wb;
889
577k
    xc = c->x;
890
577k
    borrow = 0;
891
4.20M
    do {
892
4.20M
        y = (ULLong)*xa++ - *xb++ - borrow;
893
4.20M
        borrow = y >> 32 & (ULong)1;
894
4.20M
        *xc++ = (ULong)(y & FFFFFFFF);
895
4.20M
    }
896
4.20M
    while(xb < xbe);
897
815k
    while(xa < xae) {
898
238k
        y = *xa++ - borrow;
899
238k
        borrow = y >> 32 & (ULong)1;
900
238k
        *xc++ = (ULong)(y & FFFFFFFF);
901
238k
    }
902
1.30M
    while(!*--xc)
903
732k
        wa--;
904
577k
    c->wds = wa;
905
577k
    return c;
906
577k
}
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
281k
{
914
281k
    Long L;
915
281k
    U u;
916
917
281k
    L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1;
918
281k
    word0(&u) = L;
919
281k
    word1(&u) = 0;
920
281k
    return dval(&u);
921
281k
}
922
923
/* Convert a Bigint to a double plus an exponent */
924
925
static double
926
b2d(Bigint *a, int *e)
927
553k
{
928
553k
    ULong *xa, *xa0, w, y, z;
929
553k
    int k;
930
553k
    U d;
931
932
553k
    xa0 = a->x;
933
553k
    xa = xa0 + a->wds;
934
553k
    y = *--xa;
935
#ifdef DEBUG
936
    if (!y) Bug("zero y in b2d");
937
#endif
938
553k
    k = hi0bits(y);
939
553k
    *e = 32 - k;
940
553k
    if (k < Ebits) {
941
335k
        word0(&d) = Exp_1 | y >> (Ebits - k);
942
335k
        w = xa > xa0 ? *--xa : 0;
943
335k
        word1(&d) = y << ((32-Ebits) + k) | w >> (Ebits - k);
944
335k
        goto ret_d;
945
335k
    }
946
217k
    z = xa > xa0 ? *--xa : 0;
947
217k
    if (k -= Ebits) {
948
212k
        word0(&d) = Exp_1 | y << k | z >> (32 - k);
949
212k
        y = xa > xa0 ? *--xa : 0;
950
212k
        word1(&d) = z << k | y >> (32 - k);
951
212k
    }
952
5.06k
    else {
953
5.06k
        word0(&d) = Exp_1 | y;
954
5.06k
        word1(&d) = z;
955
5.06k
    }
956
553k
  ret_d:
957
553k
    return dval(&d);
958
217k
}
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
471k
{
984
471k
    Bigint *b;
985
986
471k
    b = Balloc(1);
987
471k
    if (b == NULL)
988
0
        return NULL;
989
990
    /* First construct b and e assuming that scale == 0. */
991
471k
    b->wds = 2;
992
471k
    b->x[0] = word1(d);
993
471k
    b->x[1] = word0(d) & Frac_mask;
994
471k
    *e = Etiny - 1 + (int)((word0(d) & Exp_mask) >> Exp_shift);
995
471k
    if (*e < Etiny)
996
6.90k
        *e = Etiny;
997
465k
    else
998
465k
        b->x[1] |= Exp_msk1;
999
1000
    /* Now adjust for scale, provided that b != 0. */
1001
471k
    if (scale && (b->x[0] || b->x[1])) {
1002
35.7k
        *e -= scale;
1003
35.7k
        if (*e < Etiny) {
1004
28.8k
            scale = Etiny - *e;
1005
28.8k
            *e = Etiny;
1006
            /* We can't shift more than P-1 bits without shifting out a 1. */
1007
28.8k
            assert(0 < scale && scale <= P - 1);
1008
28.8k
            if (scale >= 32) {
1009
                /* The bits shifted out should all be zero. */
1010
17.9k
                assert(b->x[0] == 0);
1011
17.9k
                b->x[0] = b->x[1];
1012
17.9k
                b->x[1] = 0;
1013
17.9k
                scale -= 32;
1014
17.9k
            }
1015
28.8k
            if (scale) {
1016
                /* The bits shifted out should all be zero. */
1017
27.0k
                assert(b->x[0] << (32 - scale) == 0);
1018
27.0k
                b->x[0] = (b->x[0] >> scale) | (b->x[1] << (32 - scale));
1019
27.0k
                b->x[1] >>= scale;
1020
27.0k
            }
1021
28.8k
        }
1022
35.7k
    }
1023
    /* Ensure b is normalized. */
1024
471k
    if (!b->x[1])
1025
28.3k
        b->wds = 1;
1026
1027
471k
    return b;
1028
471k
}
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
41.7k
{
1042
41.7k
    Bigint *b;
1043
41.7k
    int de, k;
1044
41.7k
    ULong *x, y, z;
1045
41.7k
    int i;
1046
1047
41.7k
    b = Balloc(1);
1048
41.7k
    if (b == NULL)
1049
0
        return NULL;
1050
41.7k
    x = b->x;
1051
1052
41.7k
    z = word0(d) & Frac_mask;
1053
41.7k
    word0(d) &= 0x7fffffff;   /* clear sign bit, which we ignore */
1054
41.7k
    if ((de = (int)(word0(d) >> Exp_shift)))
1055
37.1k
        z |= Exp_msk1;
1056
41.7k
    if ((y = word1(d))) {
1057
32.0k
        if ((k = lo0bits(&y))) {
1058
21.1k
            x[0] = y | z << (32 - k);
1059
21.1k
            z >>= k;
1060
21.1k
        }
1061
10.9k
        else
1062
10.9k
            x[0] = y;
1063
32.0k
        i =
1064
32.0k
            b->wds = (x[1] = z) ? 2 : 1;
1065
32.0k
    }
1066
9.73k
    else {
1067
9.73k
        k = lo0bits(&z);
1068
9.73k
        x[0] = z;
1069
9.73k
        i =
1070
9.73k
            b->wds = 1;
1071
9.73k
        k += 32;
1072
9.73k
    }
1073
41.7k
    if (de) {
1074
37.1k
        *e = de - Bias - (P-1) + k;
1075
37.1k
        *bits = P - k;
1076
37.1k
    }
1077
4.61k
    else {
1078
4.61k
        *e = de - Bias - (P-1) + 1 + k;
1079
4.61k
        *bits = 32*i - hi0bits(x[i-1]);
1080
4.61k
    }
1081
41.7k
    return b;
1082
41.7k
}
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
276k
{
1090
276k
    U da, db;
1091
276k
    int k, ka, kb;
1092
1093
276k
    dval(&da) = b2d(a, &ka);
1094
276k
    dval(&db) = b2d(b, &kb);
1095
276k
    k = ka - kb + 32*(a->wds - b->wds);
1096
276k
    if (k > 0)
1097
37.8k
        word0(&da) += k*Exp_msk1;
1098
238k
    else {
1099
238k
        k = -k;
1100
238k
        word0(&db) += k*Exp_msk1;
1101
238k
    }
1102
276k
    return dval(&da) / dval(&db);
1103
276k
}
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
42.1k
#define Scale_Bit 0x10
1121
49.0k
#define n_bigtens 5
1122
1123
#define ULbits 32
1124
#define kshift 5
1125
51.4k
#define kmask 31
1126
1127
1128
static int
1129
dshift(Bigint *b, int p2)
1130
51.4k
{
1131
51.4k
    int rv = hi0bits(b->x[b->wds-1]) - 4;
1132
51.4k
    if (p2 > 0)
1133
26.7k
        rv -= p2;
1134
51.4k
    return rv & kmask;
1135
51.4k
}
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
416k
{
1144
416k
    int n;
1145
416k
    ULong *bx, *bxe, q, *sx, *sxe;
1146
416k
    ULLong borrow, carry, y, ys;
1147
1148
416k
    n = S->wds;
1149
#ifdef DEBUG
1150
    /*debug*/ if (b->wds > n)
1151
        /*debug*/       Bug("oversize b in quorem");
1152
#endif
1153
416k
    if (b->wds < n)
1154
21.5k
        return 0;
1155
395k
    sx = S->x;
1156
395k
    sxe = sx + --n;
1157
395k
    bx = b->x;
1158
395k
    bxe = bx + n;
1159
395k
    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
395k
    if (q) {
1165
281k
        borrow = 0;
1166
281k
        carry = 0;
1167
1.89M
        do {
1168
1.89M
            ys = *sx++ * (ULLong)q + carry;
1169
1.89M
            carry = ys >> 32;
1170
1.89M
            y = *bx - (ys & FFFFFFFF) - borrow;
1171
1.89M
            borrow = y >> 32 & (ULong)1;
1172
1.89M
            *bx++ = (ULong)(y & FFFFFFFF);
1173
1.89M
        }
1174
1.89M
        while(sx <= sxe);
1175
281k
        if (!*bxe) {
1176
1.46k
            bx = b->x;
1177
1.46k
            while(--bxe > bx && !*bxe)
1178
0
                --n;
1179
1.46k
            b->wds = n;
1180
1.46k
        }
1181
281k
    }
1182
395k
    if (cmp(b, S) >= 0) {
1183
24.0k
        q++;
1184
24.0k
        borrow = 0;
1185
24.0k
        carry = 0;
1186
24.0k
        bx = b->x;
1187
24.0k
        sx = S->x;
1188
166k
        do {
1189
166k
            ys = *sx++ + carry;
1190
166k
            carry = ys >> 32;
1191
166k
            y = *bx - (ys & FFFFFFFF) - borrow;
1192
166k
            borrow = y >> 32 & (ULong)1;
1193
166k
            *bx++ = (ULong)(y & FFFFFFFF);
1194
166k
        }
1195
166k
        while(sx <= sxe);
1196
24.0k
        bx = b->x;
1197
24.0k
        bxe = bx + n;
1198
24.0k
        if (!*bxe) {
1199
21.7k
            while(--bxe > bx && !*bxe)
1200
1.70k
                --n;
1201
20.0k
            b->wds = n;
1202
20.0k
        }
1203
24.0k
    }
1204
395k
    return q;
1205
416k
}
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
5.54k
{
1216
5.54k
    U u;
1217
1218
5.54k
    if (bc->scale && 2*P + 1 > (int)((word0(x) & Exp_mask) >> Exp_shift)) {
1219
        /* rv/2^bc->scale is subnormal */
1220
302
        word0(&u) = (P+2)*Exp_msk1;
1221
302
        word1(&u) = 0;
1222
302
        return u.d;
1223
302
    }
1224
5.24k
    else {
1225
5.24k
        assert(word0(x) || word1(x)); /* x != 0.0 */
1226
5.24k
        return ulp(x);
1227
5.24k
    }
1228
5.54k
}
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
17.8k
{
1279
17.8k
    Bigint *b, *d;
1280
17.8k
    int b2, d2, dd, i, nd, nd0, odd, p2, p5;
1281
1282
17.8k
    nd = bc->nd;
1283
17.8k
    nd0 = bc->nd0;
1284
17.8k
    p5 = nd + bc->e0;
1285
17.8k
    b = sd2b(rv, bc->scale, &p2);
1286
17.8k
    if (b == NULL)
1287
0
        return -1;
1288
1289
    /* record whether the lsb of rv/2^(bc->scale) is odd:  in the exact halfway
1290
       case, this is used for round to even. */
1291
17.8k
    odd = b->x[0] & 1;
1292
1293
    /* left shift b by 1 bit and or a 1 into the least significant bit;
1294
       this gives us b * 2**p2 = rv/2^(bc->scale) + 0.5 ulp. */
1295
17.8k
    b = lshift(b, 1);
1296
17.8k
    if (b == NULL)
1297
0
        return -1;
1298
17.8k
    b->x[0] |= 1;
1299
17.8k
    p2--;
1300
1301
17.8k
    p2 -= p5;
1302
17.8k
    d = i2b(1);
1303
17.8k
    if (d == NULL) {
1304
0
        Bfree(b);
1305
0
        return -1;
1306
0
    }
1307
    /* Arrange for convenient computation of quotients:
1308
     * shift left if necessary so divisor has 4 leading 0 bits.
1309
     */
1310
17.8k
    if (p5 > 0) {
1311
13.0k
        d = pow5mult(d, p5);
1312
13.0k
        if (d == NULL) {
1313
0
            Bfree(b);
1314
0
            return -1;
1315
0
        }
1316
13.0k
    }
1317
4.85k
    else if (p5 < 0) {
1318
3.93k
        b = pow5mult(b, -p5);
1319
3.93k
        if (b == NULL) {
1320
0
            Bfree(d);
1321
0
            return -1;
1322
0
        }
1323
3.93k
    }
1324
17.8k
    if (p2 > 0) {
1325
9.71k
        b2 = p2;
1326
9.71k
        d2 = 0;
1327
9.71k
    }
1328
8.17k
    else {
1329
8.17k
        b2 = 0;
1330
8.17k
        d2 = -p2;
1331
8.17k
    }
1332
17.8k
    i = dshift(d, d2);
1333
17.8k
    if ((b2 += i) > 0) {
1334
17.3k
        b = lshift(b, b2);
1335
17.3k
        if (b == NULL) {
1336
0
            Bfree(d);
1337
0
            return -1;
1338
0
        }
1339
17.3k
    }
1340
17.8k
    if ((d2 += i) > 0) {
1341
16.6k
        d = lshift(d, d2);
1342
16.6k
        if (d == NULL) {
1343
0
            Bfree(b);
1344
0
            return -1;
1345
0
        }
1346
16.6k
    }
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
17.8k
    if (cmp(b, d) >= 0)
1352
        /* b/d >= 1 */
1353
1.98k
        dd = -1;
1354
15.9k
    else {
1355
15.9k
        i = 0;
1356
289k
        for(;;) {
1357
289k
            b = multadd(b, 10, 0);
1358
289k
            if (b == NULL) {
1359
0
                Bfree(d);
1360
0
                return -1;
1361
0
            }
1362
289k
            dd = s0[i < nd0 ? i : i+1] - '0' - quorem(b, d);
1363
289k
            i++;
1364
1365
289k
            if (dd)
1366
14.3k
                break;
1367
274k
            if (!b->x[0] && b->wds == 1) {
1368
                /* b/d == 0 */
1369
1.00k
                dd = i < nd;
1370
1.00k
                break;
1371
1.00k
            }
1372
273k
            if (!(i < nd)) {
1373
                /* b/d != 0, but digits of s0 exhausted */
1374
548
                dd = -1;
1375
548
                break;
1376
548
            }
1377
273k
        }
1378
15.9k
    }
1379
17.8k
    Bfree(b);
1380
17.8k
    Bfree(d);
1381
17.8k
    if (dd > 0 || (dd == 0 && odd))
1382
2.78k
        dval(rv) += sulp(rv, bc);
1383
17.8k
    return 0;
1384
17.8k
}
1385
1386
1387
double
1388
_Py_dg_strtod(const char *s00, char **se)
1389
769k
{
1390
769k
    int bb2, bb5, bbe, bd2, bd5, bs2, c, dsign, e, e1, error;
1391
769k
    int esign, i, j, k, lz, nd, nd0, odd, sign;
1392
769k
    const char *s, *s0, *s1;
1393
769k
    double aadj, aadj1;
1394
769k
    U aadj2, adj, rv, rv0;
1395
769k
    ULong y, z, abs_exp;
1396
769k
    Long L;
1397
769k
    BCinfo bc;
1398
769k
    Bigint *bb = NULL, *bd = NULL, *bd0 = NULL, *bs = NULL, *delta = NULL;
1399
769k
    size_t ndigits, fraclen;
1400
769k
    double result;
1401
1402
769k
    dval(&rv) = 0.;
1403
1404
    /* Start parsing. */
1405
769k
    c = *(s = s00);
1406
1407
    /* Parse optional sign, if present. */
1408
769k
    sign = 0;
1409
769k
    switch (c) {
1410
209k
    case '-':
1411
209k
        sign = 1;
1412
209k
        _Py_FALLTHROUGH;
1413
209k
    case '+':
1414
209k
        c = *++s;
1415
769k
    }
1416
1417
    /* Skip leading zeros: lz is true iff there were leading zeros. */
1418
769k
    s1 = s;
1419
902k
    while (c == '0')
1420
132k
        c = *++s;
1421
769k
    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
769k
    s0 = s1 = s;
1428
10.7M
    while ('0' <= c && c <= '9')
1429
9.93M
        c = *++s;
1430
769k
    ndigits = s - s1;
1431
769k
    fraclen = 0;
1432
1433
    /* Parse decimal point and following digits. */
1434
769k
    if (c == '.') {
1435
79.3k
        c = *++s;
1436
79.3k
        if (!ndigits) {
1437
29.0k
            s1 = s;
1438
4.54M
            while (c == '0')
1439
4.51M
                c = *++s;
1440
29.0k
            lz = lz || s != s1;
1441
29.0k
            fraclen += (s - s1);
1442
29.0k
            s0 = s;
1443
29.0k
        }
1444
79.3k
        s1 = s;
1445
40.1M
        while ('0' <= c && c <= '9')
1446
40.0M
            c = *++s;
1447
79.3k
        ndigits += s - s1;
1448
79.3k
        fraclen += s - s1;
1449
79.3k
    }
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
769k
    if (!ndigits && !lz) {
1455
33.0k
        if (se)
1456
33.0k
            *se = (char *)s00;
1457
33.0k
        goto parse_error;
1458
33.0k
    }
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
736k
    if (ndigits > MAX_DIGITS || fraclen > MAX_DIGITS) {
1463
0
        if (se)
1464
0
            *se = (char *)s00;
1465
0
        goto parse_error;
1466
0
    }
1467
736k
    nd = (int)ndigits;
1468
736k
    nd0 = (int)ndigits - (int)fraclen;
1469
1470
    /* Parse exponent. */
1471
736k
    e = 0;
1472
736k
    if (c == 'e' || c == 'E') {
1473
649k
        s00 = s;
1474
649k
        c = *++s;
1475
1476
        /* Exponent sign. */
1477
649k
        esign = 0;
1478
649k
        switch (c) {
1479
39.4k
        case '-':
1480
39.4k
            esign = 1;
1481
39.4k
            _Py_FALLTHROUGH;
1482
54.0k
        case '+':
1483
54.0k
            c = *++s;
1484
649k
        }
1485
1486
        /* Skip zeros.  lz is true iff there are leading zeros. */
1487
649k
        s1 = s;
1488
2.24M
        while (c == '0')
1489
1.59M
            c = *++s;
1490
649k
        lz = s != s1;
1491
1492
        /* Get absolute value of the exponent. */
1493
649k
        s1 = s;
1494
649k
        abs_exp = 0;
1495
14.9M
        while ('0' <= c && c <= '9') {
1496
14.3M
            abs_exp = 10*abs_exp + (c - '0');
1497
14.3M
            c = *++s;
1498
14.3M
        }
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
649k
        if (s - s1 > 9 || abs_exp > MAX_ABS_EXP)
1504
10.4k
            e = (int)MAX_ABS_EXP;
1505
639k
        else
1506
639k
            e = (int)abs_exp;
1507
649k
        if (esign)
1508
39.4k
            e = -e;
1509
1510
        /* A valid exponent must have at least one digit. */
1511
649k
        if (s == s1 && !lz)
1512
20
            s = s00;
1513
649k
    }
1514
1515
    /* Adjust exponent to take into account position of the point. */
1516
736k
    e -= nd - nd0;
1517
736k
    if (nd0 <= 0)
1518
32.9k
        nd0 = nd;
1519
1520
    /* Finished parsing.  Set se to indicate how far we parsed */
1521
736k
    if (se)
1522
736k
        *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
736k
    if (!nd)
1527
8.20k
        goto ret;
1528
9.74M
    for (i = nd; i > 0; ) {
1529
9.74M
        --i;
1530
9.74M
        if (s0[i < nd0 ? i : i+1] != '0') {
1531
728k
            ++i;
1532
728k
            break;
1533
728k
        }
1534
9.74M
    }
1535
728k
    e += nd - i;
1536
728k
    nd = i;
1537
728k
    if (nd0 > nd)
1538
14.4k
        nd0 = nd;
1539
1540
    /* Summary of parsing results.  After parsing, and dealing with zero
1541
     * inputs, we have values s0, nd0, nd, e, sign, where:
1542
     *
1543
     *  - s0 points to the first significant digit of the input string
1544
     *
1545
     *  - nd is the total number of significant digits (here, and
1546
     *    below, 'significant digits' means the set of digits of the
1547
     *    significand of the input that remain after ignoring leading
1548
     *    and trailing zeros).
1549
     *
1550
     *  - nd0 indicates the position of the decimal point, if present; it
1551
     *    satisfies 1 <= nd0 <= nd.  The nd significant digits are in
1552
     *    s0[0:nd0] and s0[nd0+1:nd+1] using the usual Python half-open slice
1553
     *    notation.  (If nd0 < nd, then s0[nd0] contains a '.'  character; if
1554
     *    nd0 == nd, then s0[nd0] could be any non-digit character.)
1555
     *
1556
     *  - e is the adjusted exponent: the absolute value of the number
1557
     *    represented by the original input string is n * 10**e, where
1558
     *    n is the integer represented by the concatenation of
1559
     *    s0[0:nd0] and s0[nd0+1:nd+1]
1560
     *
1561
     *  - sign gives the sign of the input:  1 for negative, 0 for positive
1562
     *
1563
     *  - the first and last significant digits are nonzero
1564
     */
1565
1566
    /* put first DBL_DIG+1 digits into integer y and z.
1567
     *
1568
     *  - y contains the value represented by the first min(9, nd)
1569
     *    significant digits
1570
     *
1571
     *  - if nd > 9, z contains the value represented by significant digits
1572
     *    with indices in [9, min(16, nd)).  So y * 10**(min(16, nd) - 9) + z
1573
     *    gives the value represented by the first min(16, nd) sig. digits.
1574
     */
1575
1576
728k
    bc.e0 = e1 = e;
1577
728k
    y = z = 0;
1578
3.61M
    for (i = 0; i < nd; i++) {
1579
2.94M
        if (i < 9)
1580
2.43M
            y = 10*y + s0[i < nd0 ? i : i+1] - '0';
1581
508k
        else if (i < DBL_DIG+1)
1582
455k
            z = 10*z + s0[i < nd0 ? i : i+1] - '0';
1583
53.0k
        else
1584
53.0k
            break;
1585
2.94M
    }
1586
1587
728k
    k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;
1588
728k
    dval(&rv) = y;
1589
728k
    if (k > 9) {
1590
74.8k
        dval(&rv) = tens[k - 9] * dval(&rv) + z;
1591
74.8k
    }
1592
728k
    if (nd <= DBL_DIG
1593
667k
        && Flt_Rounds == 1
1594
728k
        ) {
1595
667k
        if (!e)
1596
14.9k
            goto ret;
1597
652k
        if (e > 0) {
1598
596k
            if (e <= Ten_pmax) {
1599
25.7k
                dval(&rv) *= tens[e];
1600
25.7k
                goto ret;
1601
25.7k
            }
1602
571k
            i = DBL_DIG - nd;
1603
571k
            if (e <= Ten_pmax + i) {
1604
                /* A fancier test would sometimes let us do
1605
                 * this for larger i values.
1606
                 */
1607
9.94k
                e -= i;
1608
9.94k
                dval(&rv) *= tens[i];
1609
9.94k
                dval(&rv) *= tens[e];
1610
9.94k
                goto ret;
1611
9.94k
            }
1612
571k
        }
1613
55.6k
        else if (e >= -Ten_pmax) {
1614
22.1k
            dval(&rv) /= tens[-e];
1615
22.1k
            goto ret;
1616
22.1k
        }
1617
652k
    }
1618
655k
    e1 += nd - k;
1619
1620
655k
    bc.scale = 0;
1621
1622
    /* Get starting approximation = rv * 10**e1 */
1623
1624
655k
    if (e1 > 0) {
1625
591k
        if ((i = e1 & 15))
1626
479k
            dval(&rv) *= tens[i];
1627
591k
        if (e1 &= ~15) {
1628
576k
            if (e1 > DBL_MAX_10_EXP)
1629
228k
                goto ovfl;
1630
348k
            e1 >>= 4;
1631
881k
            for(j = 0; e1 > 1; j++, e1 >>= 1)
1632
533k
                if (e1 & 1)
1633
281k
                    dval(&rv) *= bigtens[j];
1634
            /* The last multiplication could overflow. */
1635
348k
            word0(&rv) -= P*Exp_msk1;
1636
348k
            dval(&rv) *= bigtens[j];
1637
348k
            if ((z = word0(&rv) & Exp_mask)
1638
348k
                > Exp_msk1*(DBL_MAX_EXP+Bias-P))
1639
2.69k
                goto ovfl;
1640
345k
            if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) {
1641
                /* set to largest number */
1642
                /* (Can't trust DBL_MAX) */
1643
765
                word0(&rv) = Big0;
1644
765
                word1(&rv) = Big1;
1645
765
            }
1646
344k
            else
1647
344k
                word0(&rv) += P*Exp_msk1;
1648
345k
        }
1649
591k
    }
1650
64.4k
    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
60.6k
        e1 = -e1;
1662
60.6k
        if ((i = e1 & 15))
1663
47.3k
            dval(&rv) /= tens[i];
1664
60.6k
        if (e1 >>= 4) {
1665
49.0k
            if (e1 >= 1 << n_bigtens)
1666
6.89k
                goto undfl;
1667
42.1k
            if (e1 & Scale_Bit)
1668
21.8k
                bc.scale = 2*P;
1669
197k
            for(j = 0; e1 > 0; j++, e1 >>= 1)
1670
154k
                if (e1 & 1)
1671
92.6k
                    dval(&rv) *= tinytens[j];
1672
42.1k
            if (bc.scale && (j = 2*P + 1 - ((word0(&rv) & Exp_mask)
1673
21.8k
                                            >> Exp_shift)) > 0) {
1674
                /* scaled rv is denormal; clear j low bits */
1675
18.7k
                if (j >= 32) {
1676
12.7k
                    word1(&rv) = 0;
1677
12.7k
                    if (j >= 53)
1678
6.22k
                        word0(&rv) = (P+2)*Exp_msk1;
1679
6.56k
                    else
1680
6.56k
                        word0(&rv) &= 0xffffffff << (j-32);
1681
12.7k
                }
1682
5.95k
                else
1683
5.95k
                    word1(&rv) &= 0xffffffff << j;
1684
18.7k
            }
1685
42.1k
            if (!dval(&rv))
1686
0
                goto undfl;
1687
42.1k
        }
1688
60.6k
    }
1689
1690
    /* Now the hard part -- adjusting rv to the correct value.*/
1691
1692
    /* Put digits into bd: true value = bd * 10^e */
1693
1694
417k
    bc.nd = nd;
1695
417k
    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
417k
    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
196k
        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
196k
            --i;
1710
196k
            if (s0[i < nd0 ? i : i+1] != '0') {
1711
27.0k
                ++i;
1712
27.0k
                break;
1713
27.0k
            }
1714
196k
        }
1715
27.0k
        e += nd - i;
1716
27.0k
        nd = i;
1717
27.0k
        if (nd0 > nd)
1718
21.5k
            nd0 = nd;
1719
27.0k
        if (nd < 9) { /* must recompute y */
1720
11.5k
            y = 0;
1721
58.5k
            for(i = 0; i < nd0; ++i)
1722
46.9k
                y = 10*y + s0[i] - '0';
1723
21.5k
            for(; i < nd; ++i)
1724
9.91k
                y = 10*y + s0[i+1] - '0';
1725
11.5k
        }
1726
27.0k
    }
1727
417k
    bd0 = s2b(s0, nd0, nd, y);
1728
417k
    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
454k
    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
454k
        bd = Balloc(bd0->k);
1760
454k
        if (bd == NULL) {
1761
0
            goto failed_malloc;
1762
0
        }
1763
454k
        Bcopy(bd, bd0);
1764
454k
        bb = sd2b(&rv, bc.scale, &bbe);   /* srv = bb * 2^bbe */
1765
454k
        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
454k
        odd = bb->x[0] & 1;
1771
1772
        /* tdv = bd * 10**e;  srv = bb * 2**bbe */
1773
454k
        bs = i2b(1);
1774
454k
        if (bs == NULL) {
1775
0
            goto failed_malloc;
1776
0
        }
1777
1778
454k
        if (e >= 0) {
1779
372k
            bb2 = bb5 = 0;
1780
372k
            bd2 = bd5 = e;
1781
372k
        }
1782
81.8k
        else {
1783
81.8k
            bb2 = bb5 = -e;
1784
81.8k
            bd2 = bd5 = 0;
1785
81.8k
        }
1786
454k
        if (bbe >= 0)
1787
376k
            bb2 += bbe;
1788
77.1k
        else
1789
77.1k
            bd2 -= bbe;
1790
454k
        bs2 = bb2;
1791
454k
        bb2++;
1792
454k
        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
454k
        i = bb2 < bd2 ? bb2 : bd2;
1813
454k
        if (i > bs2)
1814
77.1k
            i = bs2;
1815
454k
        if (i > 0) {
1816
451k
            bb2 -= i;
1817
451k
            bd2 -= i;
1818
451k
            bs2 -= i;
1819
451k
        }
1820
1821
        /* Scale bb, bd, bs by the appropriate powers of 2 and 5. */
1822
454k
        if (bb5 > 0) {
1823
81.8k
            bs = pow5mult(bs, bb5);
1824
81.8k
            if (bs == NULL) {
1825
0
                goto failed_malloc;
1826
0
            }
1827
81.8k
            Bigint *bb1 = mult(bs, bb);
1828
81.8k
            Bfree(bb);
1829
81.8k
            bb = bb1;
1830
81.8k
            if (bb == NULL) {
1831
0
                goto failed_malloc;
1832
0
            }
1833
81.8k
        }
1834
454k
        if (bb2 > 0) {
1835
454k
            bb = lshift(bb, bb2);
1836
454k
            if (bb == NULL) {
1837
0
                goto failed_malloc;
1838
0
            }
1839
454k
        }
1840
454k
        if (bd5 > 0) {
1841
359k
            bd = pow5mult(bd, bd5);
1842
359k
            if (bd == NULL) {
1843
0
                goto failed_malloc;
1844
0
            }
1845
359k
        }
1846
454k
        if (bd2 > 0) {
1847
77.1k
            bd = lshift(bd, bd2);
1848
77.1k
            if (bd == NULL) {
1849
0
                goto failed_malloc;
1850
0
            }
1851
77.1k
        }
1852
454k
        if (bs2 > 0) {
1853
371k
            bs = lshift(bs, bs2);
1854
371k
            if (bs == NULL) {
1855
0
                goto failed_malloc;
1856
0
            }
1857
371k
        }
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
454k
        delta = diff(bb, bd);
1864
454k
        if (delta == NULL) {
1865
0
            goto failed_malloc;
1866
0
        }
1867
454k
        dsign = delta->sign;
1868
454k
        delta->sign = 0;
1869
454k
        i = cmp(delta, bs);
1870
454k
        if (bc.nd > nd && i <= 0) {
1871
26.9k
            if (dsign)
1872
16.4k
                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
10.4k
            if (!word1(&rv) && !(word0(&rv) & Bndry_mask)) {
1886
                /* rv can't be 0, since it's an overestimate for some
1887
                   nonzero value.  So rv is a normal power of 2. */
1888
3.75k
                j = (int)(word0(&rv) & Exp_mask) >> Exp_shift;
1889
                /* rv / 2^bc.scale = 2^(j - 1023 - bc.scale); use bigcomp if
1890
                   rv / 2^bc.scale >= 2^-1021. */
1891
3.75k
                if (j - bc.scale >= 2) {
1892
1.46k
                    dval(&rv) -= 0.5 * sulp(&rv, &bc);
1893
1.46k
                    break; /* Use bigcomp. */
1894
1.46k
                }
1895
3.75k
            }
1896
1897
9.01k
            {
1898
9.01k
                bc.nd = nd;
1899
9.01k
                i = -1; /* Discarded digits make delta smaller. */
1900
9.01k
            }
1901
9.01k
        }
1902
1903
436k
        if (i < 0) {
1904
            /* Error is less than half an ulp -- check for
1905
             * special case of mantissa a power of two.
1906
             */
1907
154k
            if (dsign || word1(&rv) || word0(&rv) & Bndry_mask
1908
12.7k
                || (word0(&rv) & Exp_mask) <= (2*P+1)*Exp_msk1
1909
154k
                ) {
1910
145k
                break;
1911
145k
            }
1912
9.17k
            if (!delta->x[0] && delta->wds <= 1) {
1913
                /* exact result */
1914
950
                break;
1915
950
            }
1916
8.22k
            delta = lshift(delta,Log2P);
1917
8.22k
            if (delta == NULL) {
1918
0
                goto failed_malloc;
1919
0
            }
1920
8.22k
            if (cmp(delta, bs) > 0)
1921
3.29k
                goto drop_down;
1922
4.93k
            break;
1923
8.22k
        }
1924
281k
        if (i == 0) {
1925
            /* exactly half-way between */
1926
5.20k
            if (dsign) {
1927
3.04k
                if ((word0(&rv) & Bndry_mask1) == Bndry_mask1
1928
913
                    &&  word1(&rv) == (
1929
913
                        (bc.scale &&
1930
0
                         (y = word0(&rv) & Exp_mask) <= 2*P*Exp_msk1) ?
1931
0
                        (0xffffffff & (0xffffffff << (2*P+1-(y>>Exp_shift)))) :
1932
913
                        0xffffffff)) {
1933
                    /*boundary case -- increment exponent*/
1934
490
                    word0(&rv) = (word0(&rv) & Exp_mask)
1935
490
                        + Exp_msk1
1936
490
                        ;
1937
490
                    word1(&rv) = 0;
1938
                    /* dsign = 0; */
1939
490
                    break;
1940
490
                }
1941
3.04k
            }
1942
2.16k
            else if (!(word0(&rv) & Bndry_mask) && !word1(&rv)) {
1943
3.29k
              drop_down:
1944
                /* boundary case -- decrement exponent */
1945
3.29k
                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
3.29k
                L = (word0(&rv) & Exp_mask) - Exp_msk1;
1959
3.29k
                word0(&rv) = L | Bndry_mask1;
1960
3.29k
                word1(&rv) = 0xffffffff;
1961
3.29k
                break;
1962
3.29k
            }
1963
4.71k
            if (!odd)
1964
3.41k
                break;
1965
1.29k
            if (dsign)
1966
894
                dval(&rv) += sulp(&rv, &bc);
1967
404
            else {
1968
404
                dval(&rv) -= sulp(&rv, &bc);
1969
404
                if (!dval(&rv)) {
1970
0
                    if (bc.nd >nd)
1971
0
                        break;
1972
0
                    goto undfl;
1973
0
                }
1974
404
            }
1975
            /* dsign = 1 - dsign; */
1976
1.29k
            break;
1977
1.29k
        }
1978
276k
        if ((aadj = ratio(delta, bs)) <= 2.) {
1979
252k
            if (dsign)
1980
23.7k
                aadj = aadj1 = 1.;
1981
228k
            else if (word1(&rv) || word0(&rv) & Bndry_mask) {
1982
223k
                if (word1(&rv) == Tiny1 && !word0(&rv)) {
1983
0
                    if (bc.nd >nd)
1984
0
                        break;
1985
0
                    goto undfl;
1986
0
                }
1987
223k
                aadj = 1.;
1988
223k
                aadj1 = -1.;
1989
223k
            }
1990
5.43k
            else {
1991
                /* special case -- power of FLT_RADIX to be */
1992
                /* rounded down... */
1993
1994
5.43k
                if (aadj < 2./FLT_RADIX)
1995
0
                    aadj = 1./FLT_RADIX;
1996
5.43k
                else
1997
5.43k
                    aadj *= 0.5;
1998
5.43k
                aadj1 = -aadj;
1999
5.43k
            }
2000
252k
        }
2001
24.0k
        else {
2002
24.0k
            aadj *= 0.5;
2003
24.0k
            aadj1 = dsign ? aadj : -aadj;
2004
24.0k
            if (Flt_Rounds == 0)
2005
0
                aadj1 += 0.5;
2006
24.0k
        }
2007
276k
        y = word0(&rv) & Exp_mask;
2008
2009
        /* Check for overflow */
2010
2011
276k
        if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) {
2012
4.33k
            dval(&rv0) = dval(&rv);
2013
4.33k
            word0(&rv) -= P*Exp_msk1;
2014
4.33k
            adj.d = aadj1 * ulp(&rv);
2015
4.33k
            dval(&rv) += adj.d;
2016
4.33k
            if ((word0(&rv) & Exp_mask) >=
2017
4.33k
                Exp_msk1*(DBL_MAX_EXP+Bias-P)) {
2018
1.50k
                if (word0(&rv0) == Big0 && word1(&rv0) == Big1) {
2019
1.13k
                    goto ovfl;
2020
1.13k
                }
2021
371
                word0(&rv) = Big0;
2022
371
                word1(&rv) = Big1;
2023
371
                goto cont;
2024
1.50k
            }
2025
2.82k
            else
2026
2.82k
                word0(&rv) += P*Exp_msk1;
2027
4.33k
        }
2028
272k
        else {
2029
272k
            if (bc.scale && y <= 2*P*Exp_msk1) {
2030
15.6k
                if (aadj <= 0x7fffffff) {
2031
15.6k
                    if ((z = (ULong)aadj) <= 0)
2032
1.87k
                        z = 1;
2033
15.6k
                    aadj = z;
2034
15.6k
                    aadj1 = dsign ? aadj : -aadj;
2035
15.6k
                }
2036
15.6k
                dval(&aadj2) = aadj1;
2037
15.6k
                word0(&aadj2) += (2*P+1)*Exp_msk1 - y;
2038
15.6k
                aadj1 = dval(&aadj2);
2039
15.6k
            }
2040
272k
            adj.d = aadj1 * ulp(&rv);
2041
272k
            dval(&rv) += adj.d;
2042
272k
        }
2043
275k
        z = word0(&rv) & Exp_mask;
2044
275k
        if (bc.nd == nd) {
2045
259k
            if (!bc.scale)
2046
245k
                if (y == z) {
2047
                    /* Can we stop now? */
2048
240k
                    L = (Long)aadj;
2049
240k
                    aadj -= L;
2050
                    /* The tolerances below are conservative. */
2051
240k
                    if (dsign || word1(&rv) || word0(&rv) & Bndry_mask) {
2052
240k
                        if (aadj < .4999999 || aadj > .5000001)
2053
238k
                            break;
2054
240k
                    }
2055
299
                    else if (aadj < .4999999/FLT_RADIX)
2056
299
                        break;
2057
240k
                }
2058
259k
        }
2059
36.7k
      cont:
2060
36.7k
        Bfree(bb); bb = NULL;
2061
36.7k
        Bfree(bd); bd = NULL;
2062
36.7k
        Bfree(bs); bs = NULL;
2063
36.7k
        Bfree(delta); delta = NULL;
2064
36.7k
    }
2065
416k
    if (bc.nd > nd) {
2066
17.8k
        error = bigcomp(&rv, s0, &bc);
2067
17.8k
        if (error)
2068
0
            goto failed_malloc;
2069
17.8k
    }
2070
2071
416k
    if (bc.scale) {
2072
21.8k
        word0(&rv0) = Exp_1 - 2*P*Exp_msk1;
2073
21.8k
        word1(&rv0) = 0;
2074
21.8k
        dval(&rv) *= dval(&rv0);
2075
21.8k
    }
2076
2077
497k
  ret:
2078
497k
    result = sign ? -dval(&rv) : dval(&rv);
2079
497k
    goto done;
2080
2081
33.0k
  parse_error:
2082
33.0k
    result = 0.0;
2083
33.0k
    goto done;
2084
2085
0
  failed_malloc:
2086
0
    errno = ENOMEM;
2087
0
    result = -1.0;
2088
0
    goto done;
2089
2090
6.89k
  undfl:
2091
6.89k
    result = sign ? -0.0 : 0.0;
2092
6.89k
    goto done;
2093
2094
232k
  ovfl:
2095
232k
    errno = ERANGE;
2096
    /* Can't trust HUGE_VAL */
2097
232k
    word0(&rv) = Exp_mask;
2098
232k
    word1(&rv) = 0;
2099
232k
    result = sign ? -dval(&rv) : dval(&rv);
2100
232k
    goto done;
2101
2102
769k
  done:
2103
769k
    Bfree(bb);
2104
769k
    Bfree(bd);
2105
769k
    Bfree(bs);
2106
769k
    Bfree(bd0);
2107
769k
    Bfree(delta);
2108
769k
    return result;
2109
2110
416k
}
2111
2112
static char *
2113
rv_alloc(int i)
2114
45.6k
{
2115
45.6k
    int k, *r;
2116
45.6k
    size_t j;   /* size_t so that j <<= 1 cannot overflow for i near INT_MAX */
2117
2118
45.6k
    j = sizeof(ULong);
2119
45.6k
    for(k = 0;
2120
45.6k
        sizeof(Bigint) - sizeof(ULong) - sizeof(int) + j <= (unsigned)i;
2121
45.6k
        j <<= 1)
2122
0
        k++;
2123
45.6k
    r = (int*)Balloc(k);
2124
45.6k
    if (r == NULL)
2125
0
        return NULL;
2126
45.6k
    *r = k;
2127
45.6k
    return (char *)(r+1);
2128
45.6k
}
2129
2130
static char *
2131
nrv_alloc(const char *s, char **rve, int n)
2132
3.89k
{
2133
3.89k
    char *rv, *t;
2134
2135
3.89k
    rv = rv_alloc(n);
2136
3.89k
    if (rv == NULL)
2137
0
        return NULL;
2138
3.89k
    t = rv;
2139
12.4k
    while((*t = *s++)) t++;
2140
3.89k
    if (rve)
2141
3.89k
        *rve = t;
2142
3.89k
    return rv;
2143
3.89k
}
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
45.6k
{
2154
45.6k
    Bigint *b = (Bigint *)((int *)s - 1);
2155
45.6k
    b->maxwds = 1 << (b->k = *(int*)b);
2156
45.6k
    Bfree(b);
2157
45.6k
}
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
45.6k
{
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
45.6k
    int bbits, b2, b5, be, dig, i, ieps, ilim, ilim0, ilim1,
2236
45.6k
        j, j1, k, k0, k_check, leftright, m2, m5, s2, s5,
2237
45.6k
        spec_case, try_quick;
2238
45.6k
    Long L;
2239
45.6k
    int denorm;
2240
45.6k
    ULong x;
2241
45.6k
    Bigint *b, *b1, *delta, *mlo, *mhi, *S;
2242
45.6k
    U d2, eps, u;
2243
45.6k
    double ds;
2244
45.6k
    char *s, *s0;
2245
2246
    /* set pointers to NULL, to silence gcc compiler warnings and make
2247
       cleanup easier on error */
2248
45.6k
    mlo = mhi = S = 0;
2249
45.6k
    s0 = 0;
2250
2251
45.6k
    u.d = dd;
2252
45.6k
    if (word0(&u) & Sign_bit) {
2253
        /* set sign for everything, including 0's and NaNs */
2254
12.1k
        *sign = 1;
2255
12.1k
        word0(&u) &= ~Sign_bit; /* clear sign bit */
2256
12.1k
    }
2257
33.5k
    else
2258
33.5k
        *sign = 0;
2259
2260
    /* quick return for Infinities, NaNs and zeros */
2261
45.6k
    if ((word0(&u) & Exp_mask) == Exp_mask)
2262
676
    {
2263
        /* Infinity or NaN */
2264
676
        *decpt = 9999;
2265
676
        if (!word1(&u) && !(word0(&u) & 0xfffff))
2266
673
            return nrv_alloc("Infinity", rve, 8);
2267
3
        return nrv_alloc("NaN", rve, 3);
2268
676
    }
2269
44.9k
    if (!dval(&u)) {
2270
3.21k
        *decpt = 1;
2271
3.21k
        return nrv_alloc("0", rve, 1);
2272
3.21k
    }
2273
2274
    /* compute k = floor(log10(d)).  The computation may leave k
2275
       one too large, but should never leave k too small. */
2276
41.7k
    b = d2b(&u, &be, &bbits);
2277
41.7k
    if (b == NULL)
2278
0
        goto failed_malloc;
2279
41.7k
    if ((i = (int)(word0(&u) >> Exp_shift1 & (Exp_mask>>Exp_shift1)))) {
2280
37.1k
        dval(&d2) = dval(&u);
2281
37.1k
        word0(&d2) &= Frac_mask1;
2282
37.1k
        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
37.1k
        i -= Bias;
2307
37.1k
        denorm = 0;
2308
37.1k
    }
2309
4.61k
    else {
2310
        /* d is denormalized */
2311
2312
4.61k
        i = bbits + be + (Bias + (P-1) - 1);
2313
4.61k
        x = i > 32  ? word0(&u) << (64 - i) | word1(&u) >> (i - 32)
2314
4.61k
            : word1(&u) << (32 - i);
2315
4.61k
        dval(&d2) = x;
2316
4.61k
        word0(&d2) -= 31*Exp_msk1; /* adjust exponent */
2317
4.61k
        i -= (Bias + (P-1) - 1) + 1;
2318
4.61k
        denorm = 1;
2319
4.61k
    }
2320
41.7k
    ds = (dval(&d2)-1.5)*0.289529654602168 + 0.1760912590558 +
2321
41.7k
        i*0.301029995663981;
2322
41.7k
    k = (int)ds;
2323
41.7k
    if (ds < 0. && ds != k)
2324
11.6k
        k--;    /* want k = floor(ds) */
2325
41.7k
    k_check = 1;
2326
41.7k
    if (k >= 0 && k <= Ten_pmax) {
2327
16.2k
        if (dval(&u) < tens[k])
2328
1.83k
            k--;
2329
16.2k
        k_check = 0;
2330
16.2k
    }
2331
41.7k
    j = bbits - i - 1;
2332
41.7k
    if (j >= 0) {
2333
17.6k
        b2 = 0;
2334
17.6k
        s2 = j;
2335
17.6k
    }
2336
24.0k
    else {
2337
24.0k
        b2 = -j;
2338
24.0k
        s2 = 0;
2339
24.0k
    }
2340
41.7k
    if (k >= 0) {
2341
29.6k
        b5 = 0;
2342
29.6k
        s5 = k;
2343
29.6k
        s2 += k;
2344
29.6k
    }
2345
12.1k
    else {
2346
12.1k
        b2 -= k;
2347
12.1k
        b5 = -k;
2348
12.1k
        s5 = 0;
2349
12.1k
    }
2350
41.7k
    if (mode < 0 || mode > 9)
2351
0
        mode = 0;
2352
2353
41.7k
    try_quick = 1;
2354
2355
41.7k
    if (mode > 5) {
2356
0
        mode -= 4;
2357
0
        try_quick = 0;
2358
0
    }
2359
41.7k
    leftright = 1;
2360
41.7k
    ilim = ilim1 = -1;  /* Values for cases 0 and 1; done here to */
2361
    /* silence erroneous "gcc -Wall" warning. */
2362
41.7k
    switch(mode) {
2363
41.6k
    case 0:
2364
41.6k
    case 1:
2365
41.6k
        i = 18;
2366
41.6k
        ndigits = 0;
2367
41.6k
        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
87
    case 3:
2377
87
        leftright = 0;
2378
87
        _Py_FALLTHROUGH;
2379
87
    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
87
        if (ndigits > INT_MAX - 1024)
2386
0
            ndigits = INT_MAX - 1024;
2387
87
        else if (ndigits < -(INT_MAX - 1024))
2388
0
            ndigits = -(INT_MAX - 1024);
2389
87
        i = ndigits + k + 1;
2390
87
        ilim = i;
2391
87
        ilim1 = i - 1;
2392
87
        if (i <= 0)
2393
0
            i = 1;
2394
41.7k
    }
2395
41.7k
    s0 = rv_alloc(i);
2396
41.7k
    if (s0 == NULL)
2397
0
        goto failed_malloc;
2398
41.7k
    s = s0;
2399
2400
2401
41.7k
    if (ilim >= 0 && ilim <= Quick_max && try_quick) {
2402
2403
        /* Try to get by with floating-point arithmetic. */
2404
2405
87
        i = 0;
2406
87
        dval(&d2) = dval(&u);
2407
87
        k0 = k;
2408
87
        ilim0 = ilim;
2409
87
        ieps = 2; /* conservative */
2410
87
        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
22
        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
87
        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
87
        dval(&eps) = ieps*dval(&u) + 7.;
2443
87
        word0(&eps) -= (P-1)*Exp_msk1;
2444
87
        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
87
        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
87
        else {
2473
            /* Generate ilim digits, then fix them up. */
2474
87
            dval(&eps) *= tens[ilim-1];
2475
227
            for(i = 1;; i++, dval(&u) *= 10.) {
2476
227
                L = (Long)(dval(&u));
2477
227
                if (!(dval(&u) -= L))
2478
18
                    ilim = i;
2479
227
                *s++ = '0' + (int)L;
2480
227
                if (i == ilim) {
2481
87
                    if (dval(&u) > 0.5 + dval(&eps))
2482
37
                        goto bump_up;
2483
50
                    else if (dval(&u) < 0.5 - dval(&eps)) {
2484
56
                        while(*--s == '0');
2485
50
                        s++;
2486
50
                        goto ret1;
2487
50
                    }
2488
0
                    break;
2489
87
                }
2490
227
            }
2491
87
        }
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
41.6k
    if (be >= 0 && k <= Int_max) {
2502
        /* Yes. */
2503
8.12k
        ds = tens[k];
2504
8.12k
        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
10.3k
        for(i = 1;; i++, dval(&u) *= 10.) {
2511
10.3k
            L = (Long)(dval(&u) / ds);
2512
10.3k
            dval(&u) -= L*ds;
2513
10.3k
            *s++ = '0' + (int)L;
2514
10.3k
            if (!dval(&u)) {
2515
8.12k
                break;
2516
8.12k
            }
2517
2.17k
            if (i == ilim) {
2518
0
                dval(&u) += dval(&u);
2519
0
                if (dval(&u) > ds || (dval(&u) == ds && L & 1)) {
2520
37
                  bump_up:
2521
41
                    while(*--s == '9')
2522
4
                        if (s == s0) {
2523
0
                            k++;
2524
0
                            *s = '0';
2525
0
                            break;
2526
0
                        }
2527
37
                    ++*s++;
2528
37
                }
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
37
                break;
2538
0
            }
2539
2.17k
        }
2540
8.16k
        goto ret1;
2541
8.12k
    }
2542
2543
33.5k
    m2 = b2;
2544
33.5k
    m5 = b5;
2545
33.5k
    if (leftright) {
2546
33.5k
        i =
2547
33.5k
            denorm ? be + (Bias + (P-1) - 1 + 1) :
2548
33.5k
            1 + P - bbits;
2549
33.5k
        b2 += i;
2550
33.5k
        s2 += i;
2551
33.5k
        mhi = i2b(1);
2552
33.5k
        if (mhi == NULL)
2553
0
            goto failed_malloc;
2554
33.5k
    }
2555
33.5k
    if (m2 > 0 && s2 > 0) {
2556
29.5k
        i = m2 < s2 ? m2 : s2;
2557
29.5k
        b2 -= i;
2558
29.5k
        m2 -= i;
2559
29.5k
        s2 -= i;
2560
29.5k
    }
2561
33.5k
    if (b5 > 0) {
2562
12.1k
        if (leftright) {
2563
12.1k
            if (m5 > 0) {
2564
12.1k
                mhi = pow5mult(mhi, m5);
2565
12.1k
                if (mhi == NULL)
2566
0
                    goto failed_malloc;
2567
12.1k
                b1 = mult(mhi, b);
2568
12.1k
                Bfree(b);
2569
12.1k
                b = b1;
2570
12.1k
                if (b == NULL)
2571
0
                    goto failed_malloc;
2572
12.1k
            }
2573
12.1k
            if ((j = b5 - m5)) {
2574
0
                b = pow5mult(b, j);
2575
0
                if (b == NULL)
2576
0
                    goto failed_malloc;
2577
0
            }
2578
12.1k
        }
2579
0
        else {
2580
0
            b = pow5mult(b, b5);
2581
0
            if (b == NULL)
2582
0
                goto failed_malloc;
2583
0
        }
2584
12.1k
    }
2585
33.5k
    S = i2b(1);
2586
33.5k
    if (S == NULL)
2587
0
        goto failed_malloc;
2588
33.5k
    if (s5 > 0) {
2589
19.0k
        S = pow5mult(S, s5);
2590
19.0k
        if (S == NULL)
2591
0
            goto failed_malloc;
2592
19.0k
    }
2593
2594
    /* Check for special case that d is a normalized power of 2. */
2595
2596
33.5k
    spec_case = 0;
2597
33.5k
    if ((mode < 2 || leftright)
2598
33.5k
        ) {
2599
33.5k
        if (!word1(&u) && !(word0(&u) & Bndry_mask)
2600
1.47k
            && word0(&u) & (Exp_mask & ~Exp_msk1)
2601
33.5k
            ) {
2602
            /* The special case */
2603
1.21k
            b2 += Log2P;
2604
1.21k
            s2 += Log2P;
2605
1.21k
            spec_case = 1;
2606
1.21k
        }
2607
33.5k
    }
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
33.5k
#define iInc 28
2617
33.5k
    i = dshift(S, s2);
2618
33.5k
    b2 += i;
2619
33.5k
    m2 += i;
2620
33.5k
    s2 += i;
2621
33.5k
    if (b2 > 0) {
2622
33.5k
        b = lshift(b, b2);
2623
33.5k
        if (b == NULL)
2624
0
            goto failed_malloc;
2625
33.5k
    }
2626
33.5k
    if (s2 > 0) {
2627
32.8k
        S = lshift(S, s2);
2628
32.8k
        if (S == NULL)
2629
0
            goto failed_malloc;
2630
32.8k
    }
2631
33.5k
    if (k_check) {
2632
25.5k
        if (cmp(b,S) < 0) {
2633
5.07k
            k--;
2634
5.07k
            b = multadd(b, 10, 0);      /* we botched the k estimate */
2635
5.07k
            if (b == NULL)
2636
0
                goto failed_malloc;
2637
5.07k
            if (leftright) {
2638
5.07k
                mhi = multadd(mhi, 10, 0);
2639
5.07k
                if (mhi == NULL)
2640
0
                    goto failed_malloc;
2641
5.07k
            }
2642
5.07k
            ilim = ilim1;
2643
5.07k
        }
2644
25.5k
    }
2645
33.5k
    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
33.5k
    if (leftright) {
2665
33.5k
        if (m2 > 0) {
2666
32.0k
            mhi = lshift(mhi, m2);
2667
32.0k
            if (mhi == NULL)
2668
0
                goto failed_malloc;
2669
32.0k
        }
2670
2671
        /* Compute mlo -- check for special case
2672
         * that d is a normalized power of 2.
2673
         */
2674
2675
33.5k
        mlo = mhi;
2676
33.5k
        if (spec_case) {
2677
1.21k
            mhi = Balloc(mhi->k);
2678
1.21k
            if (mhi == NULL)
2679
0
                goto failed_malloc;
2680
1.21k
            Bcopy(mhi, mlo);
2681
1.21k
            mhi = lshift(mhi, Log2P);
2682
1.21k
            if (mhi == NULL)
2683
0
                goto failed_malloc;
2684
1.21k
        }
2685
2686
127k
        for(i = 1;;i++) {
2687
127k
            dig = quorem(b,S) + '0';
2688
            /* Do we yet have the shortest decimal string
2689
             * that will round to d?
2690
             */
2691
127k
            j = cmp(b, mlo);
2692
127k
            delta = diff(S, mhi);
2693
127k
            if (delta == NULL)
2694
0
                goto failed_malloc;
2695
127k
            j1 = delta->sign ? 1 : cmp(b, delta);
2696
127k
            Bfree(delta);
2697
127k
            if (j1 == 0 && mode != 1 && !(word1(&u) & 1)
2698
127k
                ) {
2699
1.92k
                if (dig == '9')
2700
393
                    goto round_9_up;
2701
1.53k
                if (j > 0)
2702
781
                    dig++;
2703
1.53k
                *s++ = dig;
2704
1.53k
                goto ret;
2705
1.92k
            }
2706
125k
            if (j < 0 || (j == 0 && mode != 1
2707
2.06k
                          && !(word1(&u) & 1)
2708
108k
                    )) {
2709
18.0k
                if (!b->x[0] && b->wds <= 1) {
2710
2.69k
                    goto accept_dig;
2711
2.69k
                }
2712
15.3k
                if (j1 > 0) {
2713
3.24k
                    b = lshift(b, 1);
2714
3.24k
                    if (b == NULL)
2715
0
                        goto failed_malloc;
2716
3.24k
                    j1 = cmp(b, S);
2717
3.24k
                    if ((j1 > 0 || (j1 == 0 && dig & 1))
2718
1.91k
                        && dig++ == '9')
2719
394
                        goto round_9_up;
2720
3.24k
                }
2721
17.6k
              accept_dig:
2722
17.6k
                *s++ = dig;
2723
17.6k
                goto ret;
2724
15.3k
            }
2725
107k
            if (j1 > 0) {
2726
13.5k
                if (dig == '9') { /* possible if i == 1 */
2727
5.01k
                  round_9_up:
2728
5.01k
                    *s++ = '9';
2729
5.01k
                    goto roundoff;
2730
4.22k
                }
2731
9.32k
                *s++ = dig + 1;
2732
9.32k
                goto ret;
2733
13.5k
            }
2734
93.9k
            *s++ = dig;
2735
93.9k
            if (i == ilim)
2736
0
                break;
2737
93.9k
            b = multadd(b, 10, 0);
2738
93.9k
            if (b == NULL)
2739
0
                goto failed_malloc;
2740
93.9k
            if (mlo == mhi) {
2741
89.2k
                mlo = mhi = multadd(mhi, 10, 0);
2742
89.2k
                if (mlo == NULL)
2743
0
                    goto failed_malloc;
2744
89.2k
            }
2745
4.70k
            else {
2746
4.70k
                mlo = multadd(mlo, 10, 0);
2747
4.70k
                if (mlo == NULL)
2748
0
                    goto failed_malloc;
2749
4.70k
                mhi = multadd(mhi, 10, 0);
2750
4.70k
                if (mhi == NULL)
2751
0
                    goto failed_malloc;
2752
4.70k
            }
2753
93.9k
        }
2754
33.5k
    }
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
5.01k
      roundoff:
2776
5.01k
        while(*--s == '9')
2777
5.01k
            if (s == s0) {
2778
5.01k
                k++;
2779
5.01k
                *s++ = '1';
2780
5.01k
                goto ret;
2781
5.01k
            }
2782
0
        ++*s++;
2783
0
    }
2784
0
    else {
2785
0
        while(*--s == '0');
2786
0
        s++;
2787
0
    }
2788
33.5k
  ret:
2789
33.5k
    Bfree(S);
2790
33.5k
    if (mhi) {
2791
33.5k
        if (mlo && mlo != mhi)
2792
1.21k
            Bfree(mlo);
2793
33.5k
        Bfree(mhi);
2794
33.5k
    }
2795
41.7k
  ret1:
2796
41.7k
    Bfree(b);
2797
41.7k
    *s = 0;
2798
41.7k
    *decpt = k + 1;
2799
41.7k
    if (rve)
2800
41.7k
        *rve = s;
2801
41.7k
    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
33.5k
}
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
}