Coverage Report

Created: 2026-11-20 06:19

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython3/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
56
#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
1.28M
#define word0(x) (x)->L[1]
183
663k
#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
2.38M
#define dval(x) (x)->d
189
190
#ifndef STRTOD_DIGLIM
191
94.9k
#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
113k
#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
774k
#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
210k
#define Exp_shift  20
237
64.3k
#define Exp_shift1 20
238
567k
#define Exp_msk1    0x100000
239
#define Exp_msk11   0x100000
240
554k
#define Exp_mask  0x7ff00000
241
381k
#define P 53
242
#define Nbits 53
243
203k
#define Bias 1023
244
#define Emax 1023
245
#define Emin (-1022)
246
376k
#define Etiny (-1074)  /* smallest denormal is 2**Etiny */
247
142k
#define Exp_1  0x3ff00000
248
27.3k
#define Exp_11 0x3ff00000
249
310k
#define Ebits 11
250
183k
#define Frac_mask  0xfffff
251
32.5k
#define Frac_mask1 0xfffff
252
161k
#define Ten_pmax 22
253
0
#define Bletch 0x10
254
71.5k
#define Bndry_mask  0xfffff
255
18.1k
#define Bndry_mask1 0xfffff
256
39.0k
#define Sign_bit 0x80000000
257
5.55k
#define Log2P 1
258
#define Tiny0 0
259
16.2k
#define Tiny1 1
260
32.1k
#define Quick_max 14
261
19.7k
#define Int_max 14
262
263
#ifndef Flt_Rounds
264
#ifdef FLT_ROUNDS
265
201k
#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
8.11k
#define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
274
5.15k
#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
18.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
6.43M
#define freelist interp->dtoa.freelist
338
316
#define private_mem interp->dtoa.preallocated
339
836
#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
1.60M
{
346
1.60M
    int x;
347
1.60M
    Bigint *rv;
348
1.60M
    unsigned int len;
349
1.60M
    PyInterpreterState *interp = _PyInterpreterState_GET();
350
351
1.60M
    if (k <= Bigint_Kmax && (rv = freelist[k]))
352
1.60M
        freelist[k] = rv->next;
353
316
    else {
354
316
        x = 1 << k;
355
316
        len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)
356
316
            /sizeof(double);
357
316
        if (k <= Bigint_Kmax &&
358
316
            pmem_next - private_mem + len <= (Py_ssize_t)Bigint_PREALLOC_SIZE
359
316
        ) {
360
260
            rv = (Bigint*)pmem_next;
361
260
            pmem_next += len;
362
260
        }
363
56
        else {
364
56
            rv = (Bigint*)MALLOC(len*sizeof(double));
365
56
            if (rv == NULL)
366
0
                return NULL;
367
56
        }
368
316
        rv->k = k;
369
316
        rv->maxwds = x;
370
316
    }
371
1.60M
    rv->sign = rv->wds = 0;
372
1.60M
    return rv;
373
1.60M
}
374
375
/* Free a Bigint allocated with Balloc */
376
377
static void
378
Bfree(Bigint *v)
379
2.43M
{
380
2.43M
    if (v) {
381
1.60M
        if (v->k > Bigint_Kmax)
382
0
            FREE((void*)v);
383
1.60M
        else {
384
1.60M
            PyInterpreterState *interp = _PyInterpreterState_GET();
385
1.60M
            v->next = freelist[v->k];
386
1.60M
            freelist[v->k] = v;
387
1.60M
        }
388
1.60M
    }
389
2.43M
}
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
136k
#define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign,   \
438
136k
                          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.36M
{
447
1.36M
    int i, wds;
448
1.36M
    ULong *x;
449
1.36M
    ULLong carry, y;
450
1.36M
    Bigint *b1;
451
452
1.36M
    wds = b->wds;
453
1.36M
    x = b->x;
454
1.36M
    i = 0;
455
1.36M
    carry = a;
456
4.56M
    do {
457
4.56M
        y = *x * (ULLong)m + carry;
458
4.56M
        carry = y >> 32;
459
4.56M
        *x++ = (ULong)(y & FFFFFFFF);
460
4.56M
    }
461
4.56M
    while(++i < wds);
462
1.36M
    if (carry) {
463
105k
        if (wds >= b->maxwds) {
464
2.51k
            b1 = Balloc(b->k+1);
465
2.51k
            if (b1 == NULL){
466
0
                Bfree(b);
467
0
                return NULL;
468
0
            }
469
2.51k
            Bcopy(b1, b);
470
2.51k
            Bfree(b);
471
2.51k
            b = b1;
472
2.51k
        }
473
105k
        b->x[wds++] = (ULong)carry;
474
105k
        b->wds = wds;
475
105k
    }
476
1.36M
    return b;
477
1.36M
}
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
94.9k
{
488
94.9k
    Bigint *b;
489
94.9k
    int i, k;
490
94.9k
    Long x, y;
491
492
94.9k
    x = (nd + 8) / 9;
493
188k
    for(k = 0, y = 1; x > y; y <<= 1, k++) ;
494
94.9k
    b = Balloc(k);
495
94.9k
    if (b == NULL)
496
0
        return NULL;
497
94.9k
    b->x[0] = y9;
498
94.9k
    b->wds = 1;
499
500
94.9k
    if (nd <= 9)
501
27.4k
      return b;
502
503
67.4k
    s += 9;
504
653k
    for (i = 9; i < nd0; i++) {
505
585k
        b = multadd(b, 10, *s++ - '0');
506
585k
        if (b == NULL)
507
0
            return NULL;
508
585k
    }
509
67.4k
    s++;
510
221k
    for(; i < nd; i++) {
511
153k
        b = multadd(b, 10, *s++ - '0');
512
153k
        if (b == NULL)
513
0
            return NULL;
514
153k
    }
515
67.4k
    return b;
516
67.4k
}
517
518
/* count leading 0 bits in the 32-bit integer x. */
519
520
static int
521
hi0bits(ULong x)
522
167k
{
523
167k
    int k = 0;
524
525
167k
    if (!(x & 0xffff0000)) {
526
92.0k
        k = 16;
527
92.0k
        x <<= 16;
528
92.0k
    }
529
167k
    if (!(x & 0xff000000)) {
530
107k
        k += 8;
531
107k
        x <<= 8;
532
107k
    }
533
167k
    if (!(x & 0xf0000000)) {
534
99.0k
        k += 4;
535
99.0k
        x <<= 4;
536
99.0k
    }
537
167k
    if (!(x & 0xc0000000)) {
538
83.1k
        k += 2;
539
83.1k
        x <<= 2;
540
83.1k
    }
541
167k
    if (!(x & 0x80000000)) {
542
109k
        k++;
543
109k
        if (!(x & 0x40000000))
544
0
            return 32;
545
109k
    }
546
167k
    return k;
547
167k
}
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
32.1k
{
555
32.1k
    int k;
556
32.1k
    ULong x = *y;
557
558
32.1k
    if (x & 7) {
559
18.0k
        if (x & 1)
560
7.61k
            return 0;
561
10.4k
        if (x & 2) {
562
9.19k
            *y = x >> 1;
563
9.19k
            return 1;
564
9.19k
        }
565
1.21k
        *y = x >> 2;
566
1.21k
        return 2;
567
10.4k
    }
568
14.1k
    k = 0;
569
14.1k
    if (!(x & 0xffff)) {
570
7.40k
        k = 16;
571
7.40k
        x >>= 16;
572
7.40k
    }
573
14.1k
    if (!(x & 0xff)) {
574
3.25k
        k += 8;
575
3.25k
        x >>= 8;
576
3.25k
    }
577
14.1k
    if (!(x & 0xf)) {
578
6.50k
        k += 4;
579
6.50k
        x >>= 4;
580
6.50k
    }
581
14.1k
    if (!(x & 0x3)) {
582
6.10k
        k += 2;
583
6.10k
        x >>= 2;
584
6.10k
    }
585
14.1k
    if (!(x & 1)) {
586
6.47k
        k++;
587
6.47k
        x >>= 1;
588
6.47k
        if (!x)
589
0
            return 32;
590
6.47k
    }
591
14.1k
    *y = x;
592
14.1k
    return k;
593
14.1k
}
594
595
/* convert a small nonnegative integer to a Bigint */
596
597
static Bigint *
598
i2b(int i)
599
192k
{
600
192k
    Bigint *b;
601
602
192k
    b = Balloc(1);
603
192k
    if (b == NULL)
604
0
        return NULL;
605
192k
    b->x[0] = i;
606
192k
    b->wds = 1;
607
192k
    return b;
608
192k
}
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
357k
{
616
357k
    Bigint *c;
617
357k
    int k, wa, wb, wc;
618
357k
    ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
619
357k
    ULong y;
620
357k
    ULLong carry, z;
621
622
357k
    if ((!a->x[0] && a->wds == 1) || (!b->x[0] && b->wds == 1)) {
623
3.46k
        c = Balloc(0);
624
3.46k
        if (c == NULL)
625
0
            return NULL;
626
3.46k
        c->wds = 1;
627
3.46k
        c->x[0] = 0;
628
3.46k
        return c;
629
3.46k
    }
630
631
353k
    if (a->wds < b->wds) {
632
163k
        c = a;
633
163k
        a = b;
634
163k
        b = c;
635
163k
    }
636
353k
    k = a->k;
637
353k
    wa = a->wds;
638
353k
    wb = b->wds;
639
353k
    wc = wa + wb;
640
353k
    if (wc > a->maxwds)
641
137k
        k++;
642
353k
    c = Balloc(k);
643
353k
    if (c == NULL)
644
0
        return NULL;
645
3.41M
    for(x = c->x, xa = x + wc; x < xa; x++)
646
3.05M
        *x = 0;
647
353k
    xa = a->x;
648
353k
    xae = xa + wa;
649
353k
    xb = b->x;
650
353k
    xbe = xb + wb;
651
353k
    xc0 = c->x;
652
1.08M
    for(; xb < xbe; xc0++) {
653
734k
        if ((y = *xb++)) {
654
728k
            x = xa;
655
728k
            xc = xc0;
656
728k
            carry = 0;
657
7.44M
            do {
658
7.44M
                z = *x++ * (ULLong)y + *xc + carry;
659
7.44M
                carry = z >> 32;
660
7.44M
                *xc++ = (ULong)(z & FFFFFFFF);
661
7.44M
            }
662
7.44M
            while(x < xae);
663
728k
            *xc = (ULong)carry;
664
728k
        }
665
734k
    }
666
595k
    for(xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ;
667
353k
    c->wds = wc;
668
353k
    return c;
669
353k
}
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
134k
{
680
134k
    Bigint *b1, *p5, **p5s;
681
134k
    int i;
682
134k
    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
134k
    assert(0 <= k && k < 1024);
690
691
134k
    if ((i = k & 3)) {
692
107k
        b = multadd(b, p05[i-1], 0);
693
107k
        if (b == NULL)
694
0
            return NULL;
695
107k
    }
696
697
134k
    if (!(k >>= 2))
698
11.2k
        return b;
699
123k
    PyInterpreterState *interp = _PyInterpreterState_GET();
700
123k
    p5s = interp->dtoa.p5s;
701
574k
    for(;;) {
702
574k
        assert(p5s != interp->dtoa.p5s + Bigint_Pow5size);
703
574k
        p5 = *p5s;
704
574k
        p5s++;
705
574k
        if (k & 1) {
706
292k
            b1 = mult(b, p5);
707
292k
            Bfree(b);
708
292k
            b = b1;
709
292k
            if (b == NULL)
710
0
                return NULL;
711
292k
        }
712
574k
        if (!(k >>= 1))
713
123k
            break;
714
574k
    }
715
123k
    return b;
716
123k
}
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
367k
{
777
367k
    int i, k1, n, n1;
778
367k
    Bigint *b1;
779
367k
    ULong *x, *x1, *xe, z;
780
781
367k
    if (!k || (!b->x[0] && b->wds == 1))
782
3.94k
        return b;
783
784
363k
    n = k >> 5;
785
363k
    k1 = b->k;
786
363k
    n1 = n + b->wds + 1;
787
813k
    for(i = b->maxwds; n1 > i; i <<= 1)
788
450k
        k1++;
789
363k
    b1 = Balloc(k1);
790
363k
    if (b1 == NULL) {
791
0
        Bfree(b);
792
0
        return NULL;
793
0
    }
794
363k
    x1 = b1->x;
795
1.76M
    for(i = 0; i < n; i++)
796
1.40M
        *x1++ = 0;
797
363k
    x = b->x;
798
363k
    xe = x + b->wds;
799
363k
    if (k &= 0x1f) {
800
358k
        k1 = 32 - k;
801
358k
        z = 0;
802
1.58M
        do {
803
1.58M
            *x1++ = *x << k | z;
804
1.58M
            z = *x++ >> k1;
805
1.58M
        }
806
1.58M
        while(x < xe);
807
358k
        if ((*x1 = z))
808
66.0k
            ++n1;
809
358k
    }
810
4.59k
    else do
811
10.7k
             *x1++ = *x++;
812
10.7k
        while(x < xe);
813
363k
    b1->wds = n1 - 1;
814
363k
    Bfree(b);
815
363k
    return b1;
816
363k
}
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.06M
{
824
1.06M
    ULong *xa, *xa0, *xb, *xb0;
825
1.06M
    int i, j;
826
827
1.06M
    i = a->wds;
828
1.06M
    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.06M
    if (i -= j)
836
135k
        return i;
837
930k
    xa0 = a->x;
838
930k
    xa = xa0 + j;
839
930k
    xb0 = b->x;
840
930k
    xb = xb0 + j;
841
1.11M
    for(;;) {
842
1.11M
        if (*--xa != *--xb)
843
902k
            return *xa < *xb ? -1 : 1;
844
209k
        if (xa <= xa0)
845
28.3k
            break;
846
209k
    }
847
28.3k
    return 0;
848
930k
}
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
242k
{
857
242k
    Bigint *c;
858
242k
    int i, wa, wb;
859
242k
    ULong *xa, *xae, *xb, *xbe, *xc;
860
242k
    ULLong borrow, y;
861
862
242k
    i = cmp(a,b);
863
242k
    if (!i) {
864
2.95k
        c = Balloc(0);
865
2.95k
        if (c == NULL)
866
0
            return NULL;
867
2.95k
        c->wds = 1;
868
2.95k
        c->x[0] = 0;
869
2.95k
        return c;
870
2.95k
    }
871
239k
    if (i < 0) {
872
81.3k
        c = a;
873
81.3k
        a = b;
874
81.3k
        b = c;
875
81.3k
        i = 1;
876
81.3k
    }
877
158k
    else
878
158k
        i = 0;
879
239k
    c = Balloc(a->k);
880
239k
    if (c == NULL)
881
0
        return NULL;
882
239k
    c->sign = i;
883
239k
    wa = a->wds;
884
239k
    xa = a->x;
885
239k
    xae = xa + wa;
886
239k
    wb = b->wds;
887
239k
    xb = b->x;
888
239k
    xbe = xb + wb;
889
239k
    xc = c->x;
890
239k
    borrow = 0;
891
1.73M
    do {
892
1.73M
        y = (ULLong)*xa++ - *xb++ - borrow;
893
1.73M
        borrow = y >> 32 & (ULong)1;
894
1.73M
        *xc++ = (ULong)(y & FFFFFFFF);
895
1.73M
    }
896
1.73M
    while(xb < xbe);
897
395k
    while(xa < xae) {
898
155k
        y = *xa++ - borrow;
899
155k
        borrow = y >> 32 & (ULong)1;
900
155k
        *xc++ = (ULong)(y & FFFFFFFF);
901
155k
    }
902
415k
    while(!*--xc)
903
175k
        wa--;
904
239k
    c->wds = wa;
905
239k
    return c;
906
239k
}
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
80.8k
{
914
80.8k
    Long L;
915
80.8k
    U u;
916
917
80.8k
    L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1;
918
80.8k
    word0(&u) = L;
919
80.8k
    word1(&u) = 0;
920
80.8k
    return dval(&u);
921
80.8k
}
922
923
/* Convert a Bigint to a double plus an exponent */
924
925
static double
926
b2d(Bigint *a, int *e)
927
124k
{
928
124k
    ULong *xa, *xa0, w, y, z;
929
124k
    int k;
930
124k
    U d;
931
932
124k
    xa0 = a->x;
933
124k
    xa = xa0 + a->wds;
934
124k
    y = *--xa;
935
#ifdef DEBUG
936
    if (!y) Bug("zero y in b2d");
937
#endif
938
124k
    k = hi0bits(y);
939
124k
    *e = 32 - k;
940
124k
    if (k < Ebits) {
941
31.0k
        word0(&d) = Exp_1 | y >> (Ebits - k);
942
31.0k
        w = xa > xa0 ? *--xa : 0;
943
31.0k
        word1(&d) = y << ((32-Ebits) + k) | w >> (Ebits - k);
944
31.0k
        goto ret_d;
945
31.0k
    }
946
93.3k
    z = xa > xa0 ? *--xa : 0;
947
93.3k
    if (k -= Ebits) {
948
77.9k
        word0(&d) = Exp_1 | y << k | z >> (32 - k);
949
77.9k
        y = xa > xa0 ? *--xa : 0;
950
77.9k
        word1(&d) = z << k | y >> (32 - k);
951
77.9k
    }
952
15.4k
    else {
953
15.4k
        word0(&d) = Exp_1 | y;
954
15.4k
        word1(&d) = z;
955
15.4k
    }
956
124k
  ret_d:
957
124k
    return dval(&d);
958
93.3k
}
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
151k
{
984
151k
    Bigint *b;
985
986
151k
    b = Balloc(1);
987
151k
    if (b == NULL)
988
0
        return NULL;
989
990
    /* First construct b and e assuming that scale == 0. */
991
151k
    b->wds = 2;
992
151k
    b->x[0] = word1(d);
993
151k
    b->x[1] = word0(d) & Frac_mask;
994
151k
    *e = Etiny - 1 + (int)((word0(d) & Exp_mask) >> Exp_shift);
995
151k
    if (*e < Etiny)
996
3.94k
        *e = Etiny;
997
147k
    else
998
147k
        b->x[1] |= Exp_msk1;
999
1000
    /* Now adjust for scale, provided that b != 0. */
1001
151k
    if (scale && (b->x[0] || b->x[1])) {
1002
27.9k
        *e -= scale;
1003
27.9k
        if (*e < Etiny) {
1004
20.7k
            scale = Etiny - *e;
1005
20.7k
            *e = Etiny;
1006
            /* We can't shift more than P-1 bits without shifting out a 1. */
1007
20.7k
            assert(0 < scale && scale <= P - 1);
1008
20.7k
            if (scale >= 32) {
1009
                /* The bits shifted out should all be zero. */
1010
14.2k
                assert(b->x[0] == 0);
1011
14.2k
                b->x[0] = b->x[1];
1012
14.2k
                b->x[1] = 0;
1013
14.2k
                scale -= 32;
1014
14.2k
            }
1015
20.7k
            if (scale) {
1016
                /* The bits shifted out should all be zero. */
1017
19.9k
                assert(b->x[0] << (32 - scale) == 0);
1018
19.9k
                b->x[0] = (b->x[0] >> scale) | (b->x[1] << (32 - scale));
1019
19.9k
                b->x[1] >>= scale;
1020
19.9k
            }
1021
20.7k
        }
1022
27.9k
    }
1023
    /* Ensure b is normalized. */
1024
151k
    if (!b->x[1])
1025
19.5k
        b->wds = 1;
1026
1027
151k
    return b;
1028
151k
}
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
32.1k
{
1042
32.1k
    Bigint *b;
1043
32.1k
    int de, k;
1044
32.1k
    ULong *x, y, z;
1045
32.1k
    int i;
1046
1047
32.1k
    b = Balloc(1);
1048
32.1k
    if (b == NULL)
1049
0
        return NULL;
1050
32.1k
    x = b->x;
1051
1052
32.1k
    z = word0(d) & Frac_mask;
1053
32.1k
    word0(d) &= 0x7fffffff;   /* clear sign bit, which we ignore */
1054
32.1k
    if ((de = (int)(word0(d) >> Exp_shift)))
1055
27.3k
        z |= Exp_msk1;
1056
32.1k
    if ((y = word1(d))) {
1057
21.7k
        if ((k = lo0bits(&y))) {
1058
14.4k
            x[0] = y | z << (32 - k);
1059
14.4k
            z >>= k;
1060
14.4k
        }
1061
7.29k
        else
1062
7.29k
            x[0] = y;
1063
21.7k
        i =
1064
21.7k
            b->wds = (x[1] = z) ? 2 : 1;
1065
21.7k
    }
1066
10.4k
    else {
1067
10.4k
        k = lo0bits(&z);
1068
10.4k
        x[0] = z;
1069
10.4k
        i =
1070
10.4k
            b->wds = 1;
1071
10.4k
        k += 32;
1072
10.4k
    }
1073
32.1k
    if (de) {
1074
27.3k
        *e = de - Bias - (P-1) + k;
1075
27.3k
        *bits = P - k;
1076
27.3k
    }
1077
4.80k
    else {
1078
4.80k
        *e = de - Bias - (P-1) + 1 + k;
1079
4.80k
        *bits = 32*i - hi0bits(x[i-1]);
1080
4.80k
    }
1081
32.1k
    return b;
1082
32.1k
}
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
62.1k
{
1090
62.1k
    U da, db;
1091
62.1k
    int k, ka, kb;
1092
1093
62.1k
    dval(&da) = b2d(a, &ka);
1094
62.1k
    dval(&db) = b2d(b, &kb);
1095
62.1k
    k = ka - kb + 32*(a->wds - b->wds);
1096
62.1k
    if (k > 0)
1097
38.4k
        word0(&da) += k*Exp_msk1;
1098
23.7k
    else {
1099
23.7k
        k = -k;
1100
23.7k
        word0(&db) += k*Exp_msk1;
1101
23.7k
    }
1102
62.1k
    return dval(&da) / dval(&db);
1103
62.1k
}
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
25.7k
#define Scale_Bit 0x10
1121
30.9k
#define n_bigtens 5
1122
1123
#define ULbits 32
1124
#define kshift 5
1125
38.5k
#define kmask 31
1126
1127
1128
static int
1129
dshift(Bigint *b, int p2)
1130
38.5k
{
1131
38.5k
    int rv = hi0bits(b->x[b->wds-1]) - 4;
1132
38.5k
    if (p2 > 0)
1133
21.3k
        rv -= p2;
1134
38.5k
    return rv & kmask;
1135
38.5k
}
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
443k
{
1144
443k
    int n;
1145
443k
    ULong *bx, *bxe, q, *sx, *sxe;
1146
443k
    ULLong borrow, carry, y, ys;
1147
1148
443k
    n = S->wds;
1149
#ifdef DEBUG
1150
    /*debug*/ if (b->wds > n)
1151
        /*debug*/       Bug("oversize b in quorem");
1152
#endif
1153
443k
    if (b->wds < n)
1154
9.58k
        return 0;
1155
433k
    sx = S->x;
1156
433k
    sxe = sx + --n;
1157
433k
    bx = b->x;
1158
433k
    bxe = bx + n;
1159
433k
    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
433k
    if (q) {
1165
350k
        borrow = 0;
1166
350k
        carry = 0;
1167
2.08M
        do {
1168
2.08M
            ys = *sx++ * (ULLong)q + carry;
1169
2.08M
            carry = ys >> 32;
1170
2.08M
            y = *bx - (ys & FFFFFFFF) - borrow;
1171
2.08M
            borrow = y >> 32 & (ULong)1;
1172
2.08M
            *bx++ = (ULong)(y & FFFFFFFF);
1173
2.08M
        }
1174
2.08M
        while(sx <= sxe);
1175
350k
        if (!*bxe) {
1176
1.01k
            bx = b->x;
1177
1.01k
            while(--bxe > bx && !*bxe)
1178
0
                --n;
1179
1.01k
            b->wds = n;
1180
1.01k
        }
1181
350k
    }
1182
433k
    if (cmp(b, S) >= 0) {
1183
12.0k
        q++;
1184
12.0k
        borrow = 0;
1185
12.0k
        carry = 0;
1186
12.0k
        bx = b->x;
1187
12.0k
        sx = S->x;
1188
49.4k
        do {
1189
49.4k
            ys = *sx++ + carry;
1190
49.4k
            carry = ys >> 32;
1191
49.4k
            y = *bx - (ys & FFFFFFFF) - borrow;
1192
49.4k
            borrow = y >> 32 & (ULong)1;
1193
49.4k
            *bx++ = (ULong)(y & FFFFFFFF);
1194
49.4k
        }
1195
49.4k
        while(sx <= sxe);
1196
12.0k
        bx = b->x;
1197
12.0k
        bxe = bx + n;
1198
12.0k
        if (!*bxe) {
1199
13.7k
            while(--bxe > bx && !*bxe)
1200
2.70k
                --n;
1201
11.0k
            b->wds = n;
1202
11.0k
        }
1203
12.0k
    }
1204
433k
    return q;
1205
443k
}
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
19.2k
{
1216
19.2k
    U u;
1217
1218
19.2k
    if (bc->scale && 2*P + 1 > (int)((word0(x) & Exp_mask) >> Exp_shift)) {
1219
        /* rv/2^bc->scale is subnormal */
1220
531
        word0(&u) = (P+2)*Exp_msk1;
1221
531
        word1(&u) = 0;
1222
531
        return u.d;
1223
531
    }
1224
18.6k
    else {
1225
18.6k
        assert(word0(x) || word1(x)); /* x != 0.0 */
1226
18.6k
        return ulp(x);
1227
18.6k
    }
1228
19.2k
}
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
18.0k
{
1279
18.0k
    Bigint *b, *d;
1280
18.0k
    int b2, d2, dd, i, nd, nd0, odd, p2, p5;
1281
1282
18.0k
    nd = bc->nd;
1283
18.0k
    nd0 = bc->nd0;
1284
18.0k
    p5 = nd + bc->e0;
1285
18.0k
    b = sd2b(rv, bc->scale, &p2);
1286
18.0k
    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
18.0k
    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
18.0k
    b = lshift(b, 1);
1296
18.0k
    if (b == NULL)
1297
0
        return -1;
1298
18.0k
    b->x[0] |= 1;
1299
18.0k
    p2--;
1300
1301
18.0k
    p2 -= p5;
1302
18.0k
    d = i2b(1);
1303
18.0k
    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
18.0k
    if (p5 > 0) {
1311
14.3k
        d = pow5mult(d, p5);
1312
14.3k
        if (d == NULL) {
1313
0
            Bfree(b);
1314
0
            return -1;
1315
0
        }
1316
14.3k
    }
1317
3.69k
    else if (p5 < 0) {
1318
2.74k
        b = pow5mult(b, -p5);
1319
2.74k
        if (b == NULL) {
1320
0
            Bfree(d);
1321
0
            return -1;
1322
0
        }
1323
2.74k
    }
1324
18.0k
    if (p2 > 0) {
1325
11.9k
        b2 = p2;
1326
11.9k
        d2 = 0;
1327
11.9k
    }
1328
6.14k
    else {
1329
6.14k
        b2 = 0;
1330
6.14k
        d2 = -p2;
1331
6.14k
    }
1332
18.0k
    i = dshift(d, d2);
1333
18.0k
    if ((b2 += i) > 0) {
1334
17.7k
        b = lshift(b, b2);
1335
17.7k
        if (b == NULL) {
1336
0
            Bfree(d);
1337
0
            return -1;
1338
0
        }
1339
17.7k
    }
1340
18.0k
    if ((d2 += i) > 0) {
1341
17.2k
        d = lshift(d, d2);
1342
17.2k
        if (d == NULL) {
1343
0
            Bfree(b);
1344
0
            return -1;
1345
0
        }
1346
17.2k
    }
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
18.0k
    if (cmp(b, d) >= 0)
1352
        /* b/d >= 1 */
1353
1.00k
        dd = -1;
1354
17.0k
    else {
1355
17.0k
        i = 0;
1356
334k
        for(;;) {
1357
334k
            b = multadd(b, 10, 0);
1358
334k
            if (b == NULL) {
1359
0
                Bfree(d);
1360
0
                return -1;
1361
0
            }
1362
334k
            dd = s0[i < nd0 ? i : i+1] - '0' - quorem(b, d);
1363
334k
            i++;
1364
1365
334k
            if (dd)
1366
14.5k
                break;
1367
319k
            if (!b->x[0] && b->wds == 1) {
1368
                /* b/d == 0 */
1369
2.04k
                dd = i < nd;
1370
2.04k
                break;
1371
2.04k
            }
1372
317k
            if (!(i < nd)) {
1373
                /* b/d != 0, but digits of s0 exhausted */
1374
447
                dd = -1;
1375
447
                break;
1376
447
            }
1377
317k
        }
1378
17.0k
    }
1379
18.0k
    Bfree(b);
1380
18.0k
    Bfree(d);
1381
18.0k
    if (dd > 0 || (dd == 0 && odd))
1382
8.69k
        dval(rv) += sulp(rv, bc);
1383
18.0k
    return 0;
1384
18.0k
}
1385
1386
1387
double
1388
_Py_dg_strtod(const char *s00, char **se)
1389
260k
{
1390
260k
    int bb2, bb5, bbe, bd2, bd5, bs2, c, dsign, e, e1, error;
1391
260k
    int esign, i, j, k, lz, nd, nd0, odd, sign;
1392
260k
    const char *s, *s0, *s1;
1393
260k
    double aadj, aadj1;
1394
260k
    U aadj2, adj, rv, rv0;
1395
260k
    ULong y, z, abs_exp;
1396
260k
    Long L;
1397
260k
    BCinfo bc;
1398
260k
    Bigint *bb = NULL, *bd = NULL, *bd0 = NULL, *bs = NULL, *delta = NULL;
1399
260k
    size_t ndigits, fraclen;
1400
260k
    double result;
1401
1402
260k
    dval(&rv) = 0.;
1403
1404
    /* Start parsing. */
1405
260k
    c = *(s = s00);
1406
1407
    /* Parse optional sign, if present. */
1408
260k
    sign = 0;
1409
260k
    switch (c) {
1410
8.62k
    case '-':
1411
8.62k
        sign = 1;
1412
8.62k
        _Py_FALLTHROUGH;
1413
8.63k
    case '+':
1414
8.63k
        c = *++s;
1415
260k
    }
1416
1417
    /* Skip leading zeros: lz is true iff there were leading zeros. */
1418
260k
    s1 = s;
1419
294k
    while (c == '0')
1420
34.7k
        c = *++s;
1421
260k
    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
260k
    s0 = s1 = s;
1428
14.6M
    while ('0' <= c && c <= '9')
1429
14.3M
        c = *++s;
1430
260k
    ndigits = s - s1;
1431
260k
    fraclen = 0;
1432
1433
    /* Parse decimal point and following digits. */
1434
260k
    if (c == '.') {
1435
107k
        c = *++s;
1436
107k
        if (!ndigits) {
1437
23.5k
            s1 = s;
1438
1.69M
            while (c == '0')
1439
1.66M
                c = *++s;
1440
23.5k
            lz = lz || s != s1;
1441
23.5k
            fraclen += (s - s1);
1442
23.5k
            s0 = s;
1443
23.5k
        }
1444
107k
        s1 = s;
1445
32.9M
        while ('0' <= c && c <= '9')
1446
32.8M
            c = *++s;
1447
107k
        ndigits += s - s1;
1448
107k
        fraclen += s - s1;
1449
107k
    }
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
260k
    if (!ndigits && !lz) {
1455
1.85k
        if (se)
1456
1.85k
            *se = (char *)s00;
1457
1.85k
        goto parse_error;
1458
1.85k
    }
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
258k
    if (ndigits > MAX_DIGITS || fraclen > MAX_DIGITS) {
1463
0
        if (se)
1464
0
            *se = (char *)s00;
1465
0
        goto parse_error;
1466
0
    }
1467
258k
    nd = (int)ndigits;
1468
258k
    nd0 = (int)ndigits - (int)fraclen;
1469
1470
    /* Parse exponent. */
1471
258k
    e = 0;
1472
258k
    if (c == 'e' || c == 'E') {
1473
113k
        s00 = s;
1474
113k
        c = *++s;
1475
1476
        /* Exponent sign. */
1477
113k
        esign = 0;
1478
113k
        switch (c) {
1479
33.7k
        case '-':
1480
33.7k
            esign = 1;
1481
33.7k
            _Py_FALLTHROUGH;
1482
34.7k
        case '+':
1483
34.7k
            c = *++s;
1484
113k
        }
1485
1486
        /* Skip zeros.  lz is true iff there are leading zeros. */
1487
113k
        s1 = s;
1488
171k
        while (c == '0')
1489
58.6k
            c = *++s;
1490
113k
        lz = s != s1;
1491
1492
        /* Get absolute value of the exponent. */
1493
113k
        s1 = s;
1494
113k
        abs_exp = 0;
1495
2.73M
        while ('0' <= c && c <= '9') {
1496
2.62M
            abs_exp = 10*abs_exp + (c - '0');
1497
2.62M
            c = *++s;
1498
2.62M
        }
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
113k
        if (s - s1 > 9 || abs_exp > MAX_ABS_EXP)
1504
2.04k
            e = (int)MAX_ABS_EXP;
1505
111k
        else
1506
111k
            e = (int)abs_exp;
1507
113k
        if (esign)
1508
33.7k
            e = -e;
1509
1510
        /* A valid exponent must have at least one digit. */
1511
113k
        if (s == s1 && !lz)
1512
22
            s = s00;
1513
113k
    }
1514
1515
    /* Adjust exponent to take into account position of the point. */
1516
258k
    e -= nd - nd0;
1517
258k
    if (nd0 <= 0)
1518
33.5k
        nd0 = nd;
1519
1520
    /* Finished parsing.  Set se to indicate how far we parsed */
1521
258k
    if (se)
1522
258k
        *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
258k
    if (!nd)
1527
15.6k
        goto ret;
1528
8.68M
    for (i = nd; i > 0; ) {
1529
8.68M
        --i;
1530
8.68M
        if (s0[i < nd0 ? i : i+1] != '0') {
1531
242k
            ++i;
1532
242k
            break;
1533
242k
        }
1534
8.68M
    }
1535
242k
    e += nd - i;
1536
242k
    nd = i;
1537
242k
    if (nd0 > nd)
1538
10.3k
        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
242k
    bc.e0 = e1 = e;
1577
242k
    y = z = 0;
1578
1.99M
    for (i = 0; i < nd; i++) {
1579
1.82M
        if (i < 9)
1580
1.16M
            y = 10*y + s0[i < nd0 ? i : i+1] - '0';
1581
660k
        else if (i < DBL_DIG+1)
1582
596k
            z = 10*z + s0[i < nd0 ? i : i+1] - '0';
1583
64.6k
        else
1584
64.6k
            break;
1585
1.82M
    }
1586
1587
242k
    k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;
1588
242k
    dval(&rv) = y;
1589
242k
    if (k > 9) {
1590
96.8k
        dval(&rv) = tens[k - 9] * dval(&rv) + z;
1591
96.8k
    }
1592
242k
    if (nd <= DBL_DIG
1593
171k
        && Flt_Rounds == 1
1594
242k
        ) {
1595
171k
        if (!e)
1596
62.1k
            goto ret;
1597
109k
        if (e > 0) {
1598
42.4k
            if (e <= Ten_pmax) {
1599
12.3k
                dval(&rv) *= tens[e];
1600
12.3k
                goto ret;
1601
12.3k
            }
1602
30.1k
            i = DBL_DIG - nd;
1603
30.1k
            if (e <= Ten_pmax + i) {
1604
                /* A fancier test would sometimes let us do
1605
                 * this for larger i values.
1606
                 */
1607
4.30k
                e -= i;
1608
4.30k
                dval(&rv) *= tens[i];
1609
4.30k
                dval(&rv) *= tens[e];
1610
4.30k
                goto ret;
1611
4.30k
            }
1612
30.1k
        }
1613
66.5k
        else if (e >= -Ten_pmax) {
1614
45.6k
            dval(&rv) /= tens[-e];
1615
45.6k
            goto ret;
1616
45.6k
        }
1617
109k
    }
1618
118k
    e1 += nd - k;
1619
1620
118k
    bc.scale = 0;
1621
1622
    /* Get starting approximation = rv * 10**e1 */
1623
1624
118k
    if (e1 > 0) {
1625
72.7k
        if ((i = e1 & 15))
1626
69.3k
            dval(&rv) *= tens[i];
1627
72.7k
        if (e1 &= ~15) {
1628
47.1k
            if (e1 > DBL_MAX_10_EXP)
1629
17.2k
                goto ovfl;
1630
29.8k
            e1 >>= 4;
1631
74.4k
            for(j = 0; e1 > 1; j++, e1 >>= 1)
1632
44.5k
                if (e1 & 1)
1633
17.6k
                    dval(&rv) *= bigtens[j];
1634
            /* The last multiplication could overflow. */
1635
29.8k
            word0(&rv) -= P*Exp_msk1;
1636
29.8k
            dval(&rv) *= bigtens[j];
1637
29.8k
            if ((z = word0(&rv) & Exp_mask)
1638
29.8k
                > Exp_msk1*(DBL_MAX_EXP+Bias-P))
1639
638
                goto ovfl;
1640
29.2k
            if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) {
1641
                /* set to largest number */
1642
                /* (Can't trust DBL_MAX) */
1643
1.43k
                word0(&rv) = Big0;
1644
1.43k
                word1(&rv) = Big1;
1645
1.43k
            }
1646
27.7k
            else
1647
27.7k
                word0(&rv) += P*Exp_msk1;
1648
29.2k
        }
1649
72.7k
    }
1650
45.3k
    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
41.1k
        e1 = -e1;
1662
41.1k
        if ((i = e1 & 15))
1663
34.2k
            dval(&rv) /= tens[i];
1664
41.1k
        if (e1 >>= 4) {
1665
30.9k
            if (e1 >= 1 << n_bigtens)
1666
5.20k
                goto undfl;
1667
25.7k
            if (e1 & Scale_Bit)
1668
17.6k
                bc.scale = 2*P;
1669
127k
            for(j = 0; e1 > 0; j++, e1 >>= 1)
1670
101k
                if (e1 & 1)
1671
51.7k
                    dval(&rv) *= tinytens[j];
1672
25.7k
            if (bc.scale && (j = 2*P + 1 - ((word0(&rv) & Exp_mask)
1673
17.6k
                                            >> Exp_shift)) > 0) {
1674
                /* scaled rv is denormal; clear j low bits */
1675
13.9k
                if (j >= 32) {
1676
10.6k
                    word1(&rv) = 0;
1677
10.6k
                    if (j >= 53)
1678
3.90k
                        word0(&rv) = (P+2)*Exp_msk1;
1679
6.73k
                    else
1680
6.73k
                        word0(&rv) &= 0xffffffff << (j-32);
1681
10.6k
                }
1682
3.29k
                else
1683
3.29k
                    word1(&rv) &= 0xffffffff << j;
1684
13.9k
            }
1685
25.7k
            if (!dval(&rv))
1686
0
                goto undfl;
1687
25.7k
        }
1688
41.1k
    }
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
94.9k
    bc.nd = nd;
1695
94.9k
    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
94.9k
    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
83.8k
        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
83.8k
            --i;
1710
83.8k
            if (s0[i < nd0 ? i : i+1] != '0') {
1711
22.2k
                ++i;
1712
22.2k
                break;
1713
22.2k
            }
1714
83.8k
        }
1715
22.2k
        e += nd - i;
1716
22.2k
        nd = i;
1717
22.2k
        if (nd0 > nd)
1718
17.1k
            nd0 = nd;
1719
22.2k
        if (nd < 9) { /* must recompute y */
1720
3.49k
            y = 0;
1721
17.7k
            for(i = 0; i < nd0; ++i)
1722
14.2k
                y = 10*y + s0[i] - '0';
1723
6.16k
            for(; i < nd; ++i)
1724
2.66k
                y = 10*y + s0[i+1] - '0';
1725
3.49k
        }
1726
22.2k
    }
1727
94.9k
    bd0 = s2b(s0, nd0, nd, y);
1728
94.9k
    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
133k
    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
133k
        bd = Balloc(bd0->k);
1760
133k
        if (bd == NULL) {
1761
0
            goto failed_malloc;
1762
0
        }
1763
133k
        Bcopy(bd, bd0);
1764
133k
        bb = sd2b(&rv, bc.scale, &bbe);   /* srv = bb * 2^bbe */
1765
133k
        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
133k
        odd = bb->x[0] & 1;
1771
1772
        /* tdv = bd * 10**e;  srv = bb * 2**bbe */
1773
133k
        bs = i2b(1);
1774
133k
        if (bs == NULL) {
1775
0
            goto failed_malloc;
1776
0
        }
1777
1778
133k
        if (e >= 0) {
1779
78.3k
            bb2 = bb5 = 0;
1780
78.3k
            bd2 = bd5 = e;
1781
78.3k
        }
1782
55.1k
        else {
1783
55.1k
            bb2 = bb5 = -e;
1784
55.1k
            bd2 = bd5 = 0;
1785
55.1k
        }
1786
133k
        if (bbe >= 0)
1787
82.2k
            bb2 += bbe;
1788
51.2k
        else
1789
51.2k
            bd2 -= bbe;
1790
133k
        bs2 = bb2;
1791
133k
        bb2++;
1792
133k
        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
133k
        i = bb2 < bd2 ? bb2 : bd2;
1813
133k
        if (i > bs2)
1814
50.3k
            i = bs2;
1815
133k
        if (i > 0) {
1816
131k
            bb2 -= i;
1817
131k
            bd2 -= i;
1818
131k
            bs2 -= i;
1819
131k
        }
1820
1821
        /* Scale bb, bd, bs by the appropriate powers of 2 and 5. */
1822
133k
        if (bb5 > 0) {
1823
55.1k
            bs = pow5mult(bs, bb5);
1824
55.1k
            if (bs == NULL) {
1825
0
                goto failed_malloc;
1826
0
            }
1827
55.1k
            Bigint *bb1 = mult(bs, bb);
1828
55.1k
            Bfree(bb);
1829
55.1k
            bb = bb1;
1830
55.1k
            if (bb == NULL) {
1831
0
                goto failed_malloc;
1832
0
            }
1833
55.1k
        }
1834
133k
        if (bb2 > 0) {
1835
133k
            bb = lshift(bb, bb2);
1836
133k
            if (bb == NULL) {
1837
0
                goto failed_malloc;
1838
0
            }
1839
133k
        }
1840
133k
        if (bd5 > 0) {
1841
42.9k
            bd = pow5mult(bd, bd5);
1842
42.9k
            if (bd == NULL) {
1843
0
                goto failed_malloc;
1844
0
            }
1845
42.9k
        }
1846
133k
        if (bd2 > 0) {
1847
50.3k
            bd = lshift(bd, bd2);
1848
50.3k
            if (bd == NULL) {
1849
0
                goto failed_malloc;
1850
0
            }
1851
50.3k
        }
1852
133k
        if (bs2 > 0) {
1853
60.6k
            bs = lshift(bs, bs2);
1854
60.6k
            if (bs == NULL) {
1855
0
                goto failed_malloc;
1856
0
            }
1857
60.6k
        }
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
133k
        delta = diff(bb, bd);
1864
133k
        if (delta == NULL) {
1865
0
            goto failed_malloc;
1866
0
        }
1867
133k
        dsign = delta->sign;
1868
133k
        delta->sign = 0;
1869
133k
        i = cmp(delta, bs);
1870
133k
        if (bc.nd > nd && i <= 0) {
1871
22.2k
            if (dsign)
1872
10.8k
                break;  /* Must use bigcomp(). */
1873
1874
            /* Here rv overestimates the truncated decimal value by at most
1875
               0.5 ulp(rv).  Hence rv either overestimates the true decimal
1876
               value by <= 0.5 ulp(rv), or underestimates it by some small
1877
               amount (< 0.1 ulp(rv)); either way, rv is within 0.5 ulps of
1878
               the true decimal value, so it's possible to exit.
1879
1880
               Exception: if scaled rv is a normal exact power of 2, but not
1881
               DBL_MIN, then rv - 0.5 ulp(rv) takes us all the way down to the
1882
               next double, so the correctly rounded result is either rv - 0.5
1883
               ulp(rv) or rv; in this case, use bigcomp to distinguish. */
1884
1885
11.3k
            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
7.42k
                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
7.42k
                if (j - bc.scale >= 2) {
1892
7.16k
                    dval(&rv) -= 0.5 * sulp(&rv, &bc);
1893
7.16k
                    break; /* Use bigcomp. */
1894
7.16k
                }
1895
7.42k
            }
1896
1897
4.23k
            {
1898
4.23k
                bc.nd = nd;
1899
4.23k
                i = -1; /* Discarded digits make delta smaller. */
1900
4.23k
            }
1901
4.23k
        }
1902
1903
115k
        if (i < 0) {
1904
            /* Error is less than half an ulp -- check for
1905
             * special case of mantissa a power of two.
1906
             */
1907
37.3k
            if (dsign || word1(&rv) || word0(&rv) & Bndry_mask
1908
6.47k
                || (word0(&rv) & Exp_mask) <= (2*P+1)*Exp_msk1
1909
37.3k
                ) {
1910
32.0k
                break;
1911
32.0k
            }
1912
5.32k
            if (!delta->x[0] && delta->wds <= 1) {
1913
                /* exact result */
1914
333
                break;
1915
333
            }
1916
4.99k
            delta = lshift(delta,Log2P);
1917
4.99k
            if (delta == NULL) {
1918
0
                goto failed_malloc;
1919
0
            }
1920
4.99k
            if (cmp(delta, bs) > 0)
1921
1.97k
                goto drop_down;
1922
3.02k
            break;
1923
4.99k
        }
1924
78.1k
        if (i == 0) {
1925
            /* exactly half-way between */
1926
15.9k
            if (dsign) {
1927
5.39k
                if ((word0(&rv) & Bndry_mask1) == Bndry_mask1
1928
2.97k
                    &&  word1(&rv) == (
1929
2.97k
                        (bc.scale &&
1930
0
                         (y = word0(&rv) & Exp_mask) <= 2*P*Exp_msk1) ?
1931
0
                        (0xffffffff & (0xffffffff << (2*P+1-(y>>Exp_shift)))) :
1932
2.97k
                        0xffffffff)) {
1933
                    /*boundary case -- increment exponent*/
1934
1.67k
                    word0(&rv) = (word0(&rv) & Exp_mask)
1935
1.67k
                        + Exp_msk1
1936
1.67k
                        ;
1937
1.67k
                    word1(&rv) = 0;
1938
                    /* dsign = 0; */
1939
1.67k
                    break;
1940
1.67k
                }
1941
5.39k
            }
1942
10.5k
            else if (!(word0(&rv) & Bndry_mask) && !word1(&rv)) {
1943
1.97k
              drop_down:
1944
                /* boundary case -- decrement exponent */
1945
1.97k
                if (bc.scale) {
1946
0
                    L = word0(&rv) & Exp_mask;
1947
0
                    if (L <= (2*P+1)*Exp_msk1) {
1948
0
                        if (L > (P+2)*Exp_msk1)
1949
                            /* round even ==> */
1950
                            /* accept rv */
1951
0
                            break;
1952
                        /* rv = smallest denormal */
1953
0
                        if (bc.nd > nd)
1954
0
                            break;
1955
0
                        goto undfl;
1956
0
                    }
1957
0
                }
1958
1.97k
                L = (word0(&rv) & Exp_mask) - Exp_msk1;
1959
1.97k
                word0(&rv) = L | Bndry_mask1;
1960
1.97k
                word1(&rv) = 0xffffffff;
1961
1.97k
                break;
1962
1.97k
            }
1963
14.2k
            if (!odd)
1964
10.8k
                break;
1965
3.37k
            if (dsign)
1966
2.96k
                dval(&rv) += sulp(&rv, &bc);
1967
413
            else {
1968
413
                dval(&rv) -= sulp(&rv, &bc);
1969
413
                if (!dval(&rv)) {
1970
0
                    if (bc.nd >nd)
1971
0
                        break;
1972
0
                    goto undfl;
1973
0
                }
1974
413
            }
1975
            /* dsign = 1 - dsign; */
1976
3.37k
            break;
1977
3.37k
        }
1978
62.1k
        if ((aadj = ratio(delta, bs)) <= 2.) {
1979
32.2k
            if (dsign)
1980
20.7k
                aadj = aadj1 = 1.;
1981
11.5k
            else if (word1(&rv) || word0(&rv) & Bndry_mask) {
1982
8.11k
                if (word1(&rv) == Tiny1 && !word0(&rv)) {
1983
0
                    if (bc.nd >nd)
1984
0
                        break;
1985
0
                    goto undfl;
1986
0
                }
1987
8.11k
                aadj = 1.;
1988
8.11k
                aadj1 = -1.;
1989
8.11k
            }
1990
3.46k
            else {
1991
                /* special case -- power of FLT_RADIX to be */
1992
                /* rounded down... */
1993
1994
3.46k
                if (aadj < 2./FLT_RADIX)
1995
0
                    aadj = 1./FLT_RADIX;
1996
3.46k
                else
1997
3.46k
                    aadj *= 0.5;
1998
3.46k
                aadj1 = -aadj;
1999
3.46k
            }
2000
32.2k
        }
2001
29.9k
        else {
2002
29.9k
            aadj *= 0.5;
2003
29.9k
            aadj1 = dsign ? aadj : -aadj;
2004
29.9k
            if (Flt_Rounds == 0)
2005
0
                aadj1 += 0.5;
2006
29.9k
        }
2007
62.1k
        y = word0(&rv) & Exp_mask;
2008
2009
        /* Check for overflow */
2010
2011
62.1k
        if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) {
2012
3.29k
            dval(&rv0) = dval(&rv);
2013
3.29k
            word0(&rv) -= P*Exp_msk1;
2014
3.29k
            adj.d = aadj1 * ulp(&rv);
2015
3.29k
            dval(&rv) += adj.d;
2016
3.29k
            if ((word0(&rv) & Exp_mask) >=
2017
3.29k
                Exp_msk1*(DBL_MAX_EXP+Bias-P)) {
2018
2.95k
                if (word0(&rv0) == Big0 && word1(&rv0) == Big1) {
2019
2.19k
                    goto ovfl;
2020
2.19k
                }
2021
760
                word0(&rv) = Big0;
2022
760
                word1(&rv) = Big1;
2023
760
                goto cont;
2024
2.95k
            }
2025
334
            else
2026
334
                word0(&rv) += P*Exp_msk1;
2027
3.29k
        }
2028
58.9k
        else {
2029
58.9k
            if (bc.scale && y <= 2*P*Exp_msk1) {
2030
9.50k
                if (aadj <= 0x7fffffff) {
2031
9.50k
                    if ((z = (ULong)aadj) <= 0)
2032
910
                        z = 1;
2033
9.50k
                    aadj = z;
2034
9.50k
                    aadj1 = dsign ? aadj : -aadj;
2035
9.50k
                }
2036
9.50k
                dval(&aadj2) = aadj1;
2037
9.50k
                word0(&aadj2) += (2*P+1)*Exp_msk1 - y;
2038
9.50k
                aadj1 = dval(&aadj2);
2039
9.50k
            }
2040
58.9k
            adj.d = aadj1 * ulp(&rv);
2041
58.9k
            dval(&rv) += adj.d;
2042
58.9k
        }
2043
59.2k
        z = word0(&rv) & Exp_mask;
2044
59.2k
        if (bc.nd == nd) {
2045
44.3k
            if (!bc.scale)
2046
34.1k
                if (y == z) {
2047
                    /* Can we stop now? */
2048
31.1k
                    L = (Long)aadj;
2049
31.1k
                    aadj -= L;
2050
                    /* The tolerances below are conservative. */
2051
31.1k
                    if (dsign || word1(&rv) || word0(&rv) & Bndry_mask) {
2052
30.8k
                        if (aadj < .4999999 || aadj > .5000001)
2053
21.2k
                            break;
2054
30.8k
                    }
2055
242
                    else if (aadj < .4999999/FLT_RADIX)
2056
242
                        break;
2057
31.1k
                }
2058
44.3k
        }
2059
38.5k
      cont:
2060
38.5k
        Bfree(bb); bb = NULL;
2061
38.5k
        Bfree(bd); bd = NULL;
2062
38.5k
        Bfree(bs); bs = NULL;
2063
38.5k
        Bfree(delta); delta = NULL;
2064
38.5k
    }
2065
92.7k
    if (bc.nd > nd) {
2066
18.0k
        error = bigcomp(&rv, s0, &bc);
2067
18.0k
        if (error)
2068
0
            goto failed_malloc;
2069
18.0k
    }
2070
2071
92.7k
    if (bc.scale) {
2072
17.6k
        word0(&rv0) = Exp_1 - 2*P*Exp_msk1;
2073
17.6k
        word1(&rv0) = 0;
2074
17.6k
        dval(&rv) *= dval(&rv0);
2075
17.6k
    }
2076
2077
232k
  ret:
2078
232k
    result = sign ? -dval(&rv) : dval(&rv);
2079
232k
    goto done;
2080
2081
1.85k
  parse_error:
2082
1.85k
    result = 0.0;
2083
1.85k
    goto done;
2084
2085
0
  failed_malloc:
2086
0
    errno = ENOMEM;
2087
0
    result = -1.0;
2088
0
    goto done;
2089
2090
5.20k
  undfl:
2091
5.20k
    result = sign ? -0.0 : 0.0;
2092
5.20k
    goto done;
2093
2094
20.1k
  ovfl:
2095
20.1k
    errno = ERANGE;
2096
    /* Can't trust HUGE_VAL */
2097
20.1k
    word0(&rv) = Exp_mask;
2098
20.1k
    word1(&rv) = 0;
2099
20.1k
    result = sign ? -dval(&rv) : dval(&rv);
2100
20.1k
    goto done;
2101
2102
260k
  done:
2103
260k
    Bfree(bb);
2104
260k
    Bfree(bd);
2105
260k
    Bfree(bs);
2106
260k
    Bfree(bd0);
2107
260k
    Bfree(delta);
2108
260k
    return result;
2109
2110
92.7k
}
2111
2112
static char *
2113
rv_alloc(int i)
2114
39.0k
{
2115
39.0k
    int k, *r;
2116
39.0k
    size_t j;   /* size_t so that j <<= 1 cannot overflow for i near INT_MAX */
2117
2118
39.0k
    j = sizeof(ULong);
2119
39.0k
    for(k = 0;
2120
39.0k
        sizeof(Bigint) - sizeof(ULong) - sizeof(int) + j <= (unsigned)i;
2121
39.0k
        j <<= 1)
2122
0
        k++;
2123
39.0k
    r = (int*)Balloc(k);
2124
39.0k
    if (r == NULL)
2125
0
        return NULL;
2126
39.0k
    *r = k;
2127
39.0k
    return (char *)(r+1);
2128
39.0k
}
2129
2130
static char *
2131
nrv_alloc(const char *s, char **rve, int n)
2132
6.84k
{
2133
6.84k
    char *rv, *t;
2134
2135
6.84k
    rv = rv_alloc(n);
2136
6.84k
    if (rv == NULL)
2137
0
        return NULL;
2138
6.84k
    t = rv;
2139
40.3k
    while((*t = *s++)) t++;
2140
6.84k
    if (rve)
2141
6.84k
        *rve = t;
2142
6.84k
    return rv;
2143
6.84k
}
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
39.0k
{
2154
39.0k
    Bigint *b = (Bigint *)((int *)s - 1);
2155
39.0k
    b->maxwds = 1 << (b->k = *(int*)b);
2156
39.0k
    Bfree(b);
2157
39.0k
}
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
39.0k
{
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
39.0k
    int bbits, b2, b5, be, dig, i, ieps, ilim, ilim0, ilim1,
2236
39.0k
        j, j1, k, k0, k_check, leftright, m2, m5, s2, s5,
2237
39.0k
        spec_case, try_quick;
2238
39.0k
    Long L;
2239
39.0k
    int denorm;
2240
39.0k
    ULong x;
2241
39.0k
    Bigint *b, *b1, *delta, *mlo, *mhi, *S;
2242
39.0k
    U d2, eps, u;
2243
39.0k
    double ds;
2244
39.0k
    char *s, *s0;
2245
2246
    /* set pointers to NULL, to silence gcc compiler warnings and make
2247
       cleanup easier on error */
2248
39.0k
    mlo = mhi = S = 0;
2249
39.0k
    s0 = 0;
2250
2251
39.0k
    u.d = dd;
2252
39.0k
    if (word0(&u) & Sign_bit) {
2253
        /* set sign for everything, including 0's and NaNs */
2254
4
        *sign = 1;
2255
4
        word0(&u) &= ~Sign_bit; /* clear sign bit */
2256
4
    }
2257
39.0k
    else
2258
39.0k
        *sign = 0;
2259
2260
    /* quick return for Infinities, NaNs and zeros */
2261
39.0k
    if ((word0(&u) & Exp_mask) == Exp_mask)
2262
3.80k
    {
2263
        /* Infinity or NaN */
2264
3.80k
        *decpt = 9999;
2265
3.80k
        if (!word1(&u) && !(word0(&u) & 0xfffff))
2266
3.80k
            return nrv_alloc("Infinity", rve, 8);
2267
0
        return nrv_alloc("NaN", rve, 3);
2268
3.80k
    }
2269
35.2k
    if (!dval(&u)) {
2270
3.04k
        *decpt = 1;
2271
3.04k
        return nrv_alloc("0", rve, 1);
2272
3.04k
    }
2273
2274
    /* compute k = floor(log10(d)).  The computation may leave k
2275
       one too large, but should never leave k too small. */
2276
32.1k
    b = d2b(&u, &be, &bbits);
2277
32.1k
    if (b == NULL)
2278
0
        goto failed_malloc;
2279
32.1k
    if ((i = (int)(word0(&u) >> Exp_shift1 & (Exp_mask>>Exp_shift1)))) {
2280
27.3k
        dval(&d2) = dval(&u);
2281
27.3k
        word0(&d2) &= Frac_mask1;
2282
27.3k
        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
27.3k
        i -= Bias;
2307
27.3k
        denorm = 0;
2308
27.3k
    }
2309
4.80k
    else {
2310
        /* d is denormalized */
2311
2312
4.80k
        i = bbits + be + (Bias + (P-1) - 1);
2313
4.80k
        x = i > 32  ? word0(&u) << (64 - i) | word1(&u) >> (i - 32)
2314
4.80k
            : word1(&u) << (32 - i);
2315
4.80k
        dval(&d2) = x;
2316
4.80k
        word0(&d2) -= 31*Exp_msk1; /* adjust exponent */
2317
4.80k
        i -= (Bias + (P-1) - 1) + 1;
2318
4.80k
        denorm = 1;
2319
4.80k
    }
2320
32.1k
    ds = (dval(&d2)-1.5)*0.289529654602168 + 0.1760912590558 +
2321
32.1k
        i*0.301029995663981;
2322
32.1k
    k = (int)ds;
2323
32.1k
    if (ds < 0. && ds != k)
2324
9.43k
        k--;    /* want k = floor(ds) */
2325
32.1k
    k_check = 1;
2326
32.1k
    if (k >= 0 && k <= Ten_pmax) {
2327
17.8k
        if (dval(&u) < tens[k])
2328
524
            k--;
2329
17.8k
        k_check = 0;
2330
17.8k
    }
2331
32.1k
    j = bbits - i - 1;
2332
32.1k
    if (j >= 0) {
2333
16.6k
        b2 = 0;
2334
16.6k
        s2 = j;
2335
16.6k
    }
2336
15.5k
    else {
2337
15.5k
        b2 = -j;
2338
15.5k
        s2 = 0;
2339
15.5k
    }
2340
32.1k
    if (k >= 0) {
2341
22.7k
        b5 = 0;
2342
22.7k
        s5 = k;
2343
22.7k
        s2 += k;
2344
22.7k
    }
2345
9.44k
    else {
2346
9.44k
        b2 -= k;
2347
9.44k
        b5 = -k;
2348
9.44k
        s5 = 0;
2349
9.44k
    }
2350
32.1k
    if (mode < 0 || mode > 9)
2351
0
        mode = 0;
2352
2353
32.1k
    try_quick = 1;
2354
2355
32.1k
    if (mode > 5) {
2356
0
        mode -= 4;
2357
0
        try_quick = 0;
2358
0
    }
2359
32.1k
    leftright = 1;
2360
32.1k
    ilim = ilim1 = -1;  /* Values for cases 0 and 1; done here to */
2361
    /* silence erroneous "gcc -Wall" warning. */
2362
32.1k
    switch(mode) {
2363
32.1k
    case 0:
2364
32.1k
    case 1:
2365
32.1k
        i = 18;
2366
32.1k
        ndigits = 0;
2367
32.1k
        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
0
    case 3:
2377
0
        leftright = 0;
2378
0
        _Py_FALLTHROUGH;
2379
0
    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
0
        if (ndigits > INT_MAX - 1024)
2386
0
            ndigits = INT_MAX - 1024;
2387
0
        else if (ndigits < -(INT_MAX - 1024))
2388
0
            ndigits = -(INT_MAX - 1024);
2389
0
        i = ndigits + k + 1;
2390
0
        ilim = i;
2391
0
        ilim1 = i - 1;
2392
0
        if (i <= 0)
2393
0
            i = 1;
2394
32.1k
    }
2395
32.1k
    s0 = rv_alloc(i);
2396
32.1k
    if (s0 == NULL)
2397
0
        goto failed_malloc;
2398
32.1k
    s = s0;
2399
2400
2401
32.1k
    if (ilim >= 0 && ilim <= Quick_max && try_quick) {
2402
2403
        /* Try to get by with floating-point arithmetic. */
2404
2405
0
        i = 0;
2406
0
        dval(&d2) = dval(&u);
2407
0
        k0 = k;
2408
0
        ilim0 = ilim;
2409
0
        ieps = 2; /* conservative */
2410
0
        if (k > 0) {
2411
0
            ds = tens[k&0xf];
2412
0
            j = k >> 4;
2413
0
            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
0
            for(; j; j >>= 1, i++)
2420
0
                if (j & 1) {
2421
0
                    ieps++;
2422
0
                    ds *= bigtens[i];
2423
0
                }
2424
0
            dval(&u) /= ds;
2425
0
        }
2426
0
        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
0
        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
0
        dval(&eps) = ieps*dval(&u) + 7.;
2443
0
        word0(&eps) -= (P-1)*Exp_msk1;
2444
0
        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
0
        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
0
        else {
2473
            /* Generate ilim digits, then fix them up. */
2474
0
            dval(&eps) *= tens[ilim-1];
2475
0
            for(i = 1;; i++, dval(&u) *= 10.) {
2476
0
                L = (Long)(dval(&u));
2477
0
                if (!(dval(&u) -= L))
2478
0
                    ilim = i;
2479
0
                *s++ = '0' + (int)L;
2480
0
                if (i == ilim) {
2481
0
                    if (dval(&u) > 0.5 + dval(&eps))
2482
0
                        goto bump_up;
2483
0
                    else if (dval(&u) < 0.5 - dval(&eps)) {
2484
0
                        while(*--s == '0');
2485
0
                        s++;
2486
0
                        goto ret1;
2487
0
                    }
2488
0
                    break;
2489
0
                }
2490
0
            }
2491
0
        }
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
32.1k
    if (be >= 0 && k <= Int_max) {
2502
        /* Yes. */
2503
11.6k
        ds = tens[k];
2504
11.6k
        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
40.2k
        for(i = 1;; i++, dval(&u) *= 10.) {
2511
40.2k
            L = (Long)(dval(&u) / ds);
2512
40.2k
            dval(&u) -= L*ds;
2513
40.2k
            *s++ = '0' + (int)L;
2514
40.2k
            if (!dval(&u)) {
2515
11.6k
                break;
2516
11.6k
            }
2517
28.5k
            if (i == ilim) {
2518
0
                dval(&u) += dval(&u);
2519
0
                if (dval(&u) > ds || (dval(&u) == ds && L & 1)) {
2520
0
                  bump_up:
2521
0
                    while(*--s == '9')
2522
0
                        if (s == s0) {
2523
0
                            k++;
2524
0
                            *s = '0';
2525
0
                            break;
2526
0
                        }
2527
0
                    ++*s++;
2528
0
                }
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
0
                break;
2538
0
            }
2539
28.5k
        }
2540
11.6k
        goto ret1;
2541
11.6k
    }
2542
2543
20.5k
    m2 = b2;
2544
20.5k
    m5 = b5;
2545
20.5k
    if (leftright) {
2546
20.5k
        i =
2547
20.5k
            denorm ? be + (Bias + (P-1) - 1 + 1) :
2548
20.5k
            1 + P - bbits;
2549
20.5k
        b2 += i;
2550
20.5k
        s2 += i;
2551
20.5k
        mhi = i2b(1);
2552
20.5k
        if (mhi == NULL)
2553
0
            goto failed_malloc;
2554
20.5k
    }
2555
20.5k
    if (m2 > 0 && s2 > 0) {
2556
17.4k
        i = m2 < s2 ? m2 : s2;
2557
17.4k
        b2 -= i;
2558
17.4k
        m2 -= i;
2559
17.4k
        s2 -= i;
2560
17.4k
    }
2561
20.5k
    if (b5 > 0) {
2562
9.44k
        if (leftright) {
2563
9.44k
            if (m5 > 0) {
2564
9.44k
                mhi = pow5mult(mhi, m5);
2565
9.44k
                if (mhi == NULL)
2566
0
                    goto failed_malloc;
2567
9.44k
                b1 = mult(mhi, b);
2568
9.44k
                Bfree(b);
2569
9.44k
                b = b1;
2570
9.44k
                if (b == NULL)
2571
0
                    goto failed_malloc;
2572
9.44k
            }
2573
9.44k
            if ((j = b5 - m5)) {
2574
0
                b = pow5mult(b, j);
2575
0
                if (b == NULL)
2576
0
                    goto failed_malloc;
2577
0
            }
2578
9.44k
        }
2579
0
        else {
2580
0
            b = pow5mult(b, b5);
2581
0
            if (b == NULL)
2582
0
                goto failed_malloc;
2583
0
        }
2584
9.44k
    }
2585
20.5k
    S = i2b(1);
2586
20.5k
    if (S == NULL)
2587
0
        goto failed_malloc;
2588
20.5k
    if (s5 > 0) {
2589
10.2k
        S = pow5mult(S, s5);
2590
10.2k
        if (S == NULL)
2591
0
            goto failed_malloc;
2592
10.2k
    }
2593
2594
    /* Check for special case that d is a normalized power of 2. */
2595
2596
20.5k
    spec_case = 0;
2597
20.5k
    if ((mode < 2 || leftright)
2598
20.5k
        ) {
2599
20.5k
        if (!word1(&u) && !(word0(&u) & Bndry_mask)
2600
188
            && word0(&u) & (Exp_mask & ~Exp_msk1)
2601
20.5k
            ) {
2602
            /* The special case */
2603
188
            b2 += Log2P;
2604
188
            s2 += Log2P;
2605
188
            spec_case = 1;
2606
188
        }
2607
20.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
20.5k
#define iInc 28
2617
20.5k
    i = dshift(S, s2);
2618
20.5k
    b2 += i;
2619
20.5k
    m2 += i;
2620
20.5k
    s2 += i;
2621
20.5k
    if (b2 > 0) {
2622
20.5k
        b = lshift(b, b2);
2623
20.5k
        if (b == NULL)
2624
0
            goto failed_malloc;
2625
20.5k
    }
2626
20.5k
    if (s2 > 0) {
2627
20.3k
        S = lshift(S, s2);
2628
20.3k
        if (S == NULL)
2629
0
            goto failed_malloc;
2630
20.3k
    }
2631
20.5k
    if (k_check) {
2632
14.3k
        if (cmp(b,S) < 0) {
2633
3.13k
            k--;
2634
3.13k
            b = multadd(b, 10, 0);      /* we botched the k estimate */
2635
3.13k
            if (b == NULL)
2636
0
                goto failed_malloc;
2637
3.13k
            if (leftright) {
2638
3.13k
                mhi = multadd(mhi, 10, 0);
2639
3.13k
                if (mhi == NULL)
2640
0
                    goto failed_malloc;
2641
3.13k
            }
2642
3.13k
            ilim = ilim1;
2643
3.13k
        }
2644
14.3k
    }
2645
20.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
20.5k
    if (leftright) {
2665
20.5k
        if (m2 > 0) {
2666
20.3k
            mhi = lshift(mhi, m2);
2667
20.3k
            if (mhi == NULL)
2668
0
                goto failed_malloc;
2669
20.3k
        }
2670
2671
        /* Compute mlo -- check for special case
2672
         * that d is a normalized power of 2.
2673
         */
2674
2675
20.5k
        mlo = mhi;
2676
20.5k
        if (spec_case) {
2677
188
            mhi = Balloc(mhi->k);
2678
188
            if (mhi == NULL)
2679
0
                goto failed_malloc;
2680
188
            Bcopy(mhi, mlo);
2681
188
            mhi = lshift(mhi, Log2P);
2682
188
            if (mhi == NULL)
2683
0
                goto failed_malloc;
2684
188
        }
2685
2686
109k
        for(i = 1;;i++) {
2687
109k
            dig = quorem(b,S) + '0';
2688
            /* Do we yet have the shortest decimal string
2689
             * that will round to d?
2690
             */
2691
109k
            j = cmp(b, mlo);
2692
109k
            delta = diff(S, mhi);
2693
109k
            if (delta == NULL)
2694
0
                goto failed_malloc;
2695
109k
            j1 = delta->sign ? 1 : cmp(b, delta);
2696
109k
            Bfree(delta);
2697
109k
            if (j1 == 0 && mode != 1 && !(word1(&u) & 1)
2698
109k
                ) {
2699
1.39k
                if (dig == '9')
2700
1.00k
                    goto round_9_up;
2701
385
                if (j > 0)
2702
77
                    dig++;
2703
385
                *s++ = dig;
2704
385
                goto ret;
2705
1.39k
            }
2706
107k
            if (j < 0 || (j == 0 && mode != 1
2707
1.05k
                          && !(word1(&u) & 1)
2708
95.8k
                    )) {
2709
12.0k
                if (!b->x[0] && b->wds <= 1) {
2710
2.06k
                    goto accept_dig;
2711
2.06k
                }
2712
9.99k
                if (j1 > 0) {
2713
3.42k
                    b = lshift(b, 1);
2714
3.42k
                    if (b == NULL)
2715
0
                        goto failed_malloc;
2716
3.42k
                    j1 = cmp(b, S);
2717
3.42k
                    if ((j1 > 0 || (j1 == 0 && dig & 1))
2718
1.48k
                        && dig++ == '9')
2719
232
                        goto round_9_up;
2720
3.42k
                }
2721
11.8k
              accept_dig:
2722
11.8k
                *s++ = dig;
2723
11.8k
                goto ret;
2724
9.99k
            }
2725
95.6k
            if (j1 > 0) {
2726
7.05k
                if (dig == '9') { /* possible if i == 1 */
2727
3.66k
                  round_9_up:
2728
3.66k
                    *s++ = '9';
2729
3.66k
                    goto roundoff;
2730
2.42k
                }
2731
4.62k
                *s++ = dig + 1;
2732
4.62k
                goto ret;
2733
7.05k
            }
2734
88.5k
            *s++ = dig;
2735
88.5k
            if (i == ilim)
2736
0
                break;
2737
88.5k
            b = multadd(b, 10, 0);
2738
88.5k
            if (b == NULL)
2739
0
                goto failed_malloc;
2740
88.5k
            if (mlo == mhi) {
2741
88.2k
                mlo = mhi = multadd(mhi, 10, 0);
2742
88.2k
                if (mlo == NULL)
2743
0
                    goto failed_malloc;
2744
88.2k
            }
2745
382
            else {
2746
382
                mlo = multadd(mlo, 10, 0);
2747
382
                if (mlo == NULL)
2748
0
                    goto failed_malloc;
2749
382
                mhi = multadd(mhi, 10, 0);
2750
382
                if (mhi == NULL)
2751
0
                    goto failed_malloc;
2752
382
            }
2753
88.5k
        }
2754
20.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
3.66k
      roundoff:
2776
3.66k
        while(*--s == '9')
2777
3.66k
            if (s == s0) {
2778
3.66k
                k++;
2779
3.66k
                *s++ = '1';
2780
3.66k
                goto ret;
2781
3.66k
            }
2782
0
        ++*s++;
2783
0
    }
2784
0
    else {
2785
0
        while(*--s == '0');
2786
0
        s++;
2787
0
    }
2788
20.5k
  ret:
2789
20.5k
    Bfree(S);
2790
20.5k
    if (mhi) {
2791
20.5k
        if (mlo && mlo != mhi)
2792
188
            Bfree(mlo);
2793
20.5k
        Bfree(mhi);
2794
20.5k
    }
2795
32.1k
  ret1:
2796
32.1k
    Bfree(b);
2797
32.1k
    *s = 0;
2798
32.1k
    *decpt = k + 1;
2799
32.1k
    if (rve)
2800
32.1k
        *rve = s;
2801
32.1k
    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
20.5k
}
2815
2816
#endif  // _PY_SHORT_FLOAT_REPR == 1
2817
2818
PyStatus
2819
_PyDtoa_Init(PyInterpreterState *interp)
2820
22
{
2821
22
#if _PY_SHORT_FLOAT_REPR == 1 && !defined(Py_USING_MEMORY_DEBUGGER)
2822
22
    Bigint **p5s = interp->dtoa.p5s;
2823
2824
    // 5**4 = 625
2825
22
    Bigint *p5 = i2b(625);
2826
22
    if (p5 == NULL) {
2827
0
        return PyStatus_NoMemory();
2828
0
    }
2829
22
    p5s[0] = p5;
2830
2831
    // compute 5**8, 5**16, 5**32, ..., 5**512
2832
176
    for (Py_ssize_t i = 1; i < Bigint_Pow5size; i++) {
2833
154
        p5 = mult(p5, p5);
2834
154
        if (p5 == NULL) {
2835
0
            return PyStatus_NoMemory();
2836
0
        }
2837
154
        p5s[i] = p5;
2838
154
    }
2839
2840
22
#endif
2841
22
    return PyStatus_Ok();
2842
22
}
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
}