Coverage Report

Created: 2022-07-08 09:39

/home/mdboom/Work/builds/cpython/Objects/longobject.c
Line
Count
Source (jump to first uncovered line)
1
/* Long (arbitrary precision) integer object implementation */
2
3
/* XXX The functional organization of this file is terrible */
4
5
#include "Python.h"
6
#include "pycore_bitutils.h"      // _Py_popcount32()
7
#include "pycore_initconfig.h"    // _PyStatus_OK()
8
#include "pycore_long.h"          // _Py_SmallInts
9
#include "pycore_object.h"        // _PyObject_InitVar()
10
#include "pycore_pystate.h"       // _Py_IsMainInterpreter()
11
#include "pycore_runtime.h"       // _PY_NSMALLPOSINTS
12
#include "pycore_structseq.h"     // _PyStructSequence_FiniType()
13
14
#include <ctype.h>
15
#include <float.h>
16
#include <stddef.h>
17
#include <stdlib.h>               // abs()
18
19
#include "clinic/longobject.c.h"
20
/*[clinic input]
21
class int "PyObject *" "&PyLong_Type"
22
[clinic start generated code]*/
23
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=ec0275e3422a36e3]*/
24
25
/* Is this PyLong of size 1, 0 or -1? */
26
#define IS_MEDIUM_VALUE(x) (((size_t)
Py_SIZE170M
(x)) + 1U < 3U)
27
28
/* convert a PyLong of size 1, 0 or -1 to a C integer */
29
static inline stwodigits
30
medium_value(PyLongObject *x)
31
{
32
    assert(IS_MEDIUM_VALUE(x));
33
    return ((stwodigits)Py_SIZE(x)) * x->ob_digit[0];
34
}
35
36
#define IS_SMALL_INT(ival) (-_PY_NSMALLNEGINTS <= (ival) && 
(ival) < 263M
_PY_NSMALLPOSINTS263M
)
37
#define IS_SMALL_UINT(ival) ((ival) < _PY_NSMALLPOSINTS)
38
39
static inline void
40
_Py_DECREF_INT(PyLongObject *op)
41
{
42
    assert(PyLong_CheckExact(op));
43
    _Py_DECREF_SPECIALIZED((PyObject *)op, (destructor)PyObject_Free);
44
}
45
46
static inline int
47
is_medium_int(stwodigits x)
48
{
49
    /* Take care that we are comparing unsigned values. */
50
    twodigits x_plus_mask = ((twodigits)x) + PyLong_MASK;
51
    return x_plus_mask < ((twodigits)PyLong_MASK) + PyLong_BASE;
52
}
53
54
static PyObject *
55
get_small_int(sdigit ival)
56
{
57
    assert(IS_SMALL_INT(ival));
58
    PyObject *v = (PyObject *)&_PyLong_SMALL_INTS[_PY_NSMALLNEGINTS + ival];
59
    Py_INCREF(v);
60
    return v;
61
}
62
63
static PyLongObject *
64
maybe_small_long(PyLongObject *v)
65
{
66
    if (v && IS_MEDIUM_VALUE(v)) {
  Branch (66:9): [True: 13.7M, False: 0]
67
        stwodigits ival = medium_value(v);
68
        if (IS_SMALL_INT(ival)) {
69
            _Py_DECREF_INT(v);
70
            return (PyLongObject *)get_small_int((sdigit)ival);
71
        }
72
    }
73
    return v;
74
}
75
76
/* For int multiplication, use the O(N**2) school algorithm unless
77
 * both operands contain more than KARATSUBA_CUTOFF digits (this
78
 * being an internal Python int digit, in base BASE).
79
 */
80
#define KARATSUBA_CUTOFF 70
81
#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
82
83
/* For exponentiation, use the binary left-to-right algorithm unless the
84
 ^ exponent contains more than HUGE_EXP_CUTOFF bits.  In that case, do
85
 * (no more than) EXP_WINDOW_SIZE bits at a time.  The potential drawback is
86
 * that a table of 2**(EXP_WINDOW_SIZE - 1) intermediate results is
87
 * precomputed.
88
 */
89
#define EXP_WINDOW_SIZE 5
90
#define EXP_TABLE_LEN (1 << (EXP_WINDOW_SIZE - 1))
91
/* Suppose the exponent has bit length e. All ways of doing this
92
 * need e squarings. The binary method also needs a multiply for
93
 * each bit set. In a k-ary method with window width w, a multiply
94
 * for each non-zero window, so at worst (and likely!)
95
 * ceiling(e/w). The k-ary sliding window method has the same
96
 * worst case, but the window slides so it can sometimes skip
97
 * over an all-zero window that the fixed-window method can't
98
 * exploit. In addition, the windowing methods need multiplies
99
 * to precompute a table of small powers.
100
 *
101
 * For the sliding window method with width 5, 16 precomputation
102
 * multiplies are needed. Assuming about half the exponent bits
103
 * are set, then, the binary method needs about e/2 extra mults
104
 * and the window method about 16 + e/5.
105
 *
106
 * The latter is smaller for e > 53 1/3. We don't have direct
107
 * access to the bit length, though, so call it 60, which is a
108
 * multiple of a long digit's max bit length (15 or 30 so far).
109
 */
110
#define HUGE_EXP_CUTOFF 60
111
112
#define SIGCHECK(PyTryBlock)                    \
113
    do {                                        \
114
        if (PyErr_CheckSignals()) 
PyTryBlock0
\
115
    } while(0)
116
117
/* Normalize (remove leading zeros from) an int object.
118
   Doesn't attempt to free the storage--in most cases, due to the nature
119
   of the algorithms used, this could save at most be one word anyway. */
120
121
static PyLongObject *
122
long_normalize(PyLongObject *v)
123
{
124
    Py_ssize_t j = Py_ABS(Py_SIZE(v));
125
    Py_ssize_t i = j;
126
127
    while (i > 0 && 
v->ob_digit[i-1] == 040.2M
)
  Branch (127:12): [True: 40.2M, False: 555k]
  Branch (127:21): [True: 13.3M, False: 26.9M]
128
        --i;
129
    if (i != j) {
  Branch (129:9): [True: 9.80M, False: 17.6M]
130
        Py_SET_SIZE(v, (Py_SIZE(v) < 0) ? -(i) : i);
131
    }
132
    return v;
133
}
134
135
/* Allocate a new int object with size digits.
136
   Return NULL and set exception if we run out of memory. */
137
138
#define MAX_LONG_DIGITS \
139
    ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
140
141
PyLongObject *
142
_PyLong_New(Py_ssize_t size)
143
{
144
    PyLongObject *result;
145
    if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
  Branch (145:9): [True: 0, False: 91.2M]
146
        PyErr_SetString(PyExc_OverflowError,
147
                        "too many digits in integer");
148
        return NULL;
149
    }
150
    /* Fast operations for single digit integers (including zero)
151
     * assume that there is always at least one digit present. */
152
    Py_ssize_t ndigits = size ? 
size91.2M
:
111.5k
;
  Branch (152:26): [True: 91.2M, False: 11.5k]
153
    /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
154
       sizeof(digit)*size.  Previous incarnations of this code used
155
       sizeof(PyVarObject) instead of the offsetof, but this risks being
156
       incorrect in the presence of padding between the PyVarObject header
157
       and the digits. */
158
    result = PyObject_Malloc(offsetof(PyLongObject, ob_digit) +
159
                             ndigits*sizeof(digit));
160
    if (!result) {
  Branch (160:9): [True: 0, False: 91.2M]
161
        PyErr_NoMemory();
162
        return NULL;
163
    }
164
    _PyObject_InitVar((PyVarObject*)result, &PyLong_Type, size);
165
    return result;
166
}
167
168
PyObject *
169
_PyLong_Copy(PyLongObject *src)
170
{
171
    PyLongObject *result;
172
    Py_ssize_t i;
173
174
    assert(src != NULL);
175
    i = Py_SIZE(src);
176
    if (i < 0)
  Branch (176:9): [True: 199k, False: 570k]
177
        i = -(i);
178
    if (i < 2) {
  Branch (178:9): [True: 545k, False: 223k]
179
        stwodigits ival = medium_value(src);
180
        if (IS_SMALL_INT(ival)) {
181
            return get_small_int((sdigit)ival);
182
        }
183
    }
184
    result = _PyLong_New(i);
185
    if (result != NULL) {
  Branch (185:9): [True: 259k, False: 0]
186
        Py_SET_SIZE(result, Py_SIZE(src));
187
        while (--i >= 0) {
  Branch (187:16): [True: 4.11M, False: 259k]
188
            result->ob_digit[i] = src->ob_digit[i];
189
        }
190
    }
191
    return (PyObject *)result;
192
}
193
194
static PyObject *
195
_PyLong_FromMedium(sdigit x)
196
{
197
    assert(!IS_SMALL_INT(x));
198
    assert(is_medium_int(x));
199
    /* We could use a freelist here */
200
    PyLongObject *v = PyObject_Malloc(sizeof(PyLongObject));
201
    if (v == NULL) {
  Branch (201:9): [True: 0, False: 61.1M]
202
        PyErr_NoMemory();
203
        return NULL;
204
    }
205
    Py_ssize_t sign = x < 0 ? 
-13.22M
:
157.9M
;
  Branch (205:23): [True: 3.22M, False: 57.9M]
206
    digit abs_x = x < 0 ? 
-x3.22M
:
x57.9M
;
  Branch (206:19): [True: 3.22M, False: 57.9M]
207
    _PyObject_InitVar((PyVarObject*)v, &PyLong_Type, sign);
208
    v->ob_digit[0] = abs_x;
209
    return (PyObject*)v;
210
}
211
212
static PyObject *
213
_PyLong_FromLarge(stwodigits ival)
214
{
215
    twodigits abs_ival;
216
    int sign;
217
    assert(!is_medium_int(ival));
218
219
    if (ival < 0) {
  Branch (219:9): [True: 13.5k, False: 17.6M]
220
        /* negate: can't write this as abs_ival = -ival since that
221
           invokes undefined behaviour when ival is LONG_MIN */
222
        abs_ival = 0U-(twodigits)ival;
223
        sign = -1;
224
    }
225
    else {
226
        abs_ival = (twodigits)ival;
227
        sign = 1;
228
    }
229
    /* Must be at least two digits */
230
    assert(abs_ival >> PyLong_SHIFT != 0);
231
    twodigits t = abs_ival >> (PyLong_SHIFT * 2);
232
    Py_ssize_t ndigits = 2;
233
    while (t) {
  Branch (233:12): [True: 0, False: 17.6M]
234
        ++ndigits;
235
        t >>= PyLong_SHIFT;
236
    }
237
    PyLongObject *v = _PyLong_New(ndigits);
238
    if (v != NULL) {
  Branch (238:9): [True: 17.6M, False: 0]
239
        digit *p = v->ob_digit;
240
        Py_SET_SIZE(v, ndigits * sign);
241
        t = abs_ival;
242
        while (t) {
  Branch (242:16): [True: 35.3M, False: 17.6M]
243
            *p++ = Py_SAFE_DOWNCAST(
244
                t & PyLong_MASK, twodigits, digit);
245
            t >>= PyLong_SHIFT;
246
        }
247
    }
248
    return (PyObject *)v;
249
}
250
251
/* Create a new int object from a C word-sized int */
252
static inline PyObject *
253
_PyLong_FromSTwoDigits(stwodigits x)
254
{
255
    if (IS_SMALL_INT(x)) {
256
        return get_small_int((sdigit)x);
257
    }
258
    assert(x != 0);
259
    if (is_medium_int(x)) {
  Branch (259:9): [True: 16.3M, False: 17.6M]
260
        return _PyLong_FromMedium((sdigit)x);
261
    }
262
    return _PyLong_FromLarge(x);
263
}
264
265
int
266
_PyLong_AssignValue(PyObject **target, Py_ssize_t value)
267
{
268
    PyObject *old = *target;
269
    if (IS_SMALL_INT(value)) {
270
        *target = get_small_int(Py_SAFE_DOWNCAST(value, Py_ssize_t, sdigit));
271
        Py_XDECREF(old);
272
        return 0;
273
    }
274
    else if (old != NULL && PyLong_CheckExact(old) &&
  Branch (274:14): [True: 25.6M, False: 2.92k]
275
             
Py_REFCNT23.5M
(old) == 123.5M
&&
Py_SIZE22.3M
(old) == 122.3M
&&
  Branch (275:14): [True: 22.3M, False: 1.21M]
  Branch (275:37): [True: 22.1M, False: 127k]
276
             
(size_t)value <= 22.1M
PyLong_MASK22.1M
)
  Branch (276:14): [True: 22.1M, False: 2]
277
    {
278
        // Mutate in place if there are no other references the old
279
        // object.  This avoids an allocation in a common case.
280
        // Since the primary use-case is iterating over ranges, which
281
        // are typically positive, only do this optimization
282
        // for positive integers (for now).
283
        ((PyLongObject *)old)->ob_digit[0] =
284
            Py_SAFE_DOWNCAST(value, Py_ssize_t, digit);
285
        return 0;
286
    }
287
    else {
288
        *target = PyLong_FromSsize_t(value);
289
        Py_XDECREF(old);
290
        if (*target == NULL) {
  Branch (290:13): [True: 0, False: 3.44M]
291
            return -1;
292
        }
293
        return 0;
294
    }
295
}
296
297
/* If a freshly-allocated int is already shared, it must
298
   be a small integer, so negating it must go to PyLong_FromLong */
299
Py_LOCAL_INLINE(void)
300
_PyLong_Negate(PyLongObject **x_p)
301
{
302
    PyLongObject *x;
303
304
    x = (PyLongObject *)*x_p;
305
    if (Py_REFCNT(x) == 1) {
  Branch (305:9): [True: 227k, False: 42.7k]
306
        Py_SET_SIZE(x, -Py_SIZE(x));
307
        return;
308
    }
309
310
    *x_p = (PyLongObject *)_PyLong_FromSTwoDigits(-medium_value(x));
311
    Py_DECREF(x);
312
}
313
314
/* Create a new int object from a C long int */
315
316
PyObject *
317
PyLong_FromLong(long ival)
318
{
319
    PyLongObject *v;
320
    unsigned long abs_ival, t;
321
    int ndigits;
322
323
    /* Handle small and medium cases. */
324
    if (IS_SMALL_INT(ival)) {
325
        return get_small_int((sdigit)ival);
326
    }
327
    if (-(long)PyLong_MASK <= ival && 
ival <= (long)47.8M
PyLong_MASK47.8M
) {
  Branch (327:9): [True: 47.8M, False: 628k]
  Branch (327:39): [True: 44.0M, False: 3.79M]
328
        return _PyLong_FromMedium((sdigit)ival);
329
    }
330
331
    /* Count digits (at least two - smaller cases were handled above). */
332
    abs_ival = ival < 0 ? 
0U-(unsigned long)ival628k
:
(unsigned long)ival3.79M
;
  Branch (332:16): [True: 628k, False: 3.79M]
333
    /* Do shift in two steps to avoid possible undefined behavior. */
334
    t = abs_ival >> PyLong_SHIFT >> PyLong_SHIFT;
335
    ndigits = 2;
336
    while (t) {
  Branch (336:12): [True: 142k, False: 4.42M]
337
        ++ndigits;
338
        t >>= PyLong_SHIFT;
339
    }
340
341
    /* Construct output value. */
342
    v = _PyLong_New(ndigits);
343
    if (v != NULL) {
  Branch (343:9): [True: 4.42M, False: 0]
344
        digit *p = v->ob_digit;
345
        Py_SET_SIZE(v, ival < 0 ? -ndigits : ndigits);
346
        t = abs_ival;
347
        while (t) {
  Branch (347:16): [True: 8.99M, False: 4.42M]
348
            *p++ = (digit)(t & PyLong_MASK);
349
            t >>= PyLong_SHIFT;
350
        }
351
    }
352
    return (PyObject *)v;
353
}
354
355
#define PYLONG_FROM_UINT(INT_TYPE, ival) \
356
    do { \
357
        if (IS_SMALL_UINT(ival)) { \
358
            return get_small_int((sdigit)(ival)); \
359
        } \
360
        /* Count the number of Python digits. */ \
361
        Py_ssize_t ndigits = 0; \
362
        INT_TYPE t = (ival); \
363
        while (t) { \
364
            ++ndigits; \
365
            t >>= PyLong_SHIFT; \
366
        } \
367
        PyLongObject *v = _PyLong_New(ndigits); \
368
        if (v == NULL) { \
369
            return NULL; \
370
        } \
371
        digit *p = v->ob_digit; \
372
        while ((ival)) { \
373
            *p++ = (digit)((ival) & PyLong_MASK); \
374
            (ival) >>= PyLong_SHIFT; \
375
        } \
376
        return (PyObject *)v; \
377
    } while(
00
)
378
379
/* Create a new int object from a C unsigned long int */
380
381
PyObject *
382
PyLong_FromUnsignedLong(unsigned long ival)
383
{
384
    PYLONG_FROM_UINT(unsigned long, ival);
385
}
386
387
/* Create a new int object from a C unsigned long long int. */
388
389
PyObject *
390
PyLong_FromUnsignedLongLong(unsigned long long ival)
391
{
392
    PYLONG_FROM_UINT(unsigned long long, ival);
393
}
394
395
/* Create a new int object from a C size_t. */
396
397
PyObject *
398
PyLong_FromSize_t(size_t ival)
399
{
400
    PYLONG_FROM_UINT(size_t, ival);
401
}
402
403
/* Create a new int object from a C double */
404
405
PyObject *
406
PyLong_FromDouble(double dval)
407
{
408
    /* Try to get out cheap if this fits in a long. When a finite value of real
409
     * floating type is converted to an integer type, the value is truncated
410
     * toward zero. If the value of the integral part cannot be represented by
411
     * the integer type, the behavior is undefined. Thus, we must check that
412
     * value is in range (LONG_MIN - 1, LONG_MAX + 1). If a long has more bits
413
     * of precision than a double, casting LONG_MIN - 1 to double may yield an
414
     * approximation, but LONG_MAX + 1 is a power of two and can be represented
415
     * as double exactly (assuming FLT_RADIX is 2 or 16), so for simplicity
416
     * check against [-(LONG_MAX + 1), LONG_MAX + 1).
417
     */
418
    const double int_max = (unsigned long)LONG_MAX + 1;
419
    if (-int_max < dval && 
dval < int_max12.2M
) {
  Branch (419:9): [True: 12.2M, False: 474]
  Branch (419:28): [True: 12.2M, False: 1.03k]
420
        return PyLong_FromLong((long)dval);
421
    }
422
423
    PyLongObject *v;
424
    double frac;
425
    int i, ndig, expo, neg;
426
    neg = 0;
427
    if (Py_IS_INFINITY(dval)) {
428
        PyErr_SetString(PyExc_OverflowError,
429
                        "cannot convert float infinity to integer");
430
        return NULL;
431
    }
432
    if (Py_IS_NAN(dval)) {
433
        PyErr_SetString(PyExc_ValueError,
434
                        "cannot convert float NaN to integer");
435
        return NULL;
436
    }
437
    if (dval < 0.0) {
  Branch (437:9): [True: 464, False: 1.03k]
438
        neg = 1;
439
        dval = -dval;
440
    }
441
    frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
442
    assert(expo > 0);
443
    ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
444
    v = _PyLong_New(ndig);
445
    if (v == NULL)
  Branch (445:9): [True: 0, False: 1.49k]
446
        return NULL;
447
    frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
448
    for (i = ndig; --i >= 0; ) {
  Branch (448:20): [True: 21.4k, False: 1.49k]
449
        digit bits = (digit)frac;
450
        v->ob_digit[i] = bits;
451
        frac = frac - (double)bits;
452
        frac = ldexp(frac, PyLong_SHIFT);
453
    }
454
    if (neg) {
  Branch (454:9): [True: 464, False: 1.03k]
455
        Py_SET_SIZE(v, -(Py_SIZE(v)));
456
    }
457
    return (PyObject *)v;
458
}
459
460
/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
461
 * anything about what happens when a signed integer operation overflows,
462
 * and some compilers think they're doing you a favor by being "clever"
463
 * then.  The bit pattern for the largest positive signed long is
464
 * (unsigned long)LONG_MAX, and for the smallest negative signed long
465
 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
466
 * However, some other compilers warn about applying unary minus to an
467
 * unsigned operand.  Hence the weird "0-".
468
 */
469
#define PY_ABS_LONG_MIN         (0-(unsigned long)LONG_MIN)
470
#define PY_ABS_SSIZE_T_MIN      (0-(size_t)PY_SSIZE_T_MIN)
471
472
/* Get a C long int from an int object or any object that has an __index__
473
   method.
474
475
   On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
476
   the result.  Otherwise *overflow is 0.
477
478
   For other errors (e.g., TypeError), return -1 and set an error condition.
479
   In this case *overflow will be 0.
480
*/
481
482
long
483
PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
484
{
485
    /* This version by Tim Peters */
486
    PyLongObject *v;
487
    unsigned long x, prev;
488
    long res;
489
    Py_ssize_t i;
490
    int sign;
491
    int do_decref = 0; /* if PyNumber_Index was called */
492
493
    *overflow = 0;
494
    if (vv == NULL) {
  Branch (494:9): [True: 0, False: 40.3M]
495
        PyErr_BadInternalCall();
496
        return -1;
497
    }
498
499
    if (PyLong_Check(vv)) {
500
        v = (PyLongObject *)vv;
501
    }
502
    else {
503
        v = (PyLongObject *)_PyNumber_Index(vv);
504
        if (v == NULL)
  Branch (504:13): [True: 76.1k, False: 71]
505
            return -1;
506
        do_decref = 1;
507
    }
508
509
    res = -1;
510
    i = Py_SIZE(v);
511
512
    switch (i) {
513
    case -1:
  Branch (513:5): [True: 539k, False: 39.6M]
514
        res = -(sdigit)v->ob_digit[0];
515
        break;
516
    case 0:
  Branch (516:5): [True: 3.79M, False: 36.4M]
517
        res = 0;
518
        break;
519
    case 1:
  Branch (519:5): [True: 35.1M, False: 5.11M]
520
        res = v->ob_digit[0];
521
        break;
522
    default:
  Branch (522:5): [True: 777k, False: 39.4M]
523
        sign = 1;
524
        x = 0;
525
        if (i < 0) {
  Branch (525:13): [True: 152k, False: 625k]
526
            sign = -1;
527
            i = -(i);
528
        }
529
        while (--i >= 0) {
  Branch (529:16): [True: 1.61M, False: 770k]
530
            prev = x;
531
            x = (x << PyLong_SHIFT) | v->ob_digit[i];
532
            if ((x >> PyLong_SHIFT) != prev) {
  Branch (532:17): [True: 7.91k, False: 1.61M]
533
                *overflow = sign;
534
                goto exit;
535
            }
536
        }
537
        /* Haven't lost any bits, but casting to long requires extra
538
         * care (see comment above).
539
         */
540
        if (x <= (unsigned long)LONG_MAX) {
  Branch (540:13): [True: 755k, False: 14.2k]
541
            res = (long)x * sign;
542
        }
543
        else if (sign < 0 && 
x == 8.30k
PY_ABS_LONG_MIN8.30k
) {
  Branch (543:18): [True: 8.30k, False: 5.90k]
  Branch (543:30): [True: 3.55k, False: 4.74k]
544
            res = LONG_MIN;
545
        }
546
        else {
547
            *overflow = sign;
548
            /* res is already set to -1 */
549
        }
550
    }
551
  exit:
552
    if (do_decref) {
  Branch (552:9): [True: 71, False: 40.2M]
553
        Py_DECREF(v);
554
    }
555
    return res;
556
}
557
558
/* Get a C long int from an int object or any object that has an __index__
559
   method.  Return -1 and set an error if overflow occurs. */
560
561
long
562
PyLong_AsLong(PyObject *obj)
563
{
564
    int overflow;
565
    long result = PyLong_AsLongAndOverflow(obj, &overflow);
566
    if (overflow) {
  Branch (566:9): [True: 16.7k, False: 13.3M]
567
        /* XXX: could be cute and give a different
568
           message for overflow == -1 */
569
        PyErr_SetString(PyExc_OverflowError,
570
                        "Python int too large to convert to C long");
571
    }
572
    return result;
573
}
574
575
/* Get a C int from an int object or any object that has an __index__
576
   method.  Return -1 and set an error if overflow occurs. */
577
578
int
579
_PyLong_AsInt(PyObject *obj)
580
{
581
    int overflow;
582
    long result = PyLong_AsLongAndOverflow(obj, &overflow);
583
    if (overflow || 
result > INT_MAX22.6M
||
result < INT_MIN22.6M
) {
  Branch (583:9): [True: 4, False: 22.6M]
  Branch (583:21): [True: 23, False: 22.6M]
  Branch (583:41): [True: 3, False: 22.6M]
584
        /* XXX: could be cute and give a different
585
           message for overflow == -1 */
586
        PyErr_SetString(PyExc_OverflowError,
587
                        "Python int too large to convert to C int");
588
        return -1;
589
    }
590
    return (int)result;
591
}
592
593
/* Get a Py_ssize_t from an int object.
594
   Returns -1 and sets an error condition if overflow occurs. */
595
596
Py_ssize_t
597
PyLong_AsSsize_t(PyObject *vv) {
598
    PyLongObject *v;
599
    size_t x, prev;
600
    Py_ssize_t i;
601
    int sign;
602
603
    if (vv == NULL) {
  Branch (603:9): [True: 0, False: 80.5M]
604
        PyErr_BadInternalCall();
605
        return -1;
606
    }
607
    if (!PyLong_Check(vv)) {
  Branch (607:9): [True: 21, False: 80.5M]
608
        PyErr_SetString(PyExc_TypeError, "an integer is required");
609
        return -1;
610
    }
611
612
    v = (PyLongObject *)vv;
613
    i = Py_SIZE(v);
614
    switch (i) {
  Branch (614:13): [True: 1.05M, False: 79.4M]
615
    case -1: return -(sdigit)v->ob_digit[0];
  Branch (615:5): [True: 8.49M, False: 72.0M]
616
    case 0: return 0;
  Branch (616:5): [True: 9.44M, False: 71.0M]
617
    case 1: return v->ob_digit[0];
  Branch (617:5): [True: 61.5M, False: 18.9M]
618
    }
619
    sign = 1;
620
    x = 0;
621
    if (i < 0) {
  Branch (621:9): [True: 337k, False: 715k]
622
        sign = -1;
623
        i = -(i);
624
    }
625
    while (--i >= 0) {
  Branch (625:12): [True: 3.06M, False: 1.04M]
626
        prev = x;
627
        x = (x << PyLong_SHIFT) | v->ob_digit[i];
628
        if ((x >> PyLong_SHIFT) != prev)
  Branch (628:13): [True: 2.61k, False: 3.06M]
629
            goto overflow;
630
    }
631
    /* Haven't lost any bits, but casting to a signed type requires
632
     * extra care (see comment above).
633
     */
634
    if (x <= (size_t)PY_SSIZE_T_MAX) {
  Branch (634:9): [True: 1.04M, False: 1.06k]
635
        return (Py_ssize_t)x * sign;
636
    }
637
    else if (sign < 0 && 
x == 482
PY_ABS_SSIZE_T_MIN482
) {
  Branch (637:14): [True: 482, False: 581]
  Branch (637:26): [True: 24, False: 458]
638
        return PY_SSIZE_T_MIN;
639
    }
640
    /* else overflow */
641
642
  overflow:
643
    PyErr_SetString(PyExc_OverflowError,
644
                    "Python int too large to convert to C ssize_t");
645
    return -1;
646
}
647
648
/* Get a C unsigned long int from an int object.
649
   Returns -1 and sets an error condition if overflow occurs. */
650
651
unsigned long
652
PyLong_AsUnsignedLong(PyObject *vv)
653
{
654
    PyLongObject *v;
655
    unsigned long x, prev;
656
    Py_ssize_t i;
657
658
    if (vv == NULL) {
  Branch (658:9): [True: 0, False: 1.39M]
659
        PyErr_BadInternalCall();
660
        return (unsigned long)-1;
661
    }
662
    if (!PyLong_Check(vv)) {
  Branch (662:9): [True: 12, False: 1.39M]
663
        PyErr_SetString(PyExc_TypeError, "an integer is required");
664
        return (unsigned long)-1;
665
    }
666
667
    v = (PyLongObject *)vv;
668
    i = Py_SIZE(v);
669
    x = 0;
670
    if (i < 0) {
  Branch (670:9): [True: 3.14k, False: 1.39M]
671
        PyErr_SetString(PyExc_OverflowError,
672
                        "can't convert negative value to unsigned int");
673
        return (unsigned long) -1;
674
    }
675
    switch (i) {
  Branch (675:13): [True: 208k, False: 1.18M]
676
    case 0: return 0;
  Branch (676:5): [True: 130k, False: 1.26M]
677
    case 1: return v->ob_digit[0];
  Branch (677:5): [True: 1.05M, False: 338k]
678
    }
679
    
while (208k
--i >= 0) {
  Branch (679:12): [True: 510k, False: 208k]
680
        prev = x;
681
        x = (x << PyLong_SHIFT) | v->ob_digit[i];
682
        if ((x >> PyLong_SHIFT) != prev) {
  Branch (682:13): [True: 84, False: 510k]
683
            PyErr_SetString(PyExc_OverflowError,
684
                            "Python int too large to convert "
685
                            "to C unsigned long");
686
            return (unsigned long) -1;
687
        }
688
    }
689
    return x;
690
}
691
692
/* Get a C size_t from an int object. Returns (size_t)-1 and sets
693
   an error condition if overflow occurs. */
694
695
size_t
696
PyLong_AsSize_t(PyObject *vv)
697
{
698
    PyLongObject *v;
699
    size_t x, prev;
700
    Py_ssize_t i;
701
702
    if (vv == NULL) {
  Branch (702:9): [True: 0, False: 40.6k]
703
        PyErr_BadInternalCall();
704
        return (size_t) -1;
705
    }
706
    if (!PyLong_Check(vv)) {
  Branch (706:9): [True: 1, False: 40.5k]
707
        PyErr_SetString(PyExc_TypeError, "an integer is required");
708
        return (size_t)-1;
709
    }
710
711
    v = (PyLongObject *)vv;
712
    i = Py_SIZE(v);
713
    x = 0;
714
    if (i < 0) {
  Branch (714:9): [True: 803, False: 39.7k]
715
        PyErr_SetString(PyExc_OverflowError,
716
                   "can't convert negative value to size_t");
717
        return (size_t) -1;
718
    }
719
    switch (i) {
  Branch (719:13): [True: 38.9k, False: 818]
720
    case 0: return 0;
  Branch (720:5): [True: 24, False: 39.7k]
721
    case 1: return v->ob_digit[0];
  Branch (721:5): [True: 794, False: 39.0k]
722
    }
723
    
while (38.9k
--i >= 0) {
  Branch (723:12): [True: 114k, False: 38.9k]
724
        prev = x;
725
        x = (x << PyLong_SHIFT) | v->ob_digit[i];
726
        if ((x >> PyLong_SHIFT) != prev) {
  Branch (726:13): [True: 25, False: 114k]
727
            PyErr_SetString(PyExc_OverflowError,
728
                "Python int too large to convert to C size_t");
729
            return (size_t) -1;
730
        }
731
    }
732
    return x;
733
}
734
735
/* Get a C unsigned long int from an int object, ignoring the high bits.
736
   Returns -1 and sets an error condition if an error occurs. */
737
738
static unsigned long
739
_PyLong_AsUnsignedLongMask(PyObject *vv)
740
{
741
    PyLongObject *v;
742
    unsigned long x;
743
    Py_ssize_t i;
744
    int sign;
745
746
    if (vv == NULL || !PyLong_Check(vv)) {
  Branch (746:9): [True: 0, False: 265k]
  Branch (746:23): [True: 0, False: 265k]
747
        PyErr_BadInternalCall();
748
        return (unsigned long) -1;
749
    }
750
    v = (PyLongObject *)vv;
751
    i = Py_SIZE(v);
752
    switch (i) {
  Branch (752:13): [True: 104k, False: 161k]
753
    case 0: return 0;
  Branch (753:5): [True: 14.5k, False: 251k]
754
    case 1: return v->ob_digit[0];
  Branch (754:5): [True: 146k, False: 119k]
755
    }
756
    sign = 1;
757
    x = 0;
758
    if (i < 0) {
  Branch (758:9): [True: 250, False: 104k]
759
        sign = -1;
760
        i = -i;
761
    }
762
    while (--i >= 0) {
  Branch (762:12): [True: 208k, False: 104k]
763
        x = (x << PyLong_SHIFT) | v->ob_digit[i];
764
    }
765
    return x * sign;
766
}
767
768
unsigned long
769
PyLong_AsUnsignedLongMask(PyObject *op)
770
{
771
    PyLongObject *lo;
772
    unsigned long val;
773
774
    if (op == NULL) {
  Branch (774:9): [True: 0, False: 268k]
775
        PyErr_BadInternalCall();
776
        return (unsigned long)-1;
777
    }
778
779
    if (PyLong_Check(op)) {
780
        return _PyLong_AsUnsignedLongMask(op);
781
    }
782
783
    lo = (PyLongObject *)_PyNumber_Index(op);
784
    if (lo == NULL)
  Branch (784:9): [True: 2.97k, False: 17]
785
        return (unsigned long)-1;
786
787
    val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
788
    Py_DECREF(lo);
789
    return val;
790
}
791
792
int
793
_PyLong_Sign(PyObject *vv)
794
{
795
    PyLongObject *v = (PyLongObject *)vv;
796
797
    assert(v != NULL);
798
    assert(PyLong_Check(v));
799
800
    return Py_SIZE(v) == 0 ? 
01.84M
:
(1.05M
Py_SIZE1.05M
(v) < 01.05M
?
-1143k
:
1909k
);
  Branch (800:12): [True: 1.84M, False: 1.05M]
  Branch (800:35): [True: 143k, False: 909k]
801
}
802
803
static int
804
bit_length_digit(digit x)
805
{
806
    // digit can be larger than unsigned long, but only PyLong_SHIFT bits
807
    // of it will be ever used.
808
    static_assert(PyLong_SHIFT <= sizeof(unsigned long) * 8,
809
                  "digit is larger than unsigned long");
810
    return _Py_bit_length((unsigned long)x);
811
}
812
813
size_t
814
_PyLong_NumBits(PyObject *vv)
815
{
816
    PyLongObject *v = (PyLongObject *)vv;
817
    size_t result = 0;
818
    Py_ssize_t ndigits;
819
    int msd_bits;
820
821
    assert(v != NULL);
822
    assert(PyLong_Check(v));
823
    ndigits = Py_ABS(Py_SIZE(v));
824
    assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
825
    if (ndigits > 0) {
  Branch (825:9): [True: 534k, False: 1.23M]
826
        digit msd = v->ob_digit[ndigits - 1];
827
        if ((size_t)(ndigits - 1) > SIZE_MAX / (size_t)PyLong_SHIFT)
  Branch (827:13): [True: 0, False: 534k]
828
            goto Overflow;
829
        result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
830
        msd_bits = bit_length_digit(msd);
831
        if (SIZE_MAX - msd_bits < result)
  Branch (831:13): [True: 0, False: 534k]
832
            goto Overflow;
833
        result += msd_bits;
834
    }
835
    return result;
836
837
  Overflow:
838
    PyErr_SetString(PyExc_OverflowError, "int has too many bits "
839
                    "to express in a platform size_t");
840
    return (size_t)-1;
841
}
842
843
PyObject *
844
_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
845
                      int little_endian, int is_signed)
846
{
847
    const unsigned char* pstartbyte;    /* LSB of bytes */
848
    int incr;                           /* direction to move pstartbyte */
849
    const unsigned char* pendbyte;      /* MSB of bytes */
850
    size_t numsignificantbytes;         /* number of bytes that matter */
851
    Py_ssize_t ndigits;                 /* number of Python int digits */
852
    PyLongObject* v;                    /* result */
853
    Py_ssize_t idigit = 0;              /* next free index in v->ob_digit */
854
855
    if (n == 0)
  Branch (855:9): [True: 12, False: 3.66M]
856
        return PyLong_FromLong(0L);
857
858
    if (little_endian) {
  Branch (858:9): [True: 3.50M, False: 166k]
859
        pstartbyte = bytes;
860
        pendbyte = bytes + n - 1;
861
        incr = 1;
862
    }
863
    else {
864
        pstartbyte = bytes + n - 1;
865
        pendbyte = bytes;
866
        incr = -1;
867
    }
868
869
    if (is_signed)
  Branch (869:9): [True: 7.52k, False: 3.66M]
870
        is_signed = *pendbyte >= 0x80;
871
872
    /* Compute numsignificantbytes.  This consists of finding the most
873
       significant byte.  Leading 0 bytes are insignificant if the number
874
       is positive, and leading 0xff bytes if negative. */
875
    {
876
        size_t i;
877
        const unsigned char* p = pendbyte;
878
        const int pincr = -incr;  /* search MSB to LSB */
879
        const unsigned char insignificant = is_signed ? 
0xff1.96k
:
0x003.66M
;
  Branch (879:45): [True: 1.96k, False: 3.66M]
880
881
        for (i = 0; i < n; 
++i, p += pincr1.64M
) {
  Branch (881:21): [True: 5.30M, False: 7.95k]
882
            if (*p != insignificant)
  Branch (882:17): [True: 3.66M, False: 1.64M]
883
                break;
884
        }
885
        numsignificantbytes = n - i;
886
        /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
887
           actually has 2 significant bytes.  OTOH, 0xff0001 ==
888
           -0x00ffff, so we wouldn't *need* to bump it there; but we
889
           do for 0xffff = -0x0001.  To be safe without bothering to
890
           check every case, bump it regardless. */
891
        if (is_signed && 
numsignificantbytes < n1.96k
)
  Branch (891:13): [True: 1.96k, False: 3.66M]
  Branch (891:26): [True: 781, False: 1.18k]
892
            ++numsignificantbytes;
893
    }
894
895
    /* How many Python int digits do we need?  We have
896
       8*numsignificantbytes bits, and each Python int digit has
897
       PyLong_SHIFT bits, so it's the ceiling of the quotient. */
898
    /* catch overflow before it happens */
899
    if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
  Branch (899:9): [True: 0, False: 3.66M]
900
        PyErr_SetString(PyExc_OverflowError,
901
                        "byte array too long to convert to int");
902
        return NULL;
903
    }
904
    ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
905
    v = _PyLong_New(ndigits);
906
    if (v == NULL)
  Branch (906:9): [True: 0, False: 3.66M]
907
        return NULL;
908
909
    /* Copy the bits over.  The tricky parts are computing 2's-comp on
910
       the fly for signed numbers, and dealing with the mismatch between
911
       8-bit bytes and (probably) 15-bit Python digits.*/
912
    {
913
        size_t i;
914
        twodigits carry = 1;                    /* for 2's-comp calculation */
915
        twodigits accum = 0;                    /* sliding register */
916
        unsigned int accumbits = 0;             /* number of bits in accum */
917
        const unsigned char* p = pstartbyte;
918
919
        for (i = 0; i < numsignificantbytes; 
++i, p += incr81.4M
) {
  Branch (919:21): [True: 81.4M, False: 3.66M]
920
            twodigits thisbyte = *p;
921
            /* Compute correction for 2's comp, if needed. */
922
            if (is_signed) {
  Branch (922:17): [True: 972k, False: 80.4M]
923
                thisbyte = (0xff ^ thisbyte) + carry;
924
                carry = thisbyte >> 8;
925
                thisbyte &= 0xff;
926
            }
927
            /* Because we're going LSB to MSB, thisbyte is
928
               more significant than what's already in accum,
929
               so needs to be prepended to accum. */
930
            accum |= thisbyte << accumbits;
931
            accumbits += 8;
932
            if (accumbits >= PyLong_SHIFT) {
  Branch (932:17): [True: 20.9M, False: 60.5M]
933
                /* There's enough to fill a Python digit. */
934
                assert(idigit < ndigits);
935
                v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
936
                ++idigit;
937
                accum >>= PyLong_SHIFT;
938
                accumbits -= PyLong_SHIFT;
939
                assert(accumbits < PyLong_SHIFT);
940
            }
941
        }
942
        assert(accumbits < PyLong_SHIFT);
943
        if (accumbits) {
  Branch (943:13): [True: 3.64M, False: 19.2k]
944
            assert(idigit < ndigits);
945
            v->ob_digit[idigit] = (digit)accum;
946
            ++idigit;
947
        }
948
    }
949
950
    Py_SET_SIZE(v, is_signed ? -idigit : idigit);
951
    return (PyObject *)maybe_small_long(long_normalize(v));
952
}
953
954
int
955
_PyLong_AsByteArray(PyLongObject* v,
956
                    unsigned char* bytes, size_t n,
957
                    int little_endian, int is_signed)
958
{
959
    Py_ssize_t i;               /* index into v->ob_digit */
960
    Py_ssize_t ndigits;         /* |v->ob_size| */
961
    twodigits accum;            /* sliding register */
962
    unsigned int accumbits;     /* # bits in accum */
963
    int do_twos_comp;           /* store 2's-comp?  is_signed and v < 0 */
964
    digit carry;                /* for computing 2's-comp */
965
    size_t j;                   /* # bytes filled */
966
    unsigned char* p;           /* pointer to next byte in bytes */
967
    int pincr;                  /* direction to move p */
968
969
    assert(v != NULL && PyLong_Check(v));
970
971
    if (Py_SIZE(v) < 0) {
  Branch (971:9): [True: 77.6k, False: 462k]
972
        ndigits = -(Py_SIZE(v));
973
        if (!is_signed) {
  Branch (973:13): [True: 2.42k, False: 75.1k]
974
            PyErr_SetString(PyExc_OverflowError,
975
                            "can't convert negative int to unsigned");
976
            return -1;
977
        }
978
        do_twos_comp = 1;
979
    }
980
    else {
981
        ndigits = Py_SIZE(v);
982
        do_twos_comp = 0;
983
    }
984
985
    if (little_endian) {
  Branch (985:9): [True: 303k, False: 234k]
986
        p = bytes;
987
        pincr = 1;
988
    }
989
    else {
990
        p = bytes + n - 1;
991
        pincr = -1;
992
    }
993
994
    /* Copy over all the Python digits.
995
       It's crucial that every Python digit except for the MSD contribute
996
       exactly PyLong_SHIFT bits to the total, so first assert that the int is
997
       normalized. */
998
    assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
999
    j = 0;
1000
    accum = 0;
1001
    accumbits = 0;
1002
    carry = do_twos_comp ? 
175.1k
:
0462k
;
  Branch (1002:13): [True: 75.1k, False: 462k]
1003
    for (i = 0; i < ndigits; 
++i12.7M
) {
  Branch (1003:17): [True: 12.7M, False: 537k]
1004
        digit thisdigit = v->ob_digit[i];
1005
        if (do_twos_comp) {
  Branch (1005:13): [True: 428k, False: 12.3M]
1006
            thisdigit = (thisdigit ^ PyLong_MASK) + carry;
1007
            carry = thisdigit >> PyLong_SHIFT;
1008
            thisdigit &= PyLong_MASK;
1009
        }
1010
        /* Because we're going LSB to MSB, thisdigit is more
1011
           significant than what's already in accum, so needs to be
1012
           prepended to accum. */
1013
        accum |= (twodigits)thisdigit << accumbits;
1014
1015
        /* The most-significant digit may be (probably is) at least
1016
           partly empty. */
1017
        if (i == ndigits - 1) {
  Branch (1017:13): [True: 535k, False: 12.2M]
1018
            /* Count # of sign bits -- they needn't be stored,
1019
             * although for signed conversion we need later to
1020
             * make sure at least one sign bit gets stored. */
1021
            digit s = do_twos_comp ? 
thisdigit ^ 75.1k
PyLong_MASK75.1k
:
thisdigit460k
;
  Branch (1021:23): [True: 75.1k, False: 460k]
1022
            while (s != 0) {
  Branch (1022:20): [True: 4.93M, False: 535k]
1023
                s >>= 1;
1024
                accumbits++;
1025
            }
1026
        }
1027
        else
1028
            accumbits += PyLong_SHIFT;
1029
1030
        /* Store as many bytes as possible. */
1031
        while (accumbits >= 8) {
  Branch (1031:16): [True: 46.3M, False: 12.7M]
1032
            if (j >= n)
  Branch (1032:17): [True: 10, False: 46.3M]
1033
                goto Overflow;
1034
            ++j;
1035
            *p = (unsigned char)(accum & 0xff);
1036
            p += pincr;
1037
            accumbits -= 8;
1038
            accum >>= 8;
1039
        }
1040
    }
1041
1042
    /* Store the straggler (if any). */
1043
    assert(accumbits < 8);
1044
    assert(carry == 0);  /* else do_twos_comp and *every* digit was 0 */
1045
    if (accumbits > 0) {
  Branch (1045:9): [True: 414k, False: 122k]
1046
        if (j >= n)
  Branch (1046:13): [True: 209, False: 414k]
1047
            goto Overflow;
1048
        ++j;
1049
        if (do_twos_comp) {
  Branch (1049:13): [True: 73.3k, False: 341k]
1050
            /* Fill leading bits of the byte with sign bits
1051
               (appropriately pretending that the int had an
1052
               infinite supply of sign bits). */
1053
            accum |= (~(twodigits)0) << accumbits;
1054
        }
1055
        *p = (unsigned char)(accum & 0xff);
1056
        p += pincr;
1057
    }
1058
    else if (j == n && 
n > 075.1k
&&
is_signed75.1k
) {
  Branch (1058:14): [True: 75.1k, False: 47.7k]
  Branch (1058:24): [True: 75.1k, False: 5]
  Branch (1058:33): [True: 1.20k, False: 73.9k]
1059
        /* The main loop filled the byte array exactly, so the code
1060
           just above didn't get to ensure there's a sign bit, and the
1061
           loop below wouldn't add one either.  Make sure a sign bit
1062
           exists. */
1063
        unsigned char msb = *(p - pincr);
1064
        int sign_bit_set = msb >= 0x80;
1065
        assert(accumbits == 0);
1066
        if (sign_bit_set == do_twos_comp)
  Branch (1066:13): [True: 0, False: 1.20k]
1067
            return 0;
1068
        else
1069
            goto Overflow;
1070
    }
1071
1072
    /* Fill remaining bytes with copies of the sign bit. */
1073
    {
1074
        unsigned char signbyte = do_twos_comp ? 
0xffU74.5k
:
0U461k
;
  Branch (1074:34): [True: 74.5k, False: 461k]
1075
        for ( ; j < n; 
++j, p += pincr506k
)
  Branch (1075:17): [True: 506k, False: 536k]
1076
            *p = signbyte;
1077
    }
1078
1079
    return 0;
1080
1081
  Overflow:
1082
    PyErr_SetString(PyExc_OverflowError, "int too big to convert");
1083
    return -1;
1084
1085
}
1086
1087
/* Create a new int object from a C pointer */
1088
1089
PyObject *
1090
PyLong_FromVoidPtr(void *p)
1091
{
1092
#if SIZEOF_VOID_P <= SIZEOF_LONG
1093
    return PyLong_FromUnsignedLong((unsigned long)(uintptr_t)p);
1094
#else
1095
1096
#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
1097
#   error "PyLong_FromVoidPtr: sizeof(long long) < sizeof(void*)"
1098
#endif
1099
    return PyLong_FromUnsignedLongLong((unsigned long long)(uintptr_t)p);
1100
#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
1101
1102
}
1103
1104
/* Get a C pointer from an int object. */
1105
1106
void *
1107
PyLong_AsVoidPtr(PyObject *vv)
1108
{
1109
#if SIZEOF_VOID_P <= SIZEOF_LONG
1110
    long x;
1111
1112
    if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
  Branch (1112:29): [True: 0, False: 58.8k]
1113
        x = PyLong_AsLong(vv);
1114
    else
1115
        x = PyLong_AsUnsignedLong(vv);
1116
#else
1117
1118
#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
1119
#   error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)"
1120
#endif
1121
    long long x;
1122
1123
    if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1124
        x = PyLong_AsLongLong(vv);
1125
    else
1126
        x = PyLong_AsUnsignedLongLong(vv);
1127
1128
#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
1129
1130
    if (x == -1 && 
PyErr_Occurred()4
)
  Branch (1130:9): [True: 4, False: 58.8k]
  Branch (1130:20): [True: 3, False: 1]
1131
        return NULL;
1132
    return (void *)x;
1133
}
1134
1135
/* Initial long long support by Chris Herborth (chrish@qnx.com), later
1136
 * rewritten to use the newer PyLong_{As,From}ByteArray API.
1137
 */
1138
1139
#define PY_ABS_LLONG_MIN (0-(unsigned long long)LLONG_MIN)
1140
1141
/* Create a new int object from a C long long int. */
1142
1143
PyObject *
1144
PyLong_FromLongLong(long long ival)
1145
{
1146
    PyLongObject *v;
1147
    unsigned long long abs_ival, t;
1148
    int ndigits;
1149
1150
    /* Handle small and medium cases. */
1151
    if (IS_SMALL_INT(ival)) {
1152
        return get_small_int((sdigit)ival);
1153
    }
1154
    if (-(long long)PyLong_MASK <= ival && 
ival <= (long long)1.83M
PyLong_MASK1.83M
) {
  Branch (1154:9): [True: 1.83M, False: 146k]
  Branch (1154:44): [True: 689k, False: 1.14M]
1155
        return _PyLong_FromMedium((sdigit)ival);
1156
    }
1157
1158
    /* Count digits (at least two - smaller cases were handled above). */
1159
    abs_ival = ival < 0 ? 
0U-(unsigned long long)ival146k
:
(unsigned long long)ival1.14M
;
  Branch (1159:16): [True: 146k, False: 1.14M]
1160
    /* Do shift in two steps to avoid possible undefined behavior. */
1161
    t = abs_ival >> PyLong_SHIFT >> PyLong_SHIFT;
1162
    ndigits = 2;
1163
    while (t) {
  Branch (1163:12): [True: 225k, False: 1.29M]
1164
        ++ndigits;
1165
        t >>= PyLong_SHIFT;
1166
    }
1167
1168
    /* Construct output value. */
1169
    v = _PyLong_New(ndigits);
1170
    if (v != NULL) {
  Branch (1170:9): [True: 1.29M, False: 0]
1171
        digit *p = v->ob_digit;
1172
        Py_SET_SIZE(v, ival < 0 ? -ndigits : ndigits);
1173
        t = abs_ival;
1174
        while (t) {
  Branch (1174:16): [True: 2.80M, False: 1.29M]
1175
            *p++ = (digit)(t & PyLong_MASK);
1176
            t >>= PyLong_SHIFT;
1177
        }
1178
    }
1179
    return (PyObject *)v;
1180
}
1181
1182
/* Create a new int object from a C Py_ssize_t. */
1183
1184
PyObject *
1185
PyLong_FromSsize_t(Py_ssize_t ival)
1186
{
1187
    PyLongObject *v;
1188
    size_t abs_ival;
1189
    size_t t;  /* unsigned so >> doesn't propagate sign bit */
1190
    int ndigits = 0;
1191
    int negative = 0;
1192
1193
    if (IS_SMALL_INT(ival)) {
1194
        return get_small_int((sdigit)ival);
1195
    }
1196
1197
    if (ival < 0) {
  Branch (1197:9): [True: 1.05M, False: 14.0M]
1198
        /* avoid signed overflow when ival = SIZE_T_MIN */
1199
        abs_ival = (size_t)(-1-ival)+1;
1200
        negative = 1;
1201
    }
1202
    else {
1203
        abs_ival = (size_t)ival;
1204
    }
1205
1206
    /* Count the number of Python digits. */
1207
    t = abs_ival;
1208
    while (t) {
  Branch (1208:12): [True: 18.5M, False: 15.1M]
1209
        ++ndigits;
1210
        t >>= PyLong_SHIFT;
1211
    }
1212
    v = _PyLong_New(ndigits);
1213
    if (v != NULL) {
  Branch (1213:9): [True: 15.1M, False: 0]
1214
        digit *p = v->ob_digit;
1215
        Py_SET_SIZE(v, negative ? -ndigits : ndigits);
1216
        t = abs_ival;
1217
        while (t) {
  Branch (1217:16): [True: 18.5M, False: 15.1M]
1218
            *p++ = (digit)(t & PyLong_MASK);
1219
            t >>= PyLong_SHIFT;
1220
        }
1221
    }
1222
    return (PyObject *)v;
1223
}
1224
1225
/* Get a C long long int from an int object or any object that has an
1226
   __index__ method.  Return -1 and set an error if overflow occurs. */
1227
1228
long long
1229
PyLong_AsLongLong(PyObject *vv)
1230
{
1231
    PyLongObject *v;
1232
    long long bytes;
1233
    int res;
1234
    int do_decref = 0; /* if PyNumber_Index was called */
1235
1236
    if (vv == NULL) {
  Branch (1236:9): [True: 0, False: 280k]
1237
        PyErr_BadInternalCall();
1238
        return -1;
1239
    }
1240
1241
    if (PyLong_Check(vv)) {
1242
        v = (PyLongObject *)vv;
1243
    }
1244
    else {
1245
        v = (PyLongObject *)_PyNumber_Index(vv);
1246
        if (v == NULL)
  Branch (1246:13): [True: 35, False: 12]
1247
            return -1;
1248
        do_decref = 1;
1249
    }
1250
1251
    res = 0;
1252
    switch(Py_SIZE(v)) {
1253
    case -1:
  Branch (1253:5): [True: 20.8k, False: 259k]
1254
        bytes = -(sdigit)v->ob_digit[0];
1255
        break;
1256
    case 0:
  Branch (1256:5): [True: 54.2k, False: 226k]
1257
        bytes = 0;
1258
        break;
1259
    case 1:
  Branch (1259:5): [True: 48.1k, False: 232k]
1260
        bytes = v->ob_digit[0];
1261
        break;
1262
    default:
  Branch (1262:5): [True: 157k, False: 123k]
1263
        res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
1264
                                  SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
1265
    }
1266
    if (do_decref) {
  Branch (1266:9): [True: 12, False: 280k]
1267
        Py_DECREF(v);
1268
    }
1269
1270
    /* Plan 9 can't handle long long in ? : expressions */
1271
    if (res < 0)
  Branch (1271:9): [True: 891, False: 279k]
1272
        return (long long)-1;
1273
    else
1274
        return bytes;
1275
}
1276
1277
/* Get a C unsigned long long int from an int object.
1278
   Return -1 and set an error if overflow occurs. */
1279
1280
unsigned long long
1281
PyLong_AsUnsignedLongLong(PyObject *vv)
1282
{
1283
    PyLongObject *v;
1284
    unsigned long long bytes;
1285
    int res;
1286
1287
    if (vv == NULL) {
  Branch (1287:9): [True: 0, False: 172k]
1288
        PyErr_BadInternalCall();
1289
        return (unsigned long long)-1;
1290
    }
1291
    if (!PyLong_Check(vv)) {
  Branch (1291:9): [True: 9, False: 172k]
1292
        PyErr_SetString(PyExc_TypeError, "an integer is required");
1293
        return (unsigned long long)-1;
1294
    }
1295
1296
    v = (PyLongObject*)vv;
1297
    switch(Py_SIZE(v)) {
1298
    case 0: return 0;
  Branch (1298:5): [True: 4.41k, False: 168k]
1299
    case 1: return v->ob_digit[0];
  Branch (1299:5): [True: 36.5k, False: 136k]
1300
    }
1301
1302
    res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1303
                              SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
1304
1305
    /* Plan 9 can't handle long long in ? : expressions */
1306
    if (res < 0)
  Branch (1306:9): [True: 1.66k, False: 130k]
1307
        return (unsigned long long)res;
1308
    else
1309
        return bytes;
1310
}
1311
1312
/* Get a C unsigned long int from an int object, ignoring the high bits.
1313
   Returns -1 and sets an error condition if an error occurs. */
1314
1315
static unsigned long long
1316
_PyLong_AsUnsignedLongLongMask(PyObject *vv)
1317
{
1318
    PyLongObject *v;
1319
    unsigned long long x;
1320
    Py_ssize_t i;
1321
    int sign;
1322
1323
    if (vv == NULL || !PyLong_Check(vv)) {
  Branch (1323:9): [True: 0, False: 37.1k]
  Branch (1323:23): [True: 0, False: 37.1k]
1324
        PyErr_BadInternalCall();
1325
        return (unsigned long long) -1;
1326
    }
1327
    v = (PyLongObject *)vv;
1328
    switch(Py_SIZE(v)) {
1329
    case 0: return 0;
  Branch (1329:5): [True: 16.4k, False: 20.7k]
1330
    case 1: return v->ob_digit[0];
  Branch (1330:5): [True: 20.7k, False: 16.4k]
1331
    }
1332
    i = Py_SIZE(v);
1333
    sign = 1;
1334
    x = 0;
1335
    if (i < 0) {
  Branch (1335:9): [True: 0, False: 4]
1336
        sign = -1;
1337
        i = -i;
1338
    }
1339
    while (--i >= 0) {
  Branch (1339:12): [True: 13, False: 4]
1340
        x = (x << PyLong_SHIFT) | v->ob_digit[i];
1341
    }
1342
    return x * sign;
1343
}
1344
1345
unsigned long long
1346
PyLong_AsUnsignedLongLongMask(PyObject *op)
1347
{
1348
    PyLongObject *lo;
1349
    unsigned long long val;
1350
1351
    if (op == NULL) {
  Branch (1351:9): [True: 1, False: 37.1k]
1352
        PyErr_BadInternalCall();
1353
        return (unsigned long long)-1;
1354
    }
1355
1356
    if (PyLong_Check(op)) {
1357
        return _PyLong_AsUnsignedLongLongMask(op);
1358
    }
1359
1360
    lo = (PyLongObject *)_PyNumber_Index(op);
1361
    if (lo == NULL)
  Branch (1361:9): [True: 0, False: 0]
1362
        return (unsigned long long)-1;
1363
1364
    val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1365
    Py_DECREF(lo);
1366
    return val;
1367
}
1368
1369
/* Get a C long long int from an int object or any object that has an
1370
   __index__ method.
1371
1372
   On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1373
   the result.  Otherwise *overflow is 0.
1374
1375
   For other errors (e.g., TypeError), return -1 and set an error condition.
1376
   In this case *overflow will be 0.
1377
*/
1378
1379
long long
1380
PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1381
{
1382
    /* This version by Tim Peters */
1383
    PyLongObject *v;
1384
    unsigned long long x, prev;
1385
    long long res;
1386
    Py_ssize_t i;
1387
    int sign;
1388
    int do_decref = 0; /* if PyNumber_Index was called */
1389
1390
    *overflow = 0;
1391
    if (vv == NULL) {
  Branch (1391:9): [True: 0, False: 114k]
1392
        PyErr_BadInternalCall();
1393
        return -1;
1394
    }
1395
1396
    if (PyLong_Check(vv)) {
1397
        v = (PyLongObject *)vv;
1398
    }
1399
    else {
1400
        v = (PyLongObject *)_PyNumber_Index(vv);
1401
        if (v == NULL)
  Branch (1401:13): [True: 0, False: 0]
1402
            return -1;
1403
        do_decref = 1;
1404
    }
1405
1406
    res = -1;
1407
    i = Py_SIZE(v);
1408
1409
    switch (i) {
1410
    case -1:
  Branch (1410:5): [True: 2, False: 114k]
1411
        res = -(sdigit)v->ob_digit[0];
1412
        break;
1413
    case 0:
  Branch (1413:5): [True: 1.73k, False: 112k]
1414
        res = 0;
1415
        break;
1416
    case 1:
  Branch (1416:5): [True: 112k, False: 1.77k]
1417
        res = v->ob_digit[0];
1418
        break;
1419
    default:
  Branch (1419:5): [True: 37, False: 114k]
1420
        sign = 1;
1421
        x = 0;
1422
        if (i < 0) {
  Branch (1422:13): [True: 6, False: 31]
1423
            sign = -1;
1424
            i = -(i);
1425
        }
1426
        while (--i >= 0) {
  Branch (1426:16): [True: 108, False: 15]
1427
            prev = x;
1428
            x = (x << PyLong_SHIFT) + v->ob_digit[i];
1429
            if ((x >> PyLong_SHIFT) != prev) {
  Branch (1429:17): [True: 22, False: 86]
1430
                *overflow = sign;
1431
                goto exit;
1432
            }
1433
        }
1434
        /* Haven't lost any bits, but casting to long requires extra
1435
         * care (see comment above).
1436
         */
1437
        if (x <= (unsigned long long)LLONG_MAX) {
  Branch (1437:13): [True: 6, False: 9]
1438
            res = (long long)x * sign;
1439
        }
1440
        else if (sign < 0 && 
x == 5
PY_ABS_LLONG_MIN5
) {
  Branch (1440:18): [True: 5, False: 4]
  Branch (1440:30): [True: 1, False: 4]
1441
            res = LLONG_MIN;
1442
        }
1443
        else {
1444
            *overflow = sign;
1445
            /* res is already set to -1 */
1446
        }
1447
    }
1448
  exit:
1449
    if (do_decref) {
  Branch (1449:9): [True: 0, False: 114k]
1450
        Py_DECREF(v);
1451
    }
1452
    return res;
1453
}
1454
1455
int
1456
_PyLong_UnsignedShort_Converter(PyObject *obj, void *ptr)
1457
{
1458
    unsigned long uval;
1459
1460
    if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
  Branch (1460:30): [True: 2, False: 145k]
1461
        PyErr_SetString(PyExc_ValueError, "value must be positive");
1462
        return 0;
1463
    }
1464
    uval = PyLong_AsUnsignedLong(obj);
1465
    if (uval == (unsigned long)-1 && 
PyErr_Occurred()2
)
  Branch (1465:9): [True: 2, False: 145k]
  Branch (1465:38): [True: 2, False: 0]
1466
        return 0;
1467
    if (uval > USHRT_MAX) {
  Branch (1467:9): [True: 2, False: 145k]
1468
        PyErr_SetString(PyExc_OverflowError,
1469
                        "Python int too large for C unsigned short");
1470
        return 0;
1471
    }
1472
1473
    *(unsigned short *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned short);
1474
    return 1;
1475
}
1476
1477
int
1478
_PyLong_UnsignedInt_Converter(PyObject *obj, void *ptr)
1479
{
1480
    unsigned long uval;
1481
1482
    if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
  Branch (1482:30): [True: 0, False: 4]
1483
        PyErr_SetString(PyExc_ValueError, "value must be positive");
1484
        return 0;
1485
    }
1486
    uval = PyLong_AsUnsignedLong(obj);
1487
    if (uval == (unsigned long)-1 && 
PyErr_Occurred()0
)
  Branch (1487:9): [True: 0, False: 4]
  Branch (1487:38): [True: 0, False: 0]
1488
        return 0;
1489
    if (uval > UINT_MAX) {
  Branch (1489:9): [True: 0, False: 4]
1490
        PyErr_SetString(PyExc_OverflowError,
1491
                        "Python int too large for C unsigned int");
1492
        return 0;
1493
    }
1494
1495
    *(unsigned int *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned int);
1496
    return 1;
1497
}
1498
1499
int
1500
_PyLong_UnsignedLong_Converter(PyObject *obj, void *ptr)
1501
{
1502
    unsigned long uval;
1503
1504
    if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
  Branch (1504:30): [True: 6, False: 72]
1505
        PyErr_SetString(PyExc_ValueError, "value must be positive");
1506
        return 0;
1507
    }
1508
    uval = PyLong_AsUnsignedLong(obj);
1509
    if (uval == (unsigned long)-1 && 
PyErr_Occurred()4
)
  Branch (1509:9): [True: 4, False: 68]
  Branch (1509:38): [True: 4, False: 0]
1510
        return 0;
1511
1512
    *(unsigned long *)ptr = uval;
1513
    return 1;
1514
}
1515
1516
int
1517
_PyLong_UnsignedLongLong_Converter(PyObject *obj, void *ptr)
1518
{
1519
    unsigned long long uval;
1520
1521
    if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
  Branch (1521:30): [True: 2, False: 17]
1522
        PyErr_SetString(PyExc_ValueError, "value must be positive");
1523
        return 0;
1524
    }
1525
    uval = PyLong_AsUnsignedLongLong(obj);
1526
    if (uval == (unsigned long long)-1 && 
PyErr_Occurred()2
)
  Branch (1526:9): [True: 2, False: 15]
  Branch (1526:43): [True: 1, False: 1]
1527
        return 0;
1528
1529
    *(unsigned long long *)ptr = uval;
1530
    return 1;
1531
}
1532
1533
int
1534
_PyLong_Size_t_Converter(PyObject *obj, void *ptr)
1535
{
1536
    size_t uval;
1537
1538
    if (PyLong_Check(obj) && _PyLong_Sign(obj) < 0) {
  Branch (1538:30): [True: 0, False: 0]
1539
        PyErr_SetString(PyExc_ValueError, "value must be positive");
1540
        return 0;
1541
    }
1542
    uval = PyLong_AsSize_t(obj);
1543
    if (uval == (size_t)-1 && PyErr_Occurred())
  Branch (1543:9): [True: 0, False: 0]
  Branch (1543:31): [True: 0, False: 0]
1544
        return 0;
1545
1546
    *(size_t *)ptr = uval;
1547
    return 1;
1548
}
1549
1550
1551
#define CHECK_BINOP(v,w)                                \
1552
    do {                                                \
1553
        if (!PyLong_Check(v) || 
!108M
PyLong_Check108M
(w)) \
1554
            
Py_RETURN_NOTIMPLEMENTED2.18M
; \
1555
    } while(
0107M
)
1556
1557
/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required.  x[0:n]
1558
 * is modified in place, by adding y to it.  Carries are propagated as far as
1559
 * x[m-1], and the remaining carry (0 or 1) is returned.
1560
 */
1561
static digit
1562
v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
1563
{
1564
    Py_ssize_t i;
1565
    digit carry = 0;
1566
1567
    assert(m >= n);
1568
    for (i = 0; i < n; 
++i1.53M
) {
  Branch (1568:17): [True: 1.53M, False: 8.62k]
1569
        carry += x[i] + y[i];
1570
        x[i] = carry & PyLong_MASK;
1571
        carry >>= PyLong_SHIFT;
1572
        assert((carry & 1) == carry);
1573
    }
1574
    for (; carry && 
i < m272k
;
++i272k
) {
  Branch (1574:12): [True: 272k, False: 8.62k]
  Branch (1574:21): [True: 272k, False: 0]
1575
        carry += x[i];
1576
        x[i] = carry & PyLong_MASK;
1577
        carry >>= PyLong_SHIFT;
1578
        assert((carry & 1) == carry);
1579
    }
1580
    return carry;
1581
}
1582
1583
/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required.  x[0:n]
1584
 * is modified in place, by subtracting y from it.  Borrows are propagated as
1585
 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1586
 */
1587
static digit
1588
v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
1589
{
1590
    Py_ssize_t i;
1591
    digit borrow = 0;
1592
1593
    assert(m >= n);
1594
    for (i = 0; i < n; 
++i2.13M
) {
  Branch (1594:17): [True: 2.13M, False: 15.0k]
1595
        borrow = x[i] - y[i] - borrow;
1596
        x[i] = borrow & PyLong_MASK;
1597
        borrow >>= PyLong_SHIFT;
1598
        borrow &= 1;            /* keep only 1 sign bit */
1599
    }
1600
    for (; borrow && 
i < m278k
;
++i278k
) {
  Branch (1600:12): [True: 278k, False: 15.0k]
  Branch (1600:22): [True: 278k, False: 0]
1601
        borrow = x[i] - borrow;
1602
        x[i] = borrow & PyLong_MASK;
1603
        borrow >>= PyLong_SHIFT;
1604
        borrow &= 1;
1605
    }
1606
    return borrow;
1607
}
1608
1609
/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT.  Put
1610
 * result in z[0:m], and return the d bits shifted out of the top.
1611
 */
1612
static digit
1613
v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
1614
{
1615
    Py_ssize_t i;
1616
    digit carry = 0;
1617
1618
    assert(0 <= d && d < PyLong_SHIFT);
1619
    for (i=0; i < m; 
i++30.5M
) {
  Branch (1619:15): [True: 30.5M, False: 7.21M]
1620
        twodigits acc = (twodigits)a[i] << d | carry;
1621
        z[i] = (digit)acc & PyLong_MASK;
1622
        carry = (digit)(acc >> PyLong_SHIFT);
1623
    }
1624
    return carry;
1625
}
1626
1627
/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT.  Put
1628
 * result in z[0:m], and return the d bits shifted out of the bottom.
1629
 */
1630
static digit
1631
v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1632
{
1633
    Py_ssize_t i;
1634
    digit carry = 0;
1635
    digit mask = ((digit)1 << d) - 1U;
1636
1637
    assert(0 <= d && d < PyLong_SHIFT);
1638
    for (i=m; i-- > 0;) {
  Branch (1638:15): [True: 13.2M, False: 3.59M]
1639
        twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1640
        carry = (digit)acc & mask;
1641
        z[i] = (digit)(acc >> d);
1642
    }
1643
    return carry;
1644
}
1645
1646
/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1647
   in pout, and returning the remainder.  pin and pout point at the LSD.
1648
   It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
1649
   _PyLong_Format, but that should be done with great care since ints are
1650
   immutable.
1651
1652
   This version of the code can be 20% faster than the pre-2022 version
1653
   on todays compilers on architectures like amd64.  It evolved from Mark
1654
   Dickinson observing that a 128:64 divide instruction was always being
1655
   generated by the compiler despite us working with 30-bit digit values.
1656
   See the thread for full context:
1657
1658
     https://mail.python.org/archives/list/python-dev@python.org/thread/ZICIMX5VFCX4IOFH5NUPVHCUJCQ4Q7QM/#NEUNFZU3TQU4CPTYZNF3WCN7DOJBBTK5
1659
1660
   If you ever want to change this code, pay attention to performance using
1661
   different compilers, optimization levels, and cpu architectures. Beware of
1662
   PGO/FDO builds doing value specialization such as a fast path for //10. :)
1663
1664
   Verify that 17 isn't specialized and this works as a quick test:
1665
     python -m timeit -s 'x = 10**1000; r=x//10; assert r == 10**999, r' 'x//17'
1666
*/
1667
static digit
1668
inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
1669
{
1670
    digit remainder = 0;
1671
1672
    assert(n > 0 && n <= PyLong_MASK);
1673
    while (--size >= 0) {
  Branch (1673:12): [True: 6.31M, False: 428k]
1674
        twodigits dividend;
1675
        dividend = ((twodigits)remainder << PyLong_SHIFT) | pin[size];
1676
        digit quotient;
1677
        quotient = (digit)(dividend / n);
1678
        remainder = dividend % n;
1679
        pout[size] = quotient;
1680
    }
1681
    return remainder;
1682
}
1683
1684
1685
/* Divide an integer by a digit, returning both the quotient
1686
   (as function result) and the remainder (through *prem).
1687
   The sign of a is ignored; n should not be zero. */
1688
1689
static PyLongObject *
1690
divrem1(PyLongObject *a, digit n, digit *prem)
1691
{
1692
    const Py_ssize_t size = Py_ABS(Py_SIZE(a));
1693
    PyLongObject *z;
1694
1695
    assert(n > 0 && n <= PyLong_MASK);
1696
    z = _PyLong_New(size);
1697
    if (z == NULL)
  Branch (1697:9): [True: 0, False: 412k]
1698
        return NULL;
1699
    *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1700
    return long_normalize(z);
1701
}
1702
1703
/* Remainder of long pin, w/ size digits, by non-zero digit n,
1704
   returning the remainder. pin points at the LSD. */
1705
1706
static digit
1707
inplace_rem1(digit *pin, Py_ssize_t size, digit n)
1708
{
1709
    twodigits rem = 0;
1710
1711
    assert(n > 0 && n <= PyLong_MASK);
1712
    while (--size >= 0)
  Branch (1712:12): [True: 39.8M, False: 17.3M]
1713
        rem = ((rem << PyLong_SHIFT) | pin[size]) % n;
1714
    return (digit)rem;
1715
}
1716
1717
/* Get the remainder of an integer divided by a digit, returning
1718
   the remainder as the result of the function. The sign of a is
1719
   ignored; n should not be zero. */
1720
1721
static PyLongObject *
1722
rem1(PyLongObject *a, digit n)
1723
{
1724
    const Py_ssize_t size = Py_ABS(Py_SIZE(a));
1725
1726
    assert(n > 0 && n <= PyLong_MASK);
1727
    return (PyLongObject *)PyLong_FromLong(
1728
        (long)inplace_rem1(a->ob_digit, size, n)
1729
    );
1730
}
1731
1732
/* Convert an integer to a base 10 string.  Returns a new non-shared
1733
   string.  (Return value is non-shared so that callers can modify the
1734
   returned value if necessary.) */
1735
1736
static int
1737
long_to_decimal_string_internal(PyObject *aa,
1738
                                PyObject **p_output,
1739
                                _PyUnicodeWriter *writer,
1740
                                _PyBytesWriter *bytes_writer,
1741
                                char **bytes_str)
1742
{
1743
    PyLongObject *scratch, *a;
1744
    PyObject *str = NULL;
1745
    Py_ssize_t size, strlen, size_a, i, j;
1746
    digit *pout, *pin, rem, tenpow;
1747
    int negative;
1748
    int d;
1749
    int kind;
1750
1751
    a = (PyLongObject *)aa;
1752
    if (a == NULL || !PyLong_Check(a)) {
  Branch (1752:9): [True: 0, False: 12.8M]
  Branch (1752:22): [True: 0, False: 12.8M]
1753
        PyErr_BadInternalCall();
1754
        return -1;
1755
    }
1756
    size_a = Py_ABS(Py_SIZE(a));
1757
    negative = Py_SIZE(a) < 0;
1758
1759
    /* quick and dirty upper bound for the number of digits
1760
       required to express a in base _PyLong_DECIMAL_BASE:
1761
1762
         #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
1763
1764
       But log2(a) < size_a * PyLong_SHIFT, and
1765
       log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1766
                                  > 3.3 * _PyLong_DECIMAL_SHIFT
1767
1768
         size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) =
1769
             size_a + size_a / d < size_a + size_a / floor(d),
1770
       where d = (3.3 * _PyLong_DECIMAL_SHIFT) /
1771
                 (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT)
1772
    */
1773
    d = (33 * _PyLong_DECIMAL_SHIFT) /
1774
        (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT);
1775
    assert(size_a < PY_SSIZE_T_MAX/2);
1776
    size = 1 + size_a + size_a / d;
1777
    scratch = _PyLong_New(size);
1778
    if (scratch == NULL)
  Branch (1778:9): [True: 0, False: 12.8M]
1779
        return -1;
1780
1781
    /* convert array of base _PyLong_BASE digits in pin to an array of
1782
       base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1783
       Volume 2 (3rd edn), section 4.4, Method 1b). */
1784
    pin = a->ob_digit;
1785
    pout = scratch->ob_digit;
1786
    size = 0;
1787
    for (i = size_a; --i >= 0; ) {
  Branch (1787:22): [True: 22.2M, False: 12.8M]
1788
        digit hi = pin[i];
1789
        for (j = 0; j < size; 
j++102M
) {
  Branch (1789:21): [True: 102M, False: 22.2M]
1790
            twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1791
            hi = (digit)(z / _PyLong_DECIMAL_BASE);
1792
            pout[j] = (digit)(z - (twodigits)hi *
1793
                              _PyLong_DECIMAL_BASE);
1794
        }
1795
        while (hi) {
  Branch (1795:16): [True: 22.2M, False: 22.2M]
1796
            pout[size++] = hi % _PyLong_DECIMAL_BASE;
1797
            hi /= _PyLong_DECIMAL_BASE;
1798
        }
1799
        /* check for keyboard interrupt */
1800
        SIGCHECK({
1801
                Py_DECREF(scratch);
1802
                return -1;
1803
            });
1804
    }
1805
    /* pout should have at least one digit, so that the case when a = 0
1806
       works correctly */
1807
    if (size == 0)
  Branch (1807:9): [True: 2.07M, False: 10.8M]
1808
        pout[size++] = 0;
1809
1810
    /* calculate exact length of output string, and allocate */
1811
    strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1812
    tenpow = 10;
1813
    rem = pout[size-1];
1814
    while (rem >= tenpow) {
  Branch (1814:12): [True: 24.5M, False: 12.8M]
1815
        tenpow *= 10;
1816
        strlen++;
1817
    }
1818
    if (writer) {
  Branch (1818:9): [True: 9.02M, False: 3.86M]
1819
        if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
  Branch (1819:13): [True: 0, False: 9.02M]
1820
            Py_DECREF(scratch);
1821
            return -1;
1822
        }
1823
        kind = writer->kind;
1824
    }
1825
    else if (bytes_writer) {
  Branch (1825:14): [True: 88, False: 3.86M]
1826
        *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
1827
        if (*bytes_str == NULL) {
  Branch (1827:13): [True: 0, False: 88]
1828
            Py_DECREF(scratch);
1829
            return -1;
1830
        }
1831
    }
1832
    else {
1833
        str = PyUnicode_New(strlen, '9');
1834
        if (str == NULL) {
  Branch (1834:13): [True: 0, False: 3.86M]
1835
            Py_DECREF(scratch);
1836
            return -1;
1837
        }
1838
        kind = PyUnicode_KIND(str);
1839
    }
1840
1841
#define WRITE_DIGITS(p)                                               \
1842
    do {                                                              \
1843
        /* pout[0] through pout[size-2] contribute exactly            \
1844
           _PyLong_DECIMAL_SHIFT digits each */                       \
1845
        for (i=0; i < size - 1; 
i++11.4M
) { \
1846
            rem = pout[i];                                            \
1847
            for (j = 0; j < _PyLong_DECIMAL_SHIFT; 
j++103M
) { \
1848
                *--p = '0' + rem % 10;                                \
1849
                rem /= 10;                                            \
1850
            }                                                         \
1851
        }                                                             \
1852
        /* pout[size-1]: always produce at least one decimal digit */ \
1853
        rem = pout[i];                                                \
1854
        do {                                                          \
1855
            *--p = '0' + rem % 10;                                    \
1856
            rem /= 10;                                                \
1857
        } while (rem != 0);                                           \
1858
                                                                      \
1859
        /* and sign */                                                \
1860
        if (negative)                                                 \
1861
            
*--p = '-'155k
; \
1862
    } while (0)
1863
1864
#define WRITE_UNICODE_DIGITS(TYPE)                                    \
1865
    
do 12.8M
{ \
1866
        if (writer)                                                   \
1867
            
p = (TYPE*)9.02M
PyUnicode_DATA9.02M
(writer->buffer) + writer->pos + strlen; \
1868
        else                                                          \
1869
            
p = (TYPE*)3.86M
PyUnicode_DATA3.86M
(str) + strlen; \
1870
                                                                      \
1871
        WRITE_DIGITS(p);                                              \
1872
                                                                      \
1873
        /* check we've counted correctly */                           \
1874
        if (writer)                                                   \
1875
            assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1876
        else                                                          \
1877
            assert(p == (TYPE*)PyUnicode_DATA(str));                  \
1878
    } while (0)
1879
1880
    /* fill the string right-to-left */
1881
    if (bytes_writer) {
  Branch (1881:9): [True: 88, False: 12.8M]
1882
        char *p = *bytes_str + strlen;
1883
        WRITE_DIGITS(p);
1884
        assert(p == *bytes_str);
1885
    }
1886
    else if (kind == PyUnicode_1BYTE_KIND) {
  Branch (1886:14): [True: 12.8M, False: 11]
1887
        Py_UCS1 *p;
1888
        WRITE_UNICODE_DIGITS(Py_UCS1);
1889
    }
1890
    else if (kind == PyUnicode_2BYTE_KIND) {
  Branch (1890:14): [True: 11, False: 0]
1891
        Py_UCS2 *p;
1892
        WRITE_UNICODE_DIGITS(Py_UCS2);
1893
    }
1894
    else {
1895
        Py_UCS4 *p;
1896
        assert (kind == PyUnicode_4BYTE_KIND);
1897
        WRITE_UNICODE_DIGITS(Py_UCS4);
1898
    }
1899
#undef WRITE_DIGITS
1900
#undef WRITE_UNICODE_DIGITS
1901
1902
    _Py_DECREF_INT(scratch);
1903
    if (writer) {
  Branch (1903:9): [True: 9.02M, False: 3.86M]
1904
        writer->pos += strlen;
1905
    }
1906
    else if (bytes_writer) {
  Branch (1906:14): [True: 88, False: 3.86M]
1907
        (*bytes_str) += strlen;
1908
    }
1909
    else {
1910
        assert(_PyUnicode_CheckConsistency(str, 1));
1911
        *p_output = (PyObject *)str;
1912
    }
1913
    return 0;
1914
}
1915
1916
static PyObject *
1917
long_to_decimal_string(PyObject *aa)
1918
{
1919
    PyObject *v;
1920
    if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1)
  Branch (1920:9): [True: 0, False: 3.78M]
1921
        return NULL;
1922
    return v;
1923
}
1924
1925
/* Convert an int object to a string, using a given conversion base,
1926
   which should be one of 2, 8 or 16.  Return a string object.
1927
   If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1928
   if alternate is nonzero. */
1929
1930
static int
1931
long_format_binary(PyObject *aa, int base, int alternate,
1932
                   PyObject **p_output, _PyUnicodeWriter *writer,
1933
                   _PyBytesWriter *bytes_writer, char **bytes_str)
1934
{
1935
    PyLongObject *a = (PyLongObject *)aa;
1936
    PyObject *v = NULL;
1937
    Py_ssize_t sz;
1938
    Py_ssize_t size_a;
1939
    int kind;
1940
    int negative;
1941
    int bits;
1942
1943
    assert(base == 2 || base == 8 || base == 16);
1944
    if (a == NULL || !PyLong_Check(a)) {
  Branch (1944:9): [True: 0, False: 767k]
  Branch (1944:22): [True: 0, False: 767k]
1945
        PyErr_BadInternalCall();
1946
        return -1;
1947
    }
1948
    size_a = Py_ABS(Py_SIZE(a));
1949
    negative = Py_SIZE(a) < 0;
1950
1951
    /* Compute a rough upper bound for the length of the string */
1952
    switch (base) {
1953
    case 16:
  Branch (1953:5): [True: 621k, False: 145k]
1954
        bits = 4;
1955
        break;
1956
    case 8:
  Branch (1956:5): [True: 10.9k, False: 756k]
1957
        bits = 3;
1958
        break;
1959
    case 2:
  Branch (1959:5): [True: 134k, False: 632k]
1960
        bits = 1;
1961
        break;
1962
    default:
  Branch (1962:5): [True: 0, False: 767k]
1963
        Py_UNREACHABLE();
1964
    }
1965
1966
    /* Compute exact length 'sz' of output string. */
1967
    if (size_a == 0) {
  Branch (1967:9): [True: 69.2k, False: 698k]
1968
        sz = 1;
1969
    }
1970
    else {
1971
        Py_ssize_t size_a_in_bits;
1972
        /* Ensure overflow doesn't occur during computation of sz. */
1973
        if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
  Branch (1973:13): [True: 0, False: 698k]
1974
            PyErr_SetString(PyExc_OverflowError,
1975
                            "int too large to format");
1976
            return -1;
1977
        }
1978
        size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1979
                         bit_length_digit(a->ob_digit[size_a - 1]);
1980
        /* Allow 1 character for a '-' sign. */
1981
        sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1982
    }
1983
    if (alternate) {
  Branch (1983:9): [True: 717k, False: 49.6k]
1984
        /* 2 characters for prefix  */
1985
        sz += 2;
1986
    }
1987
1988
    if (writer) {
  Branch (1988:9): [True: 49.2k, False: 718k]
1989
        if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
  Branch (1989:13): [True: 0, False: 49.2k]
1990
            return -1;
1991
        kind = writer->kind;
1992
    }
1993
    else if (bytes_writer) {
  Branch (1993:14): [True: 556, False: 717k]
1994
        *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz);
1995
        if (*bytes_str == NULL)
  Branch (1995:13): [True: 0, False: 556]
1996
            return -1;
1997
    }
1998
    else {
1999
        v = PyUnicode_New(sz, 'x');
2000
        if (v == NULL)
  Branch (2000:13): [True: 0, False: 717k]
2001
            return -1;
2002
        kind = PyUnicode_KIND(v);
2003
    }
2004
2005
#define WRITE_DIGITS(p)                                                 \
2006
    do {                                                                \
2007
        if (size_a == 0) {                                              \
2008
            *--p = '0';                                                 \
2009
        }                                                               \
2010
        else {                                                          \
2011
            /* JRH: special case for power-of-2 bases */                \
2012
            twodigits accum = 0;                                        \
2013
            int accumbits = 0;   /* # of bits in accum */               \
2014
            Py_ssize_t i;                                               \
2015
            for (i = 0; i < size_a; 
++i744k
) { \
2016
                accum |= (twodigits)a->ob_digit[i] << accumbits;        \
2017
                accumbits += PyLong_SHIFT;                              \
2018
                assert(accumbits >= bits);                              \
2019
                do {                                                    \
2020
                    char cdigit;                                        \
2021
                    cdigit = (char)(accum & (base - 1));                \
2022
                    cdigit += (cdigit < 10) ? 
'0'3.29M
:
'a'-10691k
; \
2023
                    *--p = cdigit;                                      \
2024
                    accumbits -= bits;                                  \
2025
                    accum >>= bits;                                     \
2026
                } while (i < size_a-1 ? 
accumbits >= bits496k
:
accum > 03.49M
); \
2027
            }                                                           \
2028
        }                                                               \
2029
                                                                        \
2030
        if (alternate) {                                                \
2031
            if (base == 16)                                             \
2032
                
*--p = 'x'573k
; \
2033
            else 
if (144k
base == 8144k
) \
2034
                
*--p = 'o'9.78k
; \
2035
            else /* (base == 2) */                                      \
2036
                
*--p = 'b'134k
; \
2037
            *--p = '0';                                                 \
2038
        }                                                               \
2039
        if (negative)                                                   \
2040
            
*--p = '-'69.4k
; \
2041
    } while (0)
2042
2043
#define WRITE_UNICODE_DIGITS(TYPE)                                      \
2044
    
do 766k
{ \
2045
        if (writer)                                                     \
2046
            
p = (TYPE*)49.2k
PyUnicode_DATA49.2k
(writer->buffer) + writer->pos + sz; \
2047
        else                                                            \
2048
            
p = (TYPE*)717k
PyUnicode_DATA717k
(v) + sz; \
2049
                                                                        \
2050
        WRITE_DIGITS(p);                                                \
2051
                                                                        \
2052
        if (writer)                                                     \
2053
            assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
2054
        else                                                            \
2055
            assert(p == (TYPE*)PyUnicode_DATA(v));                      \
2056
    } while (0)
2057
2058
    if (bytes_writer) {
  Branch (2058:9): [True: 556, False: 766k]
2059
        char *p = *bytes_str + sz;
2060
        WRITE_DIGITS(p);
2061
        assert(p == *bytes_str);
2062
    }
2063
    else if (kind == PyUnicode_1BYTE_KIND) {
  Branch (2063:14): [True: 766k, False: 0]
2064
        Py_UCS1 *p;
2065
        WRITE_UNICODE_DIGITS(Py_UCS1);
2066
    }
2067
    else if (kind == PyUnicode_2BYTE_KIND) {
  Branch (2067:14): [True: 0, False: 0]
2068
        Py_UCS2 *p;
2069
        WRITE_UNICODE_DIGITS(Py_UCS2);
2070
    }
2071
    else {
2072
        Py_UCS4 *p;
2073
        assert (kind == PyUnicode_4BYTE_KIND);
2074
        WRITE_UNICODE_DIGITS(Py_UCS4);
2075
    }
2076
#undef WRITE_DIGITS
2077
#undef WRITE_UNICODE_DIGITS
2078
2079
    if (writer) {
  Branch (2079:9): [True: 49.2k, False: 718k]
2080
        writer->pos += sz;
2081
    }
2082
    else if (bytes_writer) {
  Branch (2082:14): [True: 556, False: 717k]
2083
        (*bytes_str) += sz;
2084
    }
2085
    else {
2086
        assert(_PyUnicode_CheckConsistency(v, 1));
2087
        *p_output = v;
2088
    }
2089
    return 0;
2090
}
2091
2092
PyObject *
2093
_PyLong_Format(PyObject *obj, int base)
2094
{
2095
    PyObject *str;
2096
    int err;
2097
    if (base == 10)
  Branch (2097:9): [True: 86.5k, False: 717k]
2098
        err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL);
2099
    else
2100
        err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL);
2101
    if (err == -1)
  Branch (2101:9): [True: 0, False: 804k]
2102
        return NULL;
2103
    return str;
2104
}
2105
2106
int
2107
_PyLong_FormatWriter(_PyUnicodeWriter *writer,
2108
                     PyObject *obj,
2109
                     int base, int alternate)
2110
{
2111
    if (base == 10)
  Branch (2111:9): [True: 9.02M, False: 49.2k]
2112
        return long_to_decimal_string_internal(obj, NULL, writer,
2113
                                               NULL, NULL);
2114
    else
2115
        return long_format_binary(obj, base, alternate, NULL, writer,
2116
                                  NULL, NULL);
2117
}
2118
2119
char*
2120
_PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str,
2121
                          PyObject *obj,
2122
                          int base, int alternate)
2123
{
2124
    char *str2;
2125
    int res;
2126
    str2 = str;
2127
    if (base == 10)
  Branch (2127:9): [True: 88, False: 556]
2128
        res = long_to_decimal_string_internal(obj, NULL, NULL,
2129
                                              writer, &str2);
2130
    else
2131
        res = long_format_binary(obj, base, alternate, NULL, NULL,
2132
                                 writer, &str2);
2133
    if (res < 0)
  Branch (2133:9): [True: 0, False: 644]
2134
        return NULL;
2135
    assert(str2 != NULL);
2136
    return str2;
2137
}
2138
2139
/* Table of digit values for 8-bit string -> integer conversion.
2140
 * '0' maps to 0, ..., '9' maps to 9.
2141
 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
2142
 * All other indices map to 37.
2143
 * Note that when converting a base B string, a char c is a legitimate
2144
 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
2145
 */
2146
unsigned char _PyLong_DigitValue[256] = {
2147
    37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2148
    37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2149
    37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2150
    0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  37, 37, 37, 37, 37, 37,
2151
    37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2152
    25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2153
    37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2154
    25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2155
    37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2156
    37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2157
    37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2158
    37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2159
    37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2160
    37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2161
    37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2162
    37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2163
};
2164
2165
/* *str points to the first digit in a string of base `base` digits.  base
2166
 * is a power of 2 (2, 4, 8, 16, or 32).  *str is set to point to the first
2167
 * non-digit (which may be *str!).  A normalized int is returned.
2168
 * The point to this routine is that it takes time linear in the number of
2169
 * string characters.
2170
 *
2171
 * Return values:
2172
 *   -1 on syntax error (exception needs to be set, *res is untouched)
2173
 *   0 else (exception may be set, in that case *res is set to NULL)
2174
 */
2175
static int
2176
long_from_binary_base(const char **str, int base, PyLongObject **res)
2177
{
2178
    const char *p = *str;
2179
    const char *start = p;
2180
    char prev = 0;
2181
    Py_ssize_t digits = 0;
2182
    int bits_per_char;
2183
    Py_ssize_t n;
2184
    PyLongObject *z;
2185
    twodigits accum;
2186
    int bits_in_accum;
2187
    digit *pdigit;
2188
2189
    assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
2190
    n = base;
2191
    for (bits_per_char = -1; n; 
++bits_per_char786k
) {
  Branch (2191:30): [True: 786k, False: 182k]
2192
        n >>= 1;
2193
    }
2194
    /* count digits and set p to end-of-string */
2195
    while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base || 
*p == '_'182k
) {
  Branch (2195:12): [True: 1.35M, False: 182k]
  Branch (2195:58): [True: 71, False: 182k]
2196
        if (*p == '_') {
  Branch (2196:13): [True: 71, False: 1.35M]
2197
            if (prev == '_') {
  Branch (2197:17): [True: 3, False: 68]
2198
                *str = p - 1;
2199
                return -1;
2200
            }
2201
        } else {
2202
            ++digits;
2203
        }
2204
        prev = *p;
2205
        ++p;
2206
    }
2207
    if (prev == '_') {
  Branch (2207:9): [True: 3, False: 182k]
2208
        /* Trailing underscore not allowed. */
2209
        *str = p - 1;
2210
        return -1;
2211
    }
2212
2213
    *str = p;
2214
    /* n <- the number of Python digits needed,
2215
            = ceiling((digits * bits_per_char) / PyLong_SHIFT). */
2216
    if (digits > (PY_SSIZE_T_MAX - (PyLong_SHIFT - 1)) / bits_per_char) {
  Branch (2216:9): [True: 0, False: 182k]
2217
        PyErr_SetString(PyExc_ValueError,
2218
                        "int string too large to convert");
2219
        *res = NULL;
2220
        return 0;
2221
    }
2222
    n = (digits * bits_per_char + PyLong_SHIFT - 1) / PyLong_SHIFT;
2223
    z = _PyLong_New(n);
2224
    if (z == NULL) {
  Branch (2224:9): [True: 0, False: 182k]
2225
        *res = NULL;
2226
        return 0;
2227
    }
2228
    /* Read string from right, and fill in int from left; i.e.,
2229
     * from least to most significant in both.
2230
     */
2231
    accum = 0;
2232
    bits_in_accum = 0;
2233
    pdigit = z->ob_digit;
2234
    while (--p >= start) {
  Branch (2234:12): [True: 1.35M, False: 182k]
2235
        int k;
2236
        if (*p == '_') {
  Branch (2236:13): [True: 62, False: 1.35M]
2237
            continue;
2238
        }
2239
        k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
2240
        assert(k >= 0 && k < base);
2241
        accum |= (twodigits)k << bits_in_accum;
2242
        bits_in_accum += bits_per_char;
2243
        if (bits_in_accum >= PyLong_SHIFT) {
  Branch (2243:13): [True: 39.1k, False: 1.31M]
2244
            *pdigit++ = (digit)(accum & PyLong_MASK);
2245
            assert(pdigit - z->ob_digit <= n);
2246
            accum >>= PyLong_SHIFT;
2247
            bits_in_accum -= PyLong_SHIFT;
2248
            assert(bits_in_accum < PyLong_SHIFT);
2249
        }
2250
    }
2251
    if (bits_in_accum) {
  Branch (2251:9): [True: 181k, False: 577]
2252
        assert(bits_in_accum <= PyLong_SHIFT);
2253
        *pdigit++ = (digit)accum;
2254
        assert(pdigit - z->ob_digit <= n);
2255
    }
2256
    while (pdigit - z->ob_digit < n)
  Branch (2256:12): [True: 0, False: 182k]
2257
        *pdigit++ = 0;
2258
    *res = long_normalize(z);
2259
    return 0;
2260
}
2261
2262
/* Parses an int from a bytestring. Leading and trailing whitespace will be
2263
 * ignored.
2264
 *
2265
 * If successful, a PyLong object will be returned and 'pend' will be pointing
2266
 * to the first unused byte unless it's NULL.
2267
 *
2268
 * If unsuccessful, NULL will be returned.
2269
 */
2270
PyObject *
2271
PyLong_FromString(const char *str, char **pend, int base)
2272
{
2273
    int sign = 1, error_if_nonzero = 0;
2274
    const char *start, *orig_str = str;
2275
    PyLongObject *z = NULL;
2276
    PyObject *strobj;
2277
    Py_ssize_t slen;
2278
2279
    if ((base != 0 && 
base < 2787k
) || base > 36) {
  Branch (2279:10): [True: 787k, False: 52.0k]
  Branch (2279:23): [True: 0, False: 787k]
  Branch (2279:36): [True: 0, False: 839k]
2280
        PyErr_SetString(PyExc_ValueError,
2281
                        "int() arg 2 must be >= 2 and <= 36");
2282
        return NULL;
2283
    }
2284
    
while (839k
*str != '\0' &&
Py_ISSPACE868k
(*str)) {
  Branch (2284:12): [True: 868k, False: 36]
2285
        str++;
2286
    }
2287
    if (*str == '+') {
  Branch (2287:9): [True: 2.79k, False: 836k]
2288
        ++str;
2289
    }
2290
    else if (*str == '-') {
  Branch (2290:14): [True: 22.8k, False: 814k]
2291
        ++str;
2292
        sign = -1;
2293
    }
2294
    if (base == 0) {
  Branch (2294:9): [True: 52.0k, False: 787k]
2295
        if (str[0] != '0') {
  Branch (2295:13): [True: 50.7k, False: 1.23k]
2296
            base = 10;
2297
        }
2298
        else if (str[1] == 'x' || 
str[1] == 'X'846
) {
  Branch (2298:18): [True: 392, False: 846]
  Branch (2298:35): [True: 8, False: 838]
2299
            base = 16;
2300
        }
2301
        else if (str[1] == 'o' || 
str[1] == 'O'463
) {
  Branch (2301:18): [True: 375, False: 463]
  Branch (2301:35): [True: 2, False: 461]
2302
            base = 8;
2303
        }
2304
        else if (str[1] == 'b' || 
str[1] == 'B'92
) {
  Branch (2304:18): [True: 369, False: 92]
  Branch (2304:35): [True: 8, False: 84]
2305
            base = 2;
2306
        }
2307
        else {
2308
            /* "old" (C-style) octal literal, now invalid.
2309
               it might still be zero though */
2310
            error_if_nonzero = 1;
2311
            base = 10;
2312
        }
2313
    }
2314
    if (str[0] == '0' &&
  Branch (2314:9): [True: 180k, False: 658k]
2315
        
(180k
(180k
base == 16180k
&&
(18.0k
str[1] == 'x'18.0k
||
str[1] == 'X'17.6k
)) ||
  Branch (2315:11): [True: 18.0k, False: 162k]
  Branch (2315:26): [True: 403, False: 17.6k]
  Branch (2315:43): [True: 12, False: 17.6k]
2316
         
(180k
base == 8180k
&&
(87.7k
str[1] == 'o'87.7k
||
str[1] == 'O'87.3k
)) ||
  Branch (2316:11): [True: 87.7k, False: 92.6k]
  Branch (2316:26): [True: 379, False: 87.3k]
  Branch (2316:43): [True: 5, False: 87.3k]
2317
         
(180k
base == 2180k
&&
(10.4k
str[1] == 'b'10.4k
||
str[1] == 'B'10.1k
)))) {
  Branch (2317:11): [True: 10.4k, False: 169k]
  Branch (2317:26): [True: 373, False: 10.1k]
  Branch (2317:43): [True: 11, False: 10.0k]
2318
        str += 2;
2319
        /* One underscore allowed here. */
2320
        if (*str == '_') {
  Branch (2320:13): [True: 8, False: 1.17k]
2321
            ++str;
2322
        }
2323
    }
2324
    if (str[0] == '_') {
  Branch (2324:9): [True: 3, False: 839k]
2325
        /* May not start with underscores. */
2326
        goto onError;
2327
    }
2328
2329
    start = str;
2330
    if ((base & (base - 1)) == 0) {
  Branch (2330:9): [True: 182k, False: 657k]
2331
        int res = long_from_binary_base(&str, base, &z);
2332
        if (res < 0) {
  Branch (2332:13): [True: 6, False: 182k]
2333
            /* Syntax error. */
2334
            goto onError;
2335
        }
2336
    }
2337
    else {
2338
/***
2339
Binary bases can be converted in time linear in the number of digits, because
2340
Python's representation base is binary.  Other bases (including decimal!) use
2341
the simple quadratic-time algorithm below, complicated by some speed tricks.
2342
2343
First some math:  the largest integer that can be expressed in N base-B digits
2344
is B**N-1.  Consequently, if we have an N-digit input in base B, the worst-
2345
case number of Python digits needed to hold it is the smallest integer n s.t.
2346
2347
    BASE**n-1 >= B**N-1  [or, adding 1 to both sides]
2348
    BASE**n >= B**N      [taking logs to base BASE]
2349
    n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2350
2351
The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
2352
this quickly.  A Python int with that much space is reserved near the start,
2353
and the result is computed into it.
2354
2355
The input string is actually treated as being in base base**i (i.e., i digits
2356
are processed at a time), where two more static arrays hold:
2357
2358
    convwidth_base[base] = the largest integer i such that base**i <= BASE
2359
    convmultmax_base[base] = base ** convwidth_base[base]
2360
2361
The first of these is the largest i such that i consecutive input digits
2362
must fit in a single Python digit.  The second is effectively the input
2363
base we're really using.
2364
2365
Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2366
convmultmax_base[base], the result is "simply"
2367
2368
   (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2369
2370
where B = convmultmax_base[base].
2371
2372
Error analysis:  as above, the number of Python digits `n` needed is worst-
2373
case
2374
2375
    n >= N * log(B)/log(BASE)
2376
2377
where `N` is the number of input digits in base `B`.  This is computed via
2378
2379
    size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2380
2381
below.  Two numeric concerns are how much space this can waste, and whether
2382
the computed result can be too small.  To be concrete, assume BASE = 2**15,
2383
which is the default (and it's unlikely anyone changes that).
2384
2385
Waste isn't a problem:  provided the first input digit isn't 0, the difference
2386
between the worst-case input with N digits and the smallest input with N
2387
digits is about a factor of B, but B is small compared to BASE so at most
2388
one allocated Python digit can remain unused on that count.  If
2389
N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2390
and adding 1 returns a result 1 larger than necessary.  However, that can't
2391
happen:  whenever B is a power of 2, long_from_binary_base() is called
2392
instead, and it's impossible for B**i to be an integer power of 2**15 when
2393
B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2394
an exact integer when B is not a power of 2, since B**i has a prime factor
2395
other than 2 in that case, but (2**15)**j's only prime factor is 2).
2396
2397
The computed result can be too small if the true value of N*log(B)/log(BASE)
2398
is a little bit larger than an exact integer, but due to roundoff errors (in
2399
computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2400
yields a numeric result a little less than that integer.  Unfortunately, "how
2401
close can a transcendental function get to an integer over some range?"
2402
questions are generally theoretically intractable.  Computer analysis via
2403
continued fractions is practical:  expand log(B)/log(BASE) via continued
2404
fractions, giving a sequence i/j of "the best" rational approximations.  Then
2405
j*log(B)/log(BASE) is approximately equal to (the integer) i.  This shows that
2406
we can get very close to being in trouble, but very rarely.  For example,
2407
76573 is a denominator in one of the continued-fraction approximations to
2408
log(10)/log(2**15), and indeed:
2409
2410
    >>> log(10)/log(2**15)*76573
2411
    16958.000000654003
2412
2413
is very close to an integer.  If we were working with IEEE single-precision,
2414
rounding errors could kill us.  Finding worst cases in IEEE double-precision
2415
requires better-than-double-precision log() functions, and Tim didn't bother.
2416
Instead the code checks to see whether the allocated space is enough as each
2417
new Python digit is added, and copies the whole thing to a larger int if not.
2418
This should happen extremely rarely, and in fact I don't have a test case
2419
that triggers it(!).  Instead the code was tested by artificially allocating
2420
just 1 digit at the start, so that the copying code was exercised for every
2421
digit beyond the first.
2422
***/
2423
        twodigits c;           /* current input character */
2424
        Py_ssize_t size_z;
2425
        Py_ssize_t digits = 0;
2426
        int i;
2427
        int convwidth;
2428
        twodigits convmultmax, convmult;
2429
        digit *pz, *pzstop;
2430
        const char *scan, *lastdigit;
2431
        char prev = 0;
2432
2433
        static double log_base_BASE[37] = {0.0e0,};
2434
        static int convwidth_base[37] = {0,};
2435
        static twodigits convmultmax_base[37] = {0,};
2436
2437
        if (log_base_BASE[base] == 0.0) {
  Branch (2437:13): [True: 31, False: 657k]
2438
            twodigits convmax = base;
2439
            int i = 1;
2440
2441
            log_base_BASE[base] = (log((double)base) /
2442
                                   log((double)PyLong_BASE));
2443
            for (;;) {
2444
                twodigits next = convmax * base;
2445
                if (next > PyLong_BASE) {
  Branch (2445:21): [True: 31, False: 198]
2446
                    break;
2447
                }
2448
                convmax = next;
2449
                ++i;
2450
            }
2451
            convmultmax_base[base] = convmax;
2452
            assert(i > 0);
2453
            convwidth_base[base] = i;
2454
        }
2455
2456
        /* Find length of the string of numeric characters. */
2457
        scan = str;
2458
        lastdigit = str;
2459
2460
        while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base || 
*scan == '_'657k
) {
  Branch (2460:16): [True: 4.73M, False: 657k]
  Branch (2460:65): [True: 32, False: 657k]
2461
            if (*scan == '_') {
  Branch (2461:17): [True: 32, False: 4.73M]
2462
                if (prev == '_') {
  Branch (2462:21): [True: 2, False: 30]
2463
                    /* Only one underscore allowed. */
2464
                    str = lastdigit + 1;
2465
                    goto onError;
2466
                }
2467
            }
2468
            else {
2469
                ++digits;
2470
                lastdigit = scan;
2471
            }
2472
            prev = *scan;
2473
            ++scan;
2474
        }
2475
        if (prev == '_') {
  Branch (2475:13): [True: 6, False: 657k]
2476
            /* Trailing underscore not allowed. */
2477
            /* Set error pointer to first underscore. */
2478
            str = lastdigit + 1;
2479
            goto onError;
2480
        }
2481
2482
        /* Create an int object that can contain the largest possible
2483
         * integer with this base and length.  Note that there's no
2484
         * need to initialize z->ob_digit -- no slot is read up before
2485
         * being stored into.
2486
         */
2487
        double fsize_z = (double)digits * log_base_BASE[base] + 1.0;
2488
        if (fsize_z > (double)MAX_LONG_DIGITS) {
  Branch (2488:13): [True: 0, False: 657k]
2489
            /* The same exception as in _PyLong_New(). */
2490
            PyErr_SetString(PyExc_OverflowError,
2491
                            "too many digits in integer");
2492
            return NULL;
2493
        }
2494
        size_z = (Py_ssize_t)fsize_z;
2495
        /* Uncomment next line to test exceedingly rare copy code */
2496
        /* size_z = 1; */
2497
        assert(size_z > 0);
2498
        z = _PyLong_New(size_z);
2499
        if (z == NULL) {
  Branch (2499:13): [True: 0, False: 657k]
2500
            return NULL;
2501
        }
2502
        Py_SET_SIZE(z, 0);
2503
2504
        /* `convwidth` consecutive input digits are treated as a single
2505
         * digit in base `convmultmax`.
2506
         */
2507
        convwidth = convwidth_base[base];
2508
        convmultmax = convmultmax_base[base];
2509
2510
        /* Work ;-) */
2511
        while (str < scan) {
  Branch (2511:16): [True: 986k, False: 657k]
2512
            if (*str == '_') {
  Branch (2512:17): [True: 0, False: 986k]
2513
                str++;
2514
                continue;
2515
            }
2516
            /* grab up to convwidth digits from the input string */
2517
            c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2518
            for (i = 1; i < convwidth && 
str != scan4.39M
;
++str3.74M
) {
  Branch (2518:25): [True: 4.39M, False: 333k]
  Branch (2518:42): [True: 3.74M, False: 652k]
2519
                if (*str == '_') {
  Branch (2519:21): [True: 22, False: 3.74M]
2520
                    continue;
2521
                }
2522
                i++;
2523
                c = (twodigits)(c *  base +
2524
                                (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
2525
                assert(c < PyLong_BASE);
2526
            }
2527
2528
            convmult = convmultmax;
2529
            /* Calculate the shift only if we couldn't get
2530
             * convwidth digits.
2531
             */
2532
            if (i != convwidth) {
  Branch (2532:17): [True: 652k, False: 333k]
2533
                convmult = base;
2534
                for ( ; i > 1; 
--i1.07M
) {
  Branch (2534:25): [True: 1.07M, False: 652k]
2535
                    convmult *= base;
2536
                }
2537
            }
2538
2539
            /* Multiply z by convmult, and add c. */
2540
            pz = z->ob_digit;
2541
            pzstop = pz + Py_SIZE(z);
2542
            for (; pz < pzstop; 
++pz11.7M
) {
  Branch (2542:20): [True: 11.7M, False: 986k]
2543
                c += (twodigits)*pz * convmult;
2544
                *pz = (digit)(c & PyLong_MASK);
2545
                c >>= PyLong_SHIFT;
2546
            }
2547
            /* carry off the current end? */
2548
            if (c) {
  Branch (2548:17): [True: 932k, False: 53.3k]
2549
                assert(c < PyLong_BASE);
2550
                if (Py_SIZE(z) < size_z) {
  Branch (2550:21): [True: 932k, False: 0]
2551
                    *pz = (digit)c;
2552
                    Py_SET_SIZE(z, Py_SIZE(z) + 1);
2553
                }
2554
                else {
2555
                    PyLongObject *tmp;
2556
                    /* Extremely rare.  Get more space. */
2557
                    assert(Py_SIZE(z) == size_z);
2558
                    tmp = _PyLong_New(size_z + 1);
2559
                    if (tmp == NULL) {
  Branch (2559:25): [True: 0, False: 0]
2560
                        Py_DECREF(z);
2561
                        return NULL;
2562
                    }
2563
                    memcpy(tmp->ob_digit,
2564
                           z->ob_digit,
2565
                           sizeof(digit) * size_z);
2566
                    Py_DECREF(z);
2567
                    z = tmp;
2568
                    z->ob_digit[size_z] = (digit)c;
2569
                    ++size_z;
2570
                }
2571
            }
2572
        }
2573
    }
2574
    if (z == NULL) {
  Branch (2574:9): [True: 0, False: 839k]
2575
        return NULL;
2576
    }
2577
    if (error_if_nonzero) {
  Branch (2577:9): [True: 80, False: 839k]
2578
        /* reset the base to 0, else the exception message
2579
           doesn't make too much sense */
2580
        base = 0;
2581
        if (Py_SIZE(z) != 0) {
  Branch (2581:13): [True: 4, False: 76]
2582
            goto onError;
2583
        }
2584
        /* there might still be other problems, therefore base
2585
           remains zero here for the same reason */
2586
    }
2587
    if (str == start) {
  Branch (2587:9): [True: 726, False: 839k]
2588
        goto onError;
2589
    }
2590
    if (sign < 0) {
  Branch (2590:9): [True: 22.7k, False: 816k]
2591
        Py_SET_SIZE(z, -(Py_SIZE(z)));
2592
    }
2593
    while (*str && 
Py_ISSPACE180k
(*str)) {
  Branch (2593:12): [True: 180k, False: 838k]
2594
        str++;
2595
    }
2596
    if (*str != '\0') {
  Branch (2596:9): [True: 376, False: 838k]
2597
        goto onError;
2598
    }
2599
    long_normalize(z);
2600
    z = maybe_small_long(z);
2601
    if (z == NULL) {
  Branch (2601:9): [True: 0, False: 838k]
2602
        return NULL;
2603
    }
2604
    if (pend != NULL) {
  Branch (2604:9): [True: 699k, False: 139k]
2605
        *pend = (char *)str;
2606
    }
2607
    return (PyObject *) z;
2608
2609
  onError:
2610
    if (pend != NULL) {
  Branch (2610:9): [True: 1.12k, False: 2]
2611
        *pend = (char *)str;
2612
    }
2613
    Py_XDECREF(z);
2614
    slen = strlen(orig_str) < 200 ? strlen(orig_str) : 
2000
;
  Branch (2614:12): [True: 1.12k, False: 0]
2615
    strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2616
    if (strobj == NULL) {
  Branch (2616:9): [True: 2, False: 1.12k]
2617
        return NULL;
2618
    }
2619
    PyErr_Format(PyExc_ValueError,
2620
                 "invalid literal for int() with base %d: %.200R",
2621
                 base, strobj);
2622
    Py_DECREF(strobj);
2623
    return NULL;
2624
}
2625
2626
/* Since PyLong_FromString doesn't have a length parameter,
2627
 * check here for possible NULs in the string.
2628
 *
2629
 * Reports an invalid literal as a bytes object.
2630
 */
2631
PyObject *
2632
_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2633
{
2634
    PyObject *result, *strobj;
2635
    char *end = NULL;
2636
2637
    result = PyLong_FromString(s, &end, base);
2638
    if (end == NULL || (result != NULL && 
end == s + len238k
))
  Branch (2638:9): [True: 0, False: 238k]
  Branch (2638:25): [True: 238k, False: 33]
  Branch (2638:43): [True: 238k, False: 2]
2639
        return result;
2640
    Py_XDECREF(result);
2641
    strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2642
    if (strobj != NULL) {
  Branch (2642:9): [True: 35, False: 0]
2643
        PyErr_Format(PyExc_ValueError,
2644
                     "invalid literal for int() with base %d: %.200R",
2645
                     base, strobj);
2646
        Py_DECREF(strobj);
2647
    }
2648
    return NULL;
2649
}
2650
2651
PyObject *
2652
PyLong_FromUnicodeObject(PyObject *u, int base)
2653
{
2654
    PyObject *result, *asciidig;
2655
    const char *buffer;
2656
    char *end = NULL;
2657
    Py_ssize_t buflen;
2658
2659
    asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
2660
    if (asciidig == NULL)
  Branch (2660:9): [True: 0, False: 461k]
2661
        return NULL;
2662
    assert(PyUnicode_IS_ASCII(asciidig));
2663
    /* Simply get a pointer to existing ASCII characters. */
2664
    buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
2665
    assert(buffer != NULL);
2666
2667
    result = PyLong_FromString(buffer, &end, base);
2668
    if (end == NULL || (result != NULL && 
end == buffer + buflen460k
)) {
  Branch (2668:9): [True: 0, False: 461k]
  Branch (2668:25): [True: 460k, False: 1.08k]
  Branch (2668:43): [True: 460k, False: 7]
2669
        Py_DECREF(asciidig);
2670
        return result;
2671
    }
2672
    Py_DECREF(asciidig);
2673
    Py_XDECREF(result);
2674
    PyErr_Format(PyExc_ValueError,
2675
                 "invalid literal for int() with base %d: %.200R",
2676
                 base, u);
2677
    return NULL;
2678
}
2679
2680
/* forward */
2681
static PyLongObject *x_divrem
2682
    (PyLongObject *, PyLongObject *, PyLongObject **);
2683
static PyObject *long_long(PyObject *v);
2684
2685
/* Int division with remainder, top-level routine */
2686
2687
static int
2688
long_divrem(PyLongObject *a, PyLongObject *b,
2689
            PyLongObject **pdiv, PyLongObject **prem)
2690
{
2691
    Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
2692
    PyLongObject *z;
2693
2694
    if (size_b == 0) {
  Branch (2694:9): [True: 259, False: 1.61M]
2695
        PyErr_SetString(PyExc_ZeroDivisionError,
2696
                        "integer division or modulo by zero");
2697
        return -1;
2698
    }
2699
    if (size_a < size_b ||
  Branch (2699:9): [True: 794k, False: 824k]
2700
        
(824k
size_a == size_b824k
&&
  Branch (2700:10): [True: 239k, False: 585k]
2701
         
a->ob_digit[size_a-1] < b->ob_digit[size_b-1]239k
)) {
  Branch (2701:10): [True: 4.51k, False: 234k]
2702
        /* |a| < |b|. */
2703
        *prem = (PyLongObject *)long_long((PyObject *)a);
2704
        if (*prem == NULL) {
  Branch (2704:13): [True: 0, False: 799k]
2705
            return -1;
2706
        }
2707
        PyObject *zero = _PyLong_GetZero();
2708
        Py_INCREF(zero);
2709
        *pdiv = (PyLongObject*)zero;
2710
        return 0;
2711
    }
2712
    if (size_b == 1) {
  Branch (2712:9): [True: 411k, False: 408k]
2713
        digit rem = 0;
2714
        z = divrem1(a, b->ob_digit[0], &rem);
2715
        if (z == NULL)
  Branch (2715:13): [True: 0, False: 411k]
2716
            return -1;
2717
        *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2718
        if (*prem == NULL) {
  Branch (2718:13): [True: 0, False: 411k]
2719
            Py_DECREF(z);
2720
            return -1;
2721
        }
2722
    }
2723
    else {
2724
        z = x_divrem(a, b, prem);
2725
        *prem = maybe_small_long(*prem);
2726
        if (z == NULL)
  Branch (2726:13): [True: 0, False: 408k]
2727
            return -1;
2728
    }
2729
    /* Set the signs.
2730
       The quotient z has the sign of a*b;
2731
       the remainder r has the sign of a,
2732
       so a = b*z + r. */
2733
    if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
  Branch (2733:9): [True: 45.0k, False: 775k]
2734
        _PyLong_Negate(&z);
2735
        if (z == NULL) {
  Branch (2735:13): [True: 0, False: 45.0k]
2736
            Py_CLEAR(*prem);
2737
            return -1;
2738
        }
2739
    }
2740
    if (Py_SIZE(a) < 0 && 
Py_SIZE45.0k
(*prem) != 045.0k
) {
  Branch (2740:9): [True: 45.0k, False: 775k]
  Branch (2740:27): [True: 25.4k, False: 19.6k]
2741
        _PyLong_Negate(prem);
2742
        if (*prem == NULL) {
  Branch (2742:13): [True: 0, False: 25.4k]
2743
            Py_DECREF(z);
2744
            Py_CLEAR(*prem);
2745
            return -1;
2746
        }
2747
    }
2748
    *pdiv = maybe_small_long(z);
2749
    return 0;
2750
}
2751
2752
/* Int remainder, top-level routine */
2753
2754
static int
2755
long_rem(PyLongObject *a, PyLongObject *b, PyLongObject **prem)
2756
{
2757
    Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
2758
2759
    if (size_b == 0) {
  Branch (2759:9): [True: 4, False: 20.4M]
2760
        PyErr_SetString(PyExc_ZeroDivisionError,
2761
                        "integer modulo by zero");
2762
        return -1;
2763
    }
2764
    if (size_a < size_b ||
  Branch (2764:9): [True: 49.0k, False: 20.4M]
2765
        
(20.4M
size_a == size_b20.4M
&&
  Branch (2765:10): [True: 111k, False: 20.2M]
2766
         
a->ob_digit[size_a-1] < b->ob_digit[size_b-1]111k
)) {
  Branch (2766:10): [True: 3.24k, False: 108k]
2767
        /* |a| < |b|. */
2768
        *prem = (PyLongObject *)long_long((PyObject *)a);
2769
        return -(*prem == NULL);
2770
    }
2771
    if (size_b == 1) {
  Branch (2771:9): [True: 17.3M, False: 3.01M]
2772
        *prem = rem1(a, b->ob_digit[0]);
2773
        if (*prem == NULL)
  Branch (2773:13): [True: 0, False: 17.3M]
2774
            return -1;
2775
    }
2776
    else {
2777
        /* Slow path using divrem. */
2778
        Py_XDECREF(x_divrem(a, b, prem));
2779
        *prem = maybe_small_long(*prem);
2780
        if (*prem == NULL)
  Branch (2780:13): [True: 0, False: 3.01M]
2781
            return -1;
2782
    }
2783
    /* Set the sign. */
2784
    if (Py_SIZE(a) < 0 && 
Py_SIZE13.1k
(*prem) != 013.1k
) {
  Branch (2784:9): [True: 13.1k, False: 20.3M]
  Branch (2784:27): [True: 3.15k, False: 9.94k]
2785
        _PyLong_Negate(prem);
2786
        if (*prem == NULL) {
  Branch (2786:13): [True: 0, False: 3.15k]
2787
            Py_CLEAR(*prem);
2788
            return -1;
2789
        }
2790
    }
2791
    return 0;
2792
}
2793
2794
/* Unsigned int division with remainder -- the algorithm.  The arguments v1
2795
   and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
2796
2797
static PyLongObject *
2798
x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
2799
{
2800
    PyLongObject *v, *w, *a;
2801
    Py_ssize_t i, k, size_v, size_w;
2802
    int d;
2803
    digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2804
    twodigits vv;
2805
    sdigit zhi;
2806
    stwodigits z;
2807
2808
    /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2809
       edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2810
       handle the special case when the initial estimate q for a quotient
2811
       digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2812
       that won't overflow a digit. */
2813
2814
    /* allocate space; w will also be used to hold the final remainder */
2815
    size_v = Py_ABS(Py_SIZE(v1));
2816
    size_w = Py_ABS(Py_SIZE(w1));
2817
    assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2818
    v = _PyLong_New(size_v+1);
2819
    if (v == NULL) {
  Branch (2819:9): [True: 0, False: 3.51M]
2820
        *prem = NULL;
2821
        return NULL;
2822
    }
2823
    w = _PyLong_New(size_w);
2824
    if (w == NULL) {
  Branch (2824:9): [True: 0, False: 3.51M]
2825
        Py_DECREF(v);
2826
        *prem = NULL;
2827
        return NULL;
2828
    }
2829
2830
    /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2831
       shift v1 left by the same amount.  Results go into w and v. */
2832
    d = PyLong_SHIFT - bit_length_digit(w1->ob_digit[size_w-1]);
2833
    carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2834
    assert(carry == 0);
2835
    carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2836
    if (carry != 0 || 
v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]462k
) {
  Branch (2836:9): [True: 3.05M, False: 462k]
  Branch (2836:23): [True: 169k, False: 293k]
2837
        v->ob_digit[size_v] = carry;
2838
        size_v++;
2839
    }
2840
2841
    /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2842
       at most (and usually exactly) k = size_v - size_w digits. */
2843
    k = size_v - size_w;
2844
    assert(k >= 0);
2845
    a = _PyLong_New(k);
2846
    if (a == NULL) {
  Branch (2846:9): [True: 0, False: 3.51M]
2847
        Py_DECREF(w);
2848
        Py_DECREF(v);
2849
        *prem = NULL;
2850
        return NULL;
2851
    }
2852
    v0 = v->ob_digit;
2853
    w0 = w->ob_digit;
2854
    wm1 = w0[size_w-1];
2855
    wm2 = w0[size_w-2];
2856
    for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
  Branch (2856:43): [True: 6.85M, False: 3.51M]
2857
        /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2858
           single-digit quotient q, remainder in vk[0:size_w]. */
2859
2860
        SIGCHECK({
2861
                Py_DECREF(a);
2862
                Py_DECREF(w);
2863
                Py_DECREF(v);
2864
                *prem = NULL;
2865
                return NULL;
2866
            });
2867
2868
        /* estimate quotient digit q; may overestimate by 1 (rare) */
2869
        vtop = vk[size_w];
2870
        assert(vtop <= wm1);
2871
        vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2872
        /* The code used to compute the remainder via
2873
         *     r = (digit)(vv - (twodigits)wm1 * q);
2874
         * and compilers generally generated code to do the * and -.
2875
         * But modern processors generally compute q and r with a single
2876
         * instruction, and modern optimizing compilers exploit that if we
2877
         * _don't_ try to optimize it.
2878
         */
2879
        q = (digit)(vv / wm1);
2880
        r = (digit)(vv % wm1);
2881
        while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
  Branch (2881:16): [True: 224k, False: 6.78M]
2882
                                     | vk[size_w-2])) {
2883
            --q;
2884
            r += wm1;
2885
            if (r >= PyLong_BASE)
  Branch (2885:17): [True: 68.0k, False: 156k]
2886
                break;
2887
        }
2888
        assert(q <= PyLong_BASE);
2889
2890
        /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2891
        zhi = 0;
2892
        for (i = 0; i < size_w; 
++i25.2M
) {
  Branch (2892:21): [True: 25.2M, False: 6.85M]
2893
            /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2894
               -PyLong_BASE * q <= z < PyLong_BASE */
2895
            z = (sdigit)vk[i] + zhi -
2896
                (stwodigits)q * (stwodigits)w0[i];
2897
            vk[i] = (digit)z & PyLong_MASK;
2898
            zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
2899
                                                    z, PyLong_SHIFT);
2900
        }
2901
2902
        /* add w back if q was too large (this branch taken rarely) */
2903
        assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2904
        if ((sdigit)vtop + zhi < 0) {
  Branch (2904:13): [True: 405, False: 6.85M]
2905
            carry = 0;
2906
            for (i = 0; i < size_w; 
++i3.62k
) {
  Branch (2906:25): [True: 3.62k, False: 405]
2907
                carry += vk[i] + w0[i];
2908
                vk[i] = carry & PyLong_MASK;
2909
                carry >>= PyLong_SHIFT;
2910
            }
2911
            --q;
2912
        }
2913
2914
        /* store quotient digit */
2915
        assert(q < PyLong_BASE);
2916
        *--ak = q;
2917
    }
2918
2919
    /* unshift remainder; we reuse w to store the result */
2920
    carry = v_rshift(w0, v0, size_w, d);
2921
    assert(carry==0);
2922
    Py_DECREF(v);
2923
2924
    *prem = long_normalize(w);
2925
    return long_normalize(a);
2926
}
2927
2928
/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2929
   abs(x) < 1.0 and e >= 0; return x and put e in *e.  Here x is
2930
   rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2931
   If a == 0, return 0.0 and set *e = 0.  If the resulting exponent
2932
   e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2933
   -1.0. */
2934
2935
/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2936
#if DBL_MANT_DIG == 53
2937
#define EXP2_DBL_MANT_DIG 9007199254740992.0
2938
#else
2939
#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2940
#endif
2941
2942
double
2943
_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2944
{
2945
    Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2946
    /* See below for why x_digits is always large enough. */
2947
    digit rem;
2948
    digit x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT] = {0,};
2949
    double dx;
2950
    /* Correction term for round-half-to-even rounding.  For a digit x,
2951
       "x + half_even_correction[x & 7]" gives x rounded to the nearest
2952
       multiple of 4, rounding ties to a multiple of 8. */
2953
    static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
2954
2955
    a_size = Py_ABS(Py_SIZE(a));
2956
    if (a_size == 0) {
  Branch (2956:9): [True: 0, False: 149k]
2957
        /* Special case for 0: significand 0.0, exponent 0. */
2958
        *e = 0;
2959
        return 0.0;
2960
    }
2961
    a_bits = bit_length_digit(a->ob_digit[a_size-1]);
2962
    /* The following is an overflow-free version of the check
2963
       "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2964
    if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
  Branch (2964:9): [True: 0, False: 149k]
2965
        
(0
a_size > (0
PY_SSIZE_T_MAX0
- 1) /
PyLong_SHIFT0
+ 1 ||
  Branch (2965:10): [True: 0, False: 0]
2966
         a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
  Branch (2966:10): [True: 0, False: 0]
2967
        goto overflow;
2968
    a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
2969
2970
    /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2971
       (shifting left if a_bits <= DBL_MANT_DIG + 2).
2972
2973
       Number of digits needed for result: write // for floor division.
2974
       Then if shifting left, we end up using
2975
2976
         1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
2977
2978
       digits.  If shifting right, we use
2979
2980
         a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
2981
2982
       digits.  Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2983
       the inequalities
2984
2985
         m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2986
         m // PyLong_SHIFT - n // PyLong_SHIFT <=
2987
                                          1 + (m - n - 1) // PyLong_SHIFT,
2988
2989
       valid for any integers m and n, we find that x_size satisfies
2990
2991
         x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
2992
2993
       in both cases.
2994
    */
2995
    if (a_bits <= DBL_MANT_DIG + 2) {
  Branch (2995:9): [True: 94.3k, False: 55.4k]
2996
        shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2997
        shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2998
        x_size = shift_digits;
2999
        rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
3000
                       (int)shift_bits);
3001
        x_size += a_size;
3002
        x_digits[x_size++] = rem;
3003
    }
3004
    else {
3005
        shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
3006
        shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
3007
        rem = v_rshift(x_digits, a->ob_digit + shift_digits,
3008
                       a_size - shift_digits, (int)shift_bits);
3009
        x_size = a_size - shift_digits;
3010
        /* For correct rounding below, we need the least significant
3011
           bit of x to be 'sticky' for this shift: if any of the bits
3012
           shifted out was nonzero, we set the least significant bit
3013
           of x. */
3014
        if (rem)
  Branch (3014:13): [True: 36.8k, False: 18.6k]
3015
            x_digits[0] |= 1;
3016
        else
3017
            
while (18.6k
shift_digits > 0)
  Branch (3017:20): [True: 145k, False: 17.9k]
3018
                if (a->ob_digit[--shift_digits]) {
  Branch (3018:21): [True: 646, False: 144k]
3019
                    x_digits[0] |= 1;
3020
                    break;
3021
                }
3022
    }
3023
    assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
3024
3025
    /* Round, and convert to double. */
3026
    x_digits[0] += half_even_correction[x_digits[0] & 7];
3027
    dx = x_digits[--x_size];
3028
    while (x_size > 0)
  Branch (3028:12): [True: 286k, False: 149k]
3029
        dx = dx * PyLong_BASE + x_digits[--x_size];
3030
3031
    /* Rescale;  make correction if result is 1.0. */
3032
    dx /= 4.0 * EXP2_DBL_MANT_DIG;
3033
    if (dx == 1.0) {
  Branch (3033:9): [True: 2.29k, False: 147k]
3034
        if (a_bits == PY_SSIZE_T_MAX)
  Branch (3034:13): [True: 0, False: 2.29k]
3035
            goto overflow;
3036
        dx = 0.5;
3037
        a_bits += 1;
3038
    }
3039
3040
    *e = a_bits;
3041
    return Py_SIZE(a) < 0 ? 
-dx20.8k
:
dx129k
;
  Branch (3041:12): [True: 20.8k, False: 129k]
3042
3043
  overflow:
3044
    /* exponent > PY_SSIZE_T_MAX */
3045
    PyErr_SetString(PyExc_OverflowError,
3046
                    "huge integer: number of bits overflows a Py_ssize_t");
3047
    *e = 0;
3048
    return -1.0;
3049
}
3050
3051
/* Get a C double from an int object.  Rounds to the nearest double,
3052
   using the round-half-to-even rule in the case of a tie. */
3053
3054
double
3055
PyLong_AsDouble(PyObject *v)
3056
{
3057
    Py_ssize_t exponent;
3058
    double x;
3059
3060
    if (v == NULL) {
  Branch (3060:9): [True: 0, False: 6.63M]
3061
        PyErr_BadInternalCall();
3062
        return -1.0;
3063
    }
3064
    if (!PyLong_Check(v)) {
  Branch (3064:9): [True: 1, False: 6.63M]
3065
        PyErr_SetString(PyExc_TypeError, "an integer is required");
3066
        return -1.0;
3067
    }
3068
    if (IS_MEDIUM_VALUE(v)) {
3069
        /* Fast path; single digit long (31 bits) will cast safely
3070
           to double.  This improves performance of FP/long operations
3071
           by 20%.
3072
        */
3073
        return (double)medium_value((PyLongObject *)v);
3074
    }
3075
    x = _PyLong_Frexp((PyLongObject *)v, &exponent);
3076
    if ((x == -1.0 && 
PyErr_Occurred()0
) || exponent > DBL_MAX_EXP) {
  Branch (3076:10): [True: 0, False: 149k]
  Branch (3076:23): [True: 0, False: 0]
  Branch (3076:44): [True: 90, False: 149k]
3077
        PyErr_SetString(PyExc_OverflowError,
3078
                        "int too large to convert to float");
3079
        return -1.0;
3080
    }
3081
    return ldexp(x, (int)exponent);
3082
}
3083
3084
/* Methods */
3085
3086
/* if a < b, return a negative number
3087
   if a == b, return 0
3088
   if a > b, return a positive number */
3089
3090
static Py_ssize_t
3091
long_compare(PyLongObject *a, PyLongObject *b)
3092
{
3093
    Py_ssize_t sign = Py_SIZE(a) - Py_SIZE(b);
3094
    if (sign == 0) {
  Branch (3094:9): [True: 35.0M, False: 10.9M]
3095
        Py_ssize_t i = Py_ABS(Py_SIZE(a));
3096
        sdigit diff = 0;
3097
        while (--i >= 0) {
  Branch (3097:16): [True: 41.1M, False: 11.4M]
3098
            diff = (sdigit) a->ob_digit[i] - (sdigit) b->ob_digit[i];
3099
            if (diff) {
  Branch (3099:17): [True: 23.6M, False: 17.5M]
3100
                break;
3101
            }
3102
        }
3103
        sign = Py_SIZE(a) < 0 ? 
-diff1.67M
:
diff33.4M
;
  Branch (3103:16): [True: 1.67M, False: 33.4M]
3104
    }
3105
    return sign;
3106
}
3107
3108
static PyObject *
3109
long_richcompare(PyObject *self, PyObject *other, int op)
3110
{
3111
    Py_ssize_t result;
3112
    CHECK_BINOP(self, other);
3113
    if (self == other)
  Branch (3113:9): [True: 3.93M, False: 45.7M]
3114
        result = 0;
3115
    else
3116
        result = long_compare((PyLongObject*)self, (PyLongObject*)other);
3117
    Py_RETURN_RICHCOMPARE(result, 0, op);
3118
}
3119
3120
static Py_hash_t
3121
long_hash(PyLongObject *v)
3122
{
3123
    Py_uhash_t x;
3124
    Py_ssize_t i;
3125
    int sign;
3126
3127
    i = Py_SIZE(v);
3128
    switch(i) {
  Branch (3128:12): [True: 2.89M, False: 34.1M]
3129
    case -1: return v->ob_digit[0]==1 ? 
-211.4k
:
-(sdigit)v->ob_digit[0]40.0k
;
  Branch (3129:5): [True: 51.5k, False: 37.0M]
  Branch (3129:21): [True: 11.4k, False: 40.0k]
3130
    case 0: return 0;
  Branch (3130:5): [True: 1.08M, False: 35.9M]
3131
    case 1: return v->ob_digit[0];
  Branch (3131:5): [True: 33.0M, False: 4.03M]
3132
    }
3133
    sign = 1;
3134
    x = 0;
3135
    if (i < 0) {
  Branch (3135:9): [True: 10.8k, False: 2.88M]
3136
        sign = -1;
3137
        i = -(i);
3138
    }
3139
    while (--i >= 0) {
  Branch (3139:12): [True: 6.33M, False: 2.89M]
3140
        /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
3141
           want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
3142
           _PyHASH_MODULUS.
3143
3144
           The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
3145
           amounts to a rotation of the bits of x.  To see this, write
3146
3147
             x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
3148
3149
           where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
3150
           PyLong_SHIFT bits of x (those that are shifted out of the
3151
           original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
3152
           _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
3153
           bits of x, shifted up.  Then since 2**_PyHASH_BITS is
3154
           congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
3155
           congruent to y modulo _PyHASH_MODULUS.  So
3156
3157
             x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
3158
3159
           The right-hand side is just the result of rotating the
3160
           _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
3161
           not all _PyHASH_BITS bits of x are 1s, the same is true
3162
           after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
3163
           the reduction of x*2**PyLong_SHIFT modulo
3164
           _PyHASH_MODULUS. */
3165
        x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
3166
            (x >> (_PyHASH_BITS - PyLong_SHIFT));
3167
        x += v->ob_digit[i];
3168
        if (x >= _PyHASH_MODULUS)
  Branch (3168:13): [True: 834, False: 6.33M]
3169
            x -= _PyHASH_MODULUS;
3170
    }
3171
    x = x * sign;
3172
    if (x == (Py_uhash_t)-1)
  Branch (3172:9): [True: 13, False: 2.89M]
3173
        x = (Py_uhash_t)-2;
3174
    return (Py_hash_t)x;
3175
}
3176
3177
3178
/* Add the absolute values of two integers. */
3179
3180
static PyLongObject *
3181
x_add(PyLongObject *a, PyLongObject *b)
3182
{
3183
    Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
3184
    PyLongObject *z;
3185
    Py_ssize_t i;
3186
    digit carry = 0;
3187
3188
    /* Ensure a is the larger of the two: */
3189
    if (size_a < size_b) {
  Branch (3189:9): [True: 162k, False: 2.38M]
3190
        { PyLongObject *temp = a; a = b; b = temp; }
3191
        { Py_ssize_t size_temp = size_a;
3192
            size_a = size_b;
3193
            size_b = size_temp; }
3194
    }
3195
    z = _PyLong_New(size_a+1);
3196
    if (z == NULL)
  Branch (3196:9): [True: 0, False: 2.54M]
3197
        return NULL;
3198
    
for (i = 0; 2.54M
i < size_b;
++i5.73M
) {
  Branch (3198:17): [True: 5.73M, False: 2.54M]
3199
        carry += a->ob_digit[i] + b->ob_digit[i];
3200
        z->ob_digit[i] = carry & PyLong_MASK;
3201
        carry >>= PyLong_SHIFT;
3202
    }
3203
    for (; i < size_a; 
++i6.96M
) {
  Branch (3203:12): [True: 6.96M, False: 2.54M]
3204
        carry += a->ob_digit[i];
3205
        z->ob_digit[i] = carry & PyLong_MASK;
3206
        carry >>= PyLong_SHIFT;
3207
    }
3208
    z->ob_digit[i] = carry;
3209
    return long_normalize(z);
3210
}
3211
3212
/* Subtract the absolute values of two integers. */
3213
3214
static PyLongObject *
3215
x_sub(PyLongObject *a, PyLongObject *b)
3216
{
3217
    Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
3218
    PyLongObject *z;
3219
    Py_ssize_t i;
3220
    int sign = 1;
3221
    digit borrow = 0;
3222
3223
    /* Ensure a is the larger of the two: */
3224
    if (size_a < size_b) {
  Branch (3224:9): [True: 765k, False: 1.13M]
3225
        sign = -1;
3226
        { PyLongObject *temp = a; a = b; b = temp; }
3227
        { Py_ssize_t size_temp = size_a;
3228
            size_a = size_b;
3229
            size_b = size_temp; }
3230
    }
3231
    else if (size_a == size_b) {
  Branch (3231:14): [True: 218k, False: 916k]
3232
        /* Find highest digit where a and b differ: */
3233
        i = size_a;
3234
        while (--i >= 0 && 
a->ob_digit[i] == b->ob_digit[i]538k
)
  Branch (3234:16): [True: 538k, False: 5.91k]
  Branch (3234:28): [True: 325k, False: 212k]
3235
            ;
3236
        if (i < 0)
  Branch (3236:13): [True: 5.91k, False: 212k]
3237
            return (PyLongObject *)PyLong_FromLong(0);
3238
        if (a->ob_digit[i] < b->ob_digit[i]) {
  Branch (3238:13): [True: 80.9k, False: 131k]
3239
            sign = -1;
3240
            { PyLongObject *temp = a; a = b; b = temp; }
3241
        }
3242
        size_a = size_b = i+1;
3243
    }
3244
    z = _PyLong_New(size_a);
3245
    if (z == NULL)
  Branch (3245:9): [True: 0, False: 1.89M]
3246
        return NULL;
3247
    
for (i = 0; 1.89M
i < size_b;
++i4.28M
) {
  Branch (3247:17): [True: 4.28M, False: 1.89M]
3248
        /* The following assumes unsigned arithmetic
3249
           works module 2**N for some N>PyLong_SHIFT. */
3250
        borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
3251
        z->ob_digit[i] = borrow & PyLong_MASK;
3252
        borrow >>= PyLong_SHIFT;
3253
        borrow &= 1; /* Keep only one sign bit */
3254
    }
3255
    for (; i < size_a; 
++i5.23M
) {
  Branch (3255:12): [True: 5.23M, False: 1.89M]
3256
        borrow = a->ob_digit[i] - borrow;
3257
        z->ob_digit[i] = borrow & PyLong_MASK;
3258
        borrow >>= PyLong_SHIFT;
3259
        borrow &= 1; /* Keep only one sign bit */
3260
    }
3261
    assert(borrow == 0);
3262
    if (sign < 0) {
  Branch (3262:9): [True: 846k, False: 1.04M]
3263
        Py_SET_SIZE(z, -Py_SIZE(z));
3264
    }
3265
    return maybe_small_long(long_normalize(z));
3266
}
3267
3268
PyObject *
3269
_PyLong_Add(PyLongObject *a, PyLongObject *b)
3270
{
3271
    if (IS_MEDIUM_VALUE(a) && 
IS_MEDIUM_VALUE19.2M
(b)) {
3272
        return _PyLong_FromSTwoDigits(medium_value(a) + medium_value(b));
3273
    }
3274
3275
    PyLongObject *z;
3276
    if (Py_SIZE(a) < 0) {
  Branch (3276:9): [True: 1.17M, False: 2.85M]
3277
        if (Py_SIZE(b) < 0) {
  Branch (3277:13): [True: 292k, False: 879k]
3278
            z = x_add(a, b);
3279
            if (z != NULL) {
  Branch (3279:17): [True: 292k, False: 0]
3280
                /* x_add received at least one multiple-digit int,
3281
                   and thus z must be a multiple-digit int.
3282
                   That also means z is not an element of
3283
                   small_ints, so negating it in-place is safe. */
3284
                assert(Py_REFCNT(z) == 1);
3285
                Py_SET_SIZE(z, -(Py_SIZE(z)));
3286
            }
3287
        }
3288
        else
3289
            z = x_sub(b, a);
3290
    }
3291
    else {
3292
        if (Py_SIZE(b) < 0)
  Branch (3292:13): [True: 776k, False: 2.07M]
3293
            z = x_sub(a, b);
3294
        else
3295
            z = x_add(a, b);
3296
    }
3297
    return (PyObject *)z;
3298
}
3299
3300
static PyObject *
3301
long_add(PyLongObject *a, PyLongObject *b)
3302
{
3303
    CHECK_BINOP(a, b);
3304
    return _PyLong_Add(a, b);
3305
}
3306
3307
PyObject *
3308
_PyLong_Subtract(PyLongObject *a, PyLongObject *b)
3309
{
3310
    PyLongObject *z;
3311
3312
    if (IS_MEDIUM_VALUE(a) && 
IS_MEDIUM_VALUE12.8M
(b)) {
3313
        return _PyLong_FromSTwoDigits(medium_value(a) - medium_value(b));
3314
    }
3315
    if (Py_SIZE(a) < 0) {
  Branch (3315:9): [True: 59.1k, False: 349k]
3316
        if (Py_SIZE(b) < 0) {
  Branch (3316:13): [True: 26.1k, False: 33.0k]
3317
            z = x_sub(b, a);
3318
        }
3319
        else {
3320
            z = x_add(a, b);
3321
            if (z != NULL) {
  Branch (3321:17): [True: 33.0k, False: 0]
3322
                assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
3323
                Py_SET_SIZE(z, -(Py_SIZE(z)));
3324
            }
3325
        }
3326
    }
3327
    else {
3328
        if (Py_SIZE(b) < 0)
  Branch (3328:13): [True: 131k, False: 217k]
3329
            z = x_add(a, b);
3330
        else
3331
            z = x_sub(a, b);
3332
    }
3333
    return (PyObject *)z;
3334
}
3335
3336
static PyObject *
3337
long_sub(PyLongObject *a, PyLongObject *b)
3338
{
3339
    CHECK_BINOP(a, b);
3340
    return _PyLong_Subtract(a, b);
3341
}
3342
3343
/* Grade school multiplication, ignoring the signs.
3344
 * Returns the absolute value of the product, or NULL if error.
3345
 */
3346
static PyLongObject *
3347
x_mul(PyLongObject *a, PyLongObject *b)
3348
{
3349
    PyLongObject *z;
3350
    Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3351
    Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
3352
    Py_ssize_t i;
3353
3354
    z = _PyLong_New(size_a + size_b);
3355
    if (z == NULL)
  Branch (3355:9): [True: 0, False: 7.49M]
3356
        return NULL;
3357
3358
    memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3359
    if (a == b) {
  Branch (3359:9): [True: 3.34M, False: 4.15M]
3360
        /* Efficient squaring per HAC, Algorithm 14.16:
3361
         * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3362
         * Gives slightly less than a 2x speedup when a == b,
3363
         * via exploiting that each entry in the multiplication
3364
         * pyramid appears twice (except for the size_a squares).
3365
         */
3366
        digit *paend = a->ob_digit + size_a;
3367
        for (i = 0; i < size_a; 
++i9.72M
) {
  Branch (3367:21): [True: 9.72M, False: 3.34M]
3368
            twodigits carry;
3369
            twodigits f = a->ob_digit[i];
3370
            digit *pz = z->ob_digit + (i << 1);
3371
            digit *pa = a->ob_digit + i + 1;
3372
3373
            SIGCHECK({
3374
                    Py_DECREF(z);
3375
                    return NULL;
3376
                });
3377
3378
            carry = *pz + f * f;
3379
            *pz++ = (digit)(carry & PyLong_MASK);
3380
            carry >>= PyLong_SHIFT;
3381
            assert(carry <= PyLong_MASK);
3382
3383
            /* Now f is added in twice in each column of the
3384
             * pyramid it appears.  Same as adding f<<1 once.
3385
             */
3386
            f <<= 1;
3387
            while (pa < paend) {
  Branch (3387:20): [True: 75.1M, False: 9.72M]
3388
                carry += *pz + *pa++ * f;
3389
                *pz++ = (digit)(carry & PyLong_MASK);
3390
                carry >>= PyLong_SHIFT;
3391
                assert(carry <= (PyLong_MASK << 1));
3392
            }
3393
            if (carry) {
  Branch (3393:17): [True: 4.04M, False: 5.67M]
3394
                /* See comment below. pz points at the highest possible
3395
                 * carry position from the last outer loop iteration, so
3396
                 * *pz is at most 1.
3397
                 */
3398
                assert(*pz <= 1);
3399
                carry += *pz;
3400
                *pz = (digit)(carry & PyLong_MASK);
3401
                carry >>= PyLong_SHIFT;
3402
                if (carry) {
  Branch (3402:21): [True: 26.1k, False: 4.01M]
3403
                    /* If there's still a carry, it must be into a position
3404
                     * that still holds a 0. Where the base
3405
                     ^ B is 1 << PyLong_SHIFT, the last add was of a carry no
3406
                     * more than 2*B - 2 to a stored digit no more than 1.
3407
                     * So the sum was no more than 2*B - 1, so the current
3408
                     * carry no more than floor((2*B - 1)/B) = 1.
3409
                     */
3410
                    assert(carry == 1);
3411
                    assert(pz[1] == 0);
3412
                    pz[1] = (digit)carry;
3413
                }
3414
            }
3415
        }
3416
    }
3417
    else {      /* a is not the same as b -- gradeschool int mult */
3418
        for (i = 0; i < size_a; 
++i9.42M
) {
  Branch (3418:21): [True: 9.42M, False: 4.15M]
3419
            twodigits carry = 0;
3420
            twodigits f = a->ob_digit[i];
3421
            digit *pz = z->ob_digit + i;
3422
            digit *pb = b->ob_digit;
3423
            digit *pbend = b->ob_digit + size_b;
3424
3425
            SIGCHECK({
3426
                    Py_DECREF(z);
3427
                    return NULL;
3428
                });
3429
3430
            
while (9.42M
pb < pbend) {
  Branch (3430:20): [True: 250M, False: 9.42M]
3431
                carry += *pz + *pb++ * f;
3432
                *pz++ = (digit)(carry & PyLong_MASK);
3433
                carry >>= PyLong_SHIFT;
3434
                assert(carry <= PyLong_MASK);
3435
            }
3436
            if (carry)
  Branch (3436:17): [True: 6.26M, False: 3.16M]
3437
                *pz += (digit)(carry & PyLong_MASK);
3438
            assert((carry >> PyLong_SHIFT) == 0);
3439
        }
3440
    }
3441
    return long_normalize(z);
3442
}
3443
3444
/* A helper for Karatsuba multiplication (k_mul).
3445
   Takes an int "n" and an integer "size" representing the place to
3446
   split, and sets low and high such that abs(n) == (high << size) + low,
3447
   viewing the shift as being by digits.  The sign bit is ignored, and
3448
   the return values are >= 0.
3449
   Returns 0 on success, -1 on failure.
3450
*/
3451
static int
3452
kmul_split(PyLongObject *n,
3453
           Py_ssize_t size,
3454
           PyLongObject **high,
3455
           PyLongObject **low)
3456
{
3457
    PyLongObject *hi, *lo;
3458
    Py_ssize_t size_lo, size_hi;
3459
    const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
3460
3461
    size_lo = Py_MIN(size_n, size);
3462
    size_hi = size_n - size_lo;
3463
3464
    if ((hi = _PyLong_New(size_hi)) == NULL)
  Branch (3464:9): [True: 0, False: 12.4k]
3465
        return -1;
3466
    if ((lo = _PyLong_New(size_lo)) == NULL) {
  Branch (3466:9): [True: 0, False: 12.4k]
3467
        Py_DECREF(hi);
3468
        return -1;
3469
    }
3470
3471
    memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3472
    memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
3473
3474
    *high = long_normalize(hi);
3475
    *low = long_normalize(lo);
3476
    return 0;
3477
}
3478
3479
static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3480
3481
/* Karatsuba multiplication.  Ignores the input signs, and returns the
3482
 * absolute value of the product (or NULL if error).
3483
 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3484
 */
3485
static PyLongObject *
3486
k_mul(PyLongObject *a, PyLongObject *b)
3487
{
3488
    Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3489
    Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
3490
    PyLongObject *ah = NULL;
3491
    PyLongObject *al = NULL;
3492
    PyLongObject *bh = NULL;
3493
    PyLongObject *bl = NULL;
3494
    PyLongObject *ret = NULL;
3495
    PyLongObject *t1, *t2, *t3;
3496
    Py_ssize_t shift;           /* the number of digits we split off */
3497
    Py_ssize_t i;
3498
3499
    /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3500
     * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh  + ah*bh + al*bl
3501
     * Then the original product is
3502
     *     ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3503
     * By picking X to be a power of 2, "*X" is just shifting, and it's
3504
     * been reduced to 3 multiplies on numbers half the size.
3505
     */
3506
3507
    /* We want to split based on the larger number; fiddle so that b
3508
     * is largest.
3509
     */
3510
    if (asize > bsize) {
  Branch (3510:9): [True: 2.22M, False: 5.29M]
3511
        t1 = a;
3512
        a = b;
3513
        b = t1;
3514
3515
        i = asize;
3516
        asize = bsize;
3517
        bsize = i;
3518
    }
3519
3520
    /* Use gradeschool math when either number is too small. */
3521
    i = a == b ? 
KARATSUBA_SQUARE_CUTOFF3.34M
:
KARATSUBA_CUTOFF4.16M
;
  Branch (3521:9): [True: 3.34M, False: 4.16M]
3522
    if (asize <= i) {
  Branch (3522:9): [True: 7.50M, False: 7.59k]
3523
        if (asize == 0)
  Branch (3523:13): [True: 16.3k, False: 7.49M]
3524
            return (PyLongObject *)PyLong_FromLong(0);
3525
        else
3526
            return x_mul(a, b);
3527
    }
3528
3529
    /* If a is small compared to b, splitting on b gives a degenerate
3530
     * case with ah==0, and Karatsuba may be (even much) less efficient
3531
     * than "grade school" then.  However, we can still win, by viewing
3532
     * b as a string of "big digits", each of width a->ob_size.  That
3533
     * leads to a sequence of balanced calls to k_mul.
3534
     */
3535
    if (2 * asize <= bsize)
  Branch (3535:9): [True: 72, False: 7.52k]
3536
        return k_lopsided_mul(a, b);
3537
3538
    /* Split a & b into hi & lo pieces. */
3539
    shift = bsize >> 1;
3540
    if (kmul_split(a, shift, &ah, &al) < 0) 
goto fail0
;
  Branch (3540:9): [True: 0, False: 7.52k]
3541
    assert(Py_SIZE(ah) > 0);            /* the split isn't degenerate */
3542
3543
    if (a == b) {
  Branch (3543:9): [True: 2.58k, False: 4.94k]
3544
        bh = ah;
3545
        bl = al;
3546
        Py_INCREF(bh);
3547
        Py_INCREF(bl);
3548
    }
3549
    else if (kmul_split(b, shift, &bh, &bl) < 0) 
goto fail0
;
  Branch (3549:14): [True: 0, False: 4.94k]
3550
3551
    /* The plan:
3552
     * 1. Allocate result space (asize + bsize digits:  that's always
3553
     *    enough).
3554
     * 2. Compute ah*bh, and copy into result at 2*shift.
3555
     * 3. Compute al*bl, and copy into result at 0.  Note that this
3556
     *    can't overlap with #2.
3557
     * 4. Subtract al*bl from the result, starting at shift.  This may
3558
     *    underflow (borrow out of the high digit), but we don't care:
3559
     *    we're effectively doing unsigned arithmetic mod
3560
     *    BASE**(sizea + sizeb), and so long as the *final* result fits,
3561
     *    borrows and carries out of the high digit can be ignored.
3562
     * 5. Subtract ah*bh from the result, starting at shift.
3563
     * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3564
     *    at shift.
3565
     */
3566
3567
    /* 1. Allocate result space. */
3568
    ret = _PyLong_New(asize + bsize);
3569
    if (ret == NULL) 
goto fail0
;
  Branch (3569:9): [True: 0, False: 7.52k]
3570
#ifdef Py_DEBUG
3571
    /* Fill with trash, to catch reference to uninitialized digits. */
3572
    memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
3573
#endif
3574
3575
    /* 2. t1 <- ah*bh, and copy into high digits of result. */
3576
    if ((t1 = k_mul(ah, bh)) == NULL) 
goto fail0
;
  Branch (3576:9): [True: 0, False: 7.52k]
3577
    assert(Py_SIZE(t1) >= 0);
3578
    assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3579
    memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3580
           Py_SIZE(t1) * sizeof(digit));
3581
3582
    /* Zero-out the digits higher than the ah*bh copy. */
3583
    i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3584
    if (i)
  Branch (3584:9): [True: 3.06k, False: 4.46k]
3585
        memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3586
               i * sizeof(digit));
3587
3588
    /* 3. t2 <- al*bl, and copy into the low digits. */
3589
    if ((t2 = k_mul(al, bl)) == NULL) {
  Branch (3589:9): [True: 0, False: 7.52k]
3590
        Py_DECREF(t1);
3591
        goto fail;
3592
    }
3593
    assert(Py_SIZE(t2) >= 0);
3594
    assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3595
    memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
3596
3597
    /* Zero out remaining digits. */
3598
    i = 2*shift - Py_SIZE(t2);          /* number of uninitialized digits */
3599
    if (i)
  Branch (3599:9): [True: 2.29k, False: 5.22k]
3600
        memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
3601
3602
    /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2).  We do al*bl first
3603
     * because it's fresher in cache.
3604
     */
3605
    i = Py_SIZE(ret) - shift;  /* # digits after shift */
3606
    (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3607
    _Py_DECREF_INT(t2);
3608
3609
    (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3610
    _Py_DECREF_INT(t1);
3611
3612
    /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3613
    if ((t1 = x_add(ah, al)) == NULL) 
goto fail0
;
  Branch (3613:9): [True: 0, False: 7.52k]
3614
    _Py_DECREF_INT(ah);
3615
    _Py_DECREF_INT(al);
3616
    ah = al = NULL;
3617
3618
    if (a == b) {
  Branch (3618:9): [True: 2.58k, False: 4.94k]
3619
        t2 = t1;
3620
        Py_INCREF(t2);
3621
    }
3622
    else if ((t2 = x_add(bh, bl)) == NULL) {
  Branch (3622:14): [True: 0, False: 4.94k]
3623
        Py_DECREF(t1);
3624
        goto fail;
3625
    }
3626
    _Py_DECREF_INT(bh);
3627
    _Py_DECREF_INT(bl);
3628
    bh = bl = NULL;
3629
3630
    t3 = k_mul(t1, t2);
3631
    _Py_DECREF_INT(t1);
3632
    _Py_DECREF_INT(t2);
3633
    if (t3 == NULL) 
goto fail0
;
  Branch (3633:9): [True: 0, False: 7.52k]
3634
    assert(Py_SIZE(t3) >= 0);
3635
3636
    /* Add t3.  It's not obvious why we can't run out of room here.
3637
     * See the (*) comment after this function.
3638
     */
3639
    (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3640
    _Py_DECREF_INT(t3);
3641
3642
    return long_normalize(ret);
3643
3644
  fail:
3645
    Py_XDECREF(ret);
3646
    Py_XDECREF(ah);
3647
    Py_XDECREF(al);
3648
    Py_XDECREF(bh);
3649
    Py_XDECREF(bl);
3650
    return NULL;
3651
}
3652
3653
/* (*) Why adding t3 can't "run out of room" above.
3654
3655
Let f(x) mean the floor of x and c(x) mean the ceiling of x.  Some facts
3656
to start with:
3657
3658
1. For any integer i, i = c(i/2) + f(i/2).  In particular,
3659
   bsize = c(bsize/2) + f(bsize/2).
3660
2. shift = f(bsize/2)
3661
3. asize <= bsize
3662
4. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3663
   routine, so asize > bsize/2 >= f(bsize/2) in this routine.
3664
3665
We allocated asize + bsize result digits, and add t3 into them at an offset
3666
of shift.  This leaves asize+bsize-shift allocated digit positions for t3
3667
to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3668
asize + c(bsize/2) available digit positions.
3669
3670
bh has c(bsize/2) digits, and bl at most f(size/2) digits.  So bh+hl has
3671
at most c(bsize/2) digits + 1 bit.
3672
3673
If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3674
digits, and al has at most f(bsize/2) digits in any case.  So ah+al has at
3675
most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
3676
3677
The product (ah+al)*(bh+bl) therefore has at most
3678
3679
    c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
3680
3681
and we have asize + c(bsize/2) available digit positions.  We need to show
3682
this is always enough.  An instance of c(bsize/2) cancels out in both, so
3683
the question reduces to whether asize digits is enough to hold
3684
(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits.  If asize < bsize,
3685
then we're asking whether asize digits >= f(bsize/2) digits + 2 bits.  By #4,
3686
asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
3687
digit is enough to hold 2 bits.  This is so since PyLong_SHIFT=15 >= 2.  If
3688
asize == bsize, then we're asking whether bsize digits is enough to hold
3689
c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3690
is enough to hold 2 bits.  This is so if bsize >= 2, which holds because
3691
bsize >= KARATSUBA_CUTOFF >= 2.
3692
3693
Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3694
clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3695
ah*bh and al*bl too.
3696
*/
3697
3698
/* b has at least twice the digits of a, and a is big enough that Karatsuba
3699
 * would pay off *if* the inputs had balanced sizes.  View b as a sequence
3700
 * of slices, each with a->ob_size digits, and multiply the slices by a,
3701
 * one at a time.  This gives k_mul balanced inputs to work with, and is
3702
 * also cache-friendly (we compute one double-width slice of the result
3703
 * at a time, then move on, never backtracking except for the helpful
3704
 * single-width slice overlap between successive partial sums).
3705
 */
3706
static PyLongObject *
3707
k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3708
{
3709
    const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3710
    Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
3711
    Py_ssize_t nbdone;          /* # of b digits already multiplied */
3712
    PyLongObject *ret;
3713
    PyLongObject *bslice = NULL;
3714
3715
    assert(asize > KARATSUBA_CUTOFF);
3716
    assert(2 * asize <= bsize);
3717
3718
    /* Allocate result space, and zero it out. */
3719
    ret = _PyLong_New(asize + bsize);
3720
    if (ret == NULL)
  Branch (3720:9): [True: 0, False: 72]
3721
        return NULL;
3722
    memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
3723
3724
    /* Successive slices of b are copied into bslice. */
3725
    bslice = _PyLong_New(asize);
3726
    if (bslice == NULL)
  Branch (3726:9): [True: 0, False: 72]
3727
        goto fail;
3728
3729
    nbdone = 0;
3730
    while (bsize > 0) {
  Branch (3730:12): [True: 1.10k, False: 72]
3731
        PyLongObject *product;
3732
        const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
3733
3734
        /* Multiply the next slice of b by a. */
3735
        memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3736
               nbtouse * sizeof(digit));
3737
        Py_SET_SIZE(bslice, nbtouse);
3738
        product = k_mul(a, bslice);
3739
        if (product == NULL)
  Branch (3739:13): [True: 0, False: 1.10k]
3740
            goto fail;
3741
3742
        /* Add into result. */
3743
        (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3744
                     product->ob_digit, Py_SIZE(product));
3745
        _Py_DECREF_INT(product);
3746
3747
        bsize -= nbtouse;
3748
        nbdone += nbtouse;
3749
    }
3750
3751
    _Py_DECREF_INT(bslice);
3752
    return long_normalize(ret);
3753
3754
  fail:
3755
    Py_DECREF(ret);
3756
    Py_XDECREF(bslice);
3757
    return NULL;
3758
}
3759
3760
PyObject *
3761
_PyLong_Multiply(PyLongObject *a, PyLongObject *b)
3762
{
3763
    PyLongObject *z;
3764
3765
    /* fast path for single-digit multiplication */
3766
    if (IS_MEDIUM_VALUE(a) && 
IS_MEDIUM_VALUE28.7M
(b)) {
3767
        stwodigits v = medium_value(a) * medium_value(b);
3768
        return _PyLong_FromSTwoDigits(v);
3769
    }
3770
3771
    z = k_mul(a, b);
3772
    /* Negate if exactly one of the inputs is negative. */
3773
    if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && 
z114k
) {
  Branch (3773:9): [True: 114k, False: 7.37M]
  Branch (3773:44): [True: 114k, False: 0]
3774
        _PyLong_Negate(&z);
3775
        if (z == NULL)
  Branch (3775:13): [True: 0, False: 114k]
3776
            return NULL;
3777
    }
3778
    return (PyObject *)z;
3779
}
3780
3781
static PyObject *
3782
long_mul(PyLongObject *a, PyLongObject *b)
3783
{
3784
    CHECK_BINOP(a, b);
3785
    return _PyLong_Multiply(a, b);
3786
}
3787
3788
/* Fast modulo division for single-digit longs. */
3789
static PyObject *
3790
fast_mod(PyLongObject *a, PyLongObject *b)
3791
{
3792
    sdigit left = a->ob_digit[0];
3793
    sdigit right = b->ob_digit[0];
3794
    sdigit mod;
3795
3796
    assert(Py_ABS(Py_SIZE(a)) == 1);
3797
    assert(Py_ABS(Py_SIZE(b)) == 1);
3798
3799
    if (Py_SIZE(a) == Py_SIZE(b)) {
  Branch (3799:9): [True: 2.55M, False: 64.2k]
3800
        /* 'a' and 'b' have the same sign. */
3801
        mod = left % right;
3802
    }
3803
    else {
3804
        /* Either 'a' or 'b' is negative. */
3805
        mod = right - 1 - (left - 1) % right;
3806
    }
3807
3808
    return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
3809
}
3810
3811
/* Fast floor division for single-digit longs. */
3812
static PyObject *
3813
fast_floor_div(PyLongObject *a, PyLongObject *b)
3814
{
3815
    sdigit left = a->ob_digit[0];
3816
    sdigit right = b->ob_digit[0];
3817
    sdigit div;
3818
3819
    assert(Py_ABS(Py_SIZE(a)) == 1);
3820
    assert(Py_ABS(Py_SIZE(b)) == 1);
3821
3822
    if (Py_SIZE(a) == Py_SIZE(b)) {
  Branch (3822:9): [True: 1.99M, False: 101k]
3823
        /* 'a' and 'b' have the same sign. */
3824
        div = left / right;
3825
    }
3826
    else {
3827
        /* Either 'a' or 'b' is negative. */
3828
        div = -1 - (left - 1) / right;
3829
    }
3830
3831
    return PyLong_FromLong(div);
3832
}
3833
3834
/* The / and % operators are now defined in terms of divmod().
3835
   The expression a mod b has the value a - b*floor(a/b).
3836
   The long_divrem function gives the remainder after division of
3837
   |a| by |b|, with the sign of a.  This is also expressed
3838
   as a - b*trunc(a/b), if trunc truncates towards zero.
3839
   Some examples:
3840
     a           b      a rem b         a mod b
3841
     13          10      3               3
3842
    -13          10     -3               7
3843
     13         -10      3              -7
3844
    -13         -10     -3              -3
3845
   So, to get from rem to mod, we have to add b if a and b
3846
   have different signs.  We then subtract one from the 'div'
3847
   part of the outcome to keep the invariant intact. */
3848
3849
/* Compute
3850
 *     *pdiv, *pmod = divmod(v, w)
3851
 * NULL can be passed for pdiv or pmod, in which case that part of
3852
 * the result is simply thrown away.  The caller owns a reference to
3853
 * each of these it requests (does not pass NULL for).
3854
 */
3855
static int
3856
l_divmod(PyLongObject *v, PyLongObject *w,
3857
         PyLongObject **pdiv, PyLongObject **pmod)
3858
{
3859
    PyLongObject *div, *mod;
3860
3861
    if (Py_ABS(Py_SIZE(v)) == 1 && 
Py_ABS567k
(Py_SIZE(w)) == 1567k
) {
  Branch (3861:9): [True: 567k, False: 1.60M]
  Branch (3861:36): [True: 555k, False: 12.2k]
3862
        /* Fast path for single-digit longs */
3863
        div = NULL;
3864
        if (pdiv != NULL) {
  Branch (3864:13): [True: 555k, False: 0]
3865
            div = (PyLongObject *)fast_floor_div(v, w);
3866
            if (div == NULL) {
  Branch (3866:17): [True: 0, False: 555k]
3867
                return -1;
3868
            }
3869
        }
3870
        if (pmod != NULL) {
  Branch (3870:13): [True: 555k, False: 0]
3871
            mod = (PyLongObject *)fast_mod(v, w);
3872
            if (mod == NULL) {
  Branch (3872:17): [True: 0, False: 555k]
3873
                Py_XDECREF(div);
3874
                return -1;
3875
            }
3876
            *pmod = mod;
3877
        }
3878
        if (pdiv != NULL) {
  Branch (3878:13): [True: 555k, False: 0]
3879
            /* We only want to set `*pdiv` when `*pmod` is
3880
               set successfully. */
3881
            *pdiv = div;
3882
        }
3883
        return 0;
3884
    }
3885
    if (long_divrem(v, w, &div, &mod) < 0)
  Branch (3885:9): [True: 257, False: 1.61M]
3886
        return -1;
3887
    if ((Py_SIZE(mod) < 0 && 
Py_SIZE29.3k
(w) > 029.3k
) ||
  Branch (3887:10): [True: 29.3k, False: 1.58M]
  Branch (3887:30): [True: 26.2k, False: 3.12k]
3888
        
(1.59M
Py_SIZE1.59M
(mod) > 01.59M
&&
Py_SIZE318k
(w) < 0318k
)) {
  Branch (3888:10): [True: 318k, False: 1.27M]
  Branch (3888:30): [True: 3.17k, False: 315k]
3889
        PyLongObject *temp;
3890
        temp = (PyLongObject *) long_add(mod, w);
3891
        Py_DECREF(mod);
3892
        mod = temp;
3893
        if (mod == NULL) {
  Branch (3893:13): [True: 0, False: 29.4k]
3894
            Py_DECREF(div);
3895
            return -1;
3896
        }
3897
        temp = (PyLongObject *) long_sub(div, (PyLongObject *)_PyLong_GetOne());
3898
        if (temp == NULL) {
  Branch (3898:13): [True: 0, False: 29.4k]
3899
            Py_DECREF(mod);
3900
            Py_DECREF(div);
3901
            return -1;
3902
        }
3903
        Py_DECREF(div);
3904
        div = temp;
3905
    }
3906
    if (pdiv != NULL)
  Branch (3906:9): [True: 1.61M, False: 0]
3907
        *pdiv = div;
3908
    else
3909
        Py_DECREF(div);
3910
3911
    if (pmod != NULL)
  Branch (3911:9): [True: 789k, False: 828k]
3912
        *pmod = mod;
3913
    else
3914
        Py_DECREF(mod);
3915
3916
    return 0;
3917
}
3918
3919
/* Compute
3920
 *     *pmod = v % w
3921
 * pmod cannot be NULL. The caller owns a reference to pmod.
3922
 */
3923
static int
3924
l_mod(PyLongObject *v, PyLongObject *w, PyLongObject **pmod)
3925
{
3926
    PyLongObject *mod;
3927
3928
    assert(pmod);
3929
    if (Py_ABS(Py_SIZE(v)) == 1 && 
Py_ABS2.07M
(Py_SIZE(w)) == 12.07M
) {
  Branch (3929:9): [True: 2.07M, False: 20.4M]
  Branch (3929:36): [True: 2.05M, False: 13.9k]
3930
        /* Fast path for single-digit longs */
3931
        *pmod = (PyLongObject *)fast_mod(v, w);
3932
        return -(*pmod == NULL);
3933
    }
3934
    if (long_rem(v, w, &mod) < 0)
  Branch (3934:9): [True: 4, False: 20.4M]
3935
        return -1;
3936
    if ((Py_SIZE(mod) < 0 && 
Py_SIZE4.83k
(w) > 04.83k
) ||
  Branch (3936:10): [True: 4.83k, False: 20.4M]
  Branch (3936:30): [True: 1.93k, False: 2.90k]
3937
        
(20.4M
Py_SIZE20.4M
(mod) > 020.4M
&&
Py_SIZE20.2M
(w) < 020.2M
)) {
  Branch (3937:10): [True: 20.2M, False: 237k]
  Branch (3937:30): [True: 5.60k, False: 20.2M]
3938
        PyLongObject *temp;
3939
        temp = (PyLongObject *) long_add(mod, w);
3940
        Py_DECREF(mod);
3941
        mod = temp;
3942
        if (mod == NULL)
  Branch (3942:13): [True: 0, False: 7.53k]
3943
            return -1;
3944
    }
3945
    *pmod = mod;
3946
3947
    return 0;
3948
}
3949
3950
static PyObject *
3951
long_div(PyObject *a, PyObject *b)
3952
{
3953
    PyLongObject *div;
3954
3955
    CHECK_BINOP(a, b);
3956
3957
    if (Py_ABS(Py_SIZE(a)) == 1 && 
Py_ABS1.55M
(Py_SIZE(b)) == 11.55M
) {
  Branch (3957:9): [True: 1.55M, False: 822k]
  Branch (3957:36): [True: 1.54M, False: 6.75k]
3958
        return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
3959
    }
3960
3961
    if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
  Branch (3961:9): [True: 250, False: 828k]
3962
        div = NULL;
3963
    return (PyObject *)div;
3964
}
3965
3966
/* PyLong/PyLong -> float, with correctly rounded result. */
3967
3968
#define MANT_DIG_DIGITS (DBL_MANT_DIG / 
PyLong_SHIFT4.74M
)
3969
#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3970
3971
static PyObject *
3972
long_true_divide(PyObject *v, PyObject *w)
3973
{
3974
    PyLongObject *a, *b, *x;
3975
    Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3976
    digit mask, low;
3977
    int inexact, negate, a_is_small, b_is_small;
3978
    double dx, result;
3979
3980
    CHECK_BINOP(v, w);
3981
    a = (PyLongObject *)v;
3982
    b = (PyLongObject *)w;
3983
3984
    /*
3985
       Method in a nutshell:
3986
3987
         0. reduce to case a, b > 0; filter out obvious underflow/overflow
3988
         1. choose a suitable integer 'shift'
3989
         2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3990
         3. adjust x for correct rounding
3991
         4. convert x to a double dx with the same value
3992
         5. return ldexp(dx, shift).
3993
3994
       In more detail:
3995
3996
       0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3997
       returns either 0.0 or -0.0, depending on the sign of b.  For a and
3998
       b both nonzero, ignore signs of a and b, and add the sign back in
3999
       at the end.  Now write a_bits and b_bits for the bit lengths of a
4000
       and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
4001
       for b).  Then
4002
4003
          2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
4004
4005
       So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
4006
       so overflows.  Similarly, if a_bits - b_bits < DBL_MIN_EXP -
4007
       DBL_MANT_DIG - 1 then a/b underflows to 0.  With these cases out of
4008
       the way, we can assume that
4009
4010
          DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
4011
4012
       1. The integer 'shift' is chosen so that x has the right number of
4013
       bits for a double, plus two or three extra bits that will be used
4014
       in the rounding decisions.  Writing a_bits and b_bits for the
4015
       number of significant bits in a and b respectively, a
4016
       straightforward formula for shift is:
4017
4018
          shift = a_bits - b_bits - DBL_MANT_DIG - 2
4019
4020
       This is fine in the usual case, but if a/b is smaller than the
4021
       smallest normal float then it can lead to double rounding on an
4022
       IEEE 754 platform, giving incorrectly rounded results.  So we
4023
       adjust the formula slightly.  The actual formula used is:
4024
4025
           shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
4026
4027
       2. The quantity x is computed by first shifting a (left -shift bits
4028
       if shift <= 0, right shift bits if shift > 0) and then dividing by
4029
       b.  For both the shift and the division, we keep track of whether
4030
       the result is inexact, in a flag 'inexact'; this information is
4031
       needed at the rounding stage.
4032
4033
       With the choice of shift above, together with our assumption that
4034
       a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
4035
       that x >= 1.
4036
4037
       3. Now x * 2**shift <= a/b < (x+1) * 2**shift.  We want to replace
4038
       this with an exactly representable float of the form
4039
4040
          round(x/2**extra_bits) * 2**(extra_bits+shift).
4041
4042
       For float representability, we need x/2**extra_bits <
4043
       2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
4044
       DBL_MANT_DIG.  This translates to the condition:
4045
4046
          extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
4047
4048
       To round, we just modify the bottom digit of x in-place; this can
4049
       end up giving a digit with value > PyLONG_MASK, but that's not a
4050
       problem since digits can hold values up to 2*PyLONG_MASK+1.
4051
4052
       With the original choices for shift above, extra_bits will always
4053
       be 2 or 3.  Then rounding under the round-half-to-even rule, we
4054
       round up iff the most significant of the extra bits is 1, and
4055
       either: (a) the computation of x in step 2 had an inexact result,
4056
       or (b) at least one other of the extra bits is 1, or (c) the least
4057
       significant bit of x (above those to be rounded) is 1.
4058
4059
       4. Conversion to a double is straightforward; all floating-point
4060
       operations involved in the conversion are exact, so there's no
4061
       danger of rounding errors.
4062
4063
       5. Use ldexp(x, shift) to compute x*2**shift, the final result.
4064
       The result will always be exactly representable as a double, except
4065
       in the case that it overflows.  To avoid dependence on the exact
4066
       behaviour of ldexp on overflow, we check for overflow before
4067
       applying ldexp.  The result of ldexp is adjusted for sign before
4068
       returning.
4069
    */
4070
4071
    /* Reduce to case where a and b are both positive. */
4072
    a_size = Py_ABS(Py_SIZE(a));
4073
    b_size = Py_ABS(Py_SIZE(b));
4074
    negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
4075
    if (b_size == 0) {
  Branch (4075:9): [True: 2.49k, False: 2.23M]
4076
        PyErr_SetString(PyExc_ZeroDivisionError,
4077
                        "division by zero");
4078
        goto error;
4079
    }
4080
    if (a_size == 0)
  Branch (4080:9): [True: 2.21k, False: 2.23M]
4081
        goto underflow_or_zero;
4082
4083
    /* Fast path for a and b small (exactly representable in a double).
4084
       Relies on floating-point division being correctly rounded; results
4085
       may be subject to double rounding on x86 machines that operate with
4086
       the x87 FPU set to 64-bit precision. */
4087
    a_is_small = a_size <= MANT_DIG_DIGITS ||
  Branch (4087:18): [True: 2.12M, False: 109k]
4088
        
(109k
a_size == 109k
MANT_DIG_DIGITS109k
+1 &&
  Branch (4088:10): [True: 58.4k, False: 50.8k]
4089
         
a->ob_digit[58.4k
MANT_DIG_DIGITS58.4k
] >>
MANT_DIG_BITS58.4k
== 0);
  Branch (4089:10): [True: 1.38k, False: 57.0k]
4090
    b_is_small = b_size <= MANT_DIG_DIGITS ||
  Branch (4090:18): [True: 2.14M, False: 93.5k]
4091
        
(93.5k
b_size == 93.5k
MANT_DIG_DIGITS93.5k
+1 &&
  Branch (4091:10): [True: 20.0k, False: 73.5k]
4092
         
b->ob_digit[20.0k
MANT_DIG_DIGITS20.0k
] >>
MANT_DIG_BITS20.0k
== 0);
  Branch (4092:10): [True: 14.7k, False: 5.24k]
4093
    if (a_is_small && 
b_is_small2.12M
) {
  Branch (4093:9): [True: 2.12M, False: 107k]
  Branch (4093:23): [True: 2.12M, False: 2.08k]
4094
        double da, db;
4095
        da = a->ob_digit[--a_size];
4096
        while (a_size > 0)
  Branch (4096:16): [True: 571, False: 2.12M]
4097
            da = da * PyLong_BASE + a->ob_digit[--a_size];
4098
        db = b->ob_digit[--b_size];
4099
        while (b_size > 0)
  Branch (4099:16): [True: 130, False: 2.12M]
4100
            db = db * PyLong_BASE + b->ob_digit[--b_size];
4101
        result = da / db;
4102
        goto success;
4103
    }
4104
4105
    /* Catch obvious cases of underflow and overflow */
4106
    diff = a_size - b_size;
4107
    if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
  Branch (4107:9): [True: 0, False: 110k]
4108
        /* Extreme overflow */
4109
        goto overflow;
4110
    else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
  Branch (4110:14): [True: 0, False: 110k]
4111
        /* Extreme underflow */
4112
        goto underflow_or_zero;
4113
    /* Next line is now safe from overflowing a Py_ssize_t */
4114
    diff = diff * PyLong_SHIFT + bit_length_digit(a->ob_digit[a_size - 1]) -
4115
        bit_length_digit(b->ob_digit[b_size - 1]);
4116
    /* Now diff = a_bits - b_bits. */
4117
    if (diff > DBL_MAX_EXP)
  Branch (4117:9): [True: 35, False: 109k]
4118
        goto overflow;
4119
    else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
  Branch (4119:14): [True: 41, False: 109k]
4120
        goto underflow_or_zero;
4121
4122
    /* Choose value for shift; see comments for step 1 above. */
4123
    shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
4124
4125
    inexact = 0;
4126
4127
    /* x = abs(a * 2**-shift) */
4128
    if (shift <= 0) {
  Branch (4128:9): [True: 88.0k, False: 21.8k]
4129
        Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
4130
        digit rem;
4131
        /* x = a << -shift */
4132
        if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
  Branch (4132:13): [True: 0, False: 88.0k]
4133
            /* In practice, it's probably impossible to end up
4134
               here.  Both a and b would have to be enormous,
4135
               using close to SIZE_T_MAX bytes of memory each. */
4136
            PyErr_SetString(PyExc_OverflowError,
4137
                            "intermediate overflow during division");
4138
            goto error;
4139
        }
4140
        x = _PyLong_New(a_size + shift_digits + 1);
4141
        if (x == NULL)
  Branch (4141:13): [True: 0, False: 88.0k]
4142
            goto error;
4143
        
for (i = 0; 88.0k
i < shift_digits;
i++345k
)
  Branch (4143:21): [True: 345k, False: 88.0k]
4144
            x->ob_digit[i] = 0;
4145
        rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
4146
                       a_size, -shift % PyLong_SHIFT);
4147
        x->ob_digit[a_size + shift_digits] = rem;
4148
    }
4149
    else {
4150
        Py_ssize_t shift_digits = shift / PyLong_SHIFT;
4151
        digit rem;
4152
        /* x = a >> shift */
4153
        assert(a_size >= shift_digits);
4154
        x = _PyLong_New(a_size - shift_digits);
4155
        if (x == NULL)
  Branch (4155:13): [True: 0, False: 21.8k]
4156
            goto error;
4157
        rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
4158
                       a_size - shift_digits, shift % PyLong_SHIFT);
4159
        /* set inexact if any of the bits shifted out is nonzero */
4160
        if (rem)
  Branch (4160:13): [True: 17.0k, False: 4.85k]
4161
            inexact = 1;
4162
        while (!inexact && 
shift_digits > 014.4k
)
  Branch (4162:16): [True: 14.4k, False: 18.4k]
  Branch (4162:28): [True: 11.0k, False: 3.42k]
4163
            if (a->ob_digit[--shift_digits])
  Branch (4163:17): [True: 1.42k, False: 9.60k]
4164
                inexact = 1;
4165
    }
4166
    long_normalize(x);
4167
    x_size = Py_SIZE(x);
4168
4169
    /* x //= b. If the remainder is nonzero, set inexact.  We own the only
4170
       reference to x, so it's safe to modify it in-place. */
4171
    if (b_size == 1) {
  Branch (4171:9): [True: 16.5k, False: 93.4k]
4172
        digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
4173
                              b->ob_digit[0]);
4174
        long_normalize(x);
4175
        if (rem)
  Branch (4175:13): [True: 1.51k, False: 15.0k]
4176
            inexact = 1;
4177
    }
4178
    else {
4179
        PyLongObject *div, *rem;
4180
        div = x_divrem(x, b, &rem);
4181
        Py_DECREF(x);
4182
        x = div;
4183
        if (x == NULL)
  Branch (4183:13): [True: 0, False: 93.4k]
4184
            goto error;
4185
        if (Py_SIZE(rem))
4186
            inexact = 1;
4187
        Py_DECREF(rem);
4188
    }
4189
    x_size = Py_ABS(Py_SIZE(x));
4190
    assert(x_size > 0); /* result of division is never zero */
4191
    x_bits = (x_size-1)*PyLong_SHIFT+bit_length_digit(x->ob_digit[x_size-1]);
4192
4193
    /* The number of extra bits that have to be rounded away. */
4194
    extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
4195
    assert(extra_bits == 2 || extra_bits == 3);
4196
4197
    /* Round by directly modifying the low digit of x. */
4198
    mask = (digit)1 << (extra_bits - 1);
4199
    low = x->ob_digit[0] | inexact;
4200
    if ((low & mask) && 
(low & (3U*mask-1U))55.0k
)
  Branch (4200:9): [True: 55.0k, False: 54.8k]
  Branch (4200:25): [True: 55.0k, False: 24]
4201
        low += mask;
4202
    x->ob_digit[0] = low & ~(2U*mask-1U);
4203
4204
    /* Convert x to a double dx; the conversion is exact. */
4205
    dx = x->ob_digit[--x_size];
4206
    while (x_size > 0)
  Branch (4206:12): [True: 109k, False: 109k]
4207
        dx = dx * PyLong_BASE + x->ob_digit[--x_size];
4208
    Py_DECREF(x);
4209
4210
    /* Check whether ldexp result will overflow a double. */
4211
    if (shift + x_bits >= DBL_MAX_EXP &&
  Branch (4211:9): [True: 487, False: 109k]
4212
        
(487
shift + x_bits > DBL_MAX_EXP487
||
dx == ldexp(1.0, (int)x_bits)486
))
  Branch (4212:10): [True: 1, False: 486]
  Branch (4212:42): [True: 252, False: 234]
4213
        goto overflow;
4214
    result = ldexp(dx, (int)shift);
4215
4216
  success:
4217
    return PyFloat_FromDouble(negate ? 
-result24.7k
:
result2.20M
);
  Branch (4217:31): [True: 24.7k, False: 2.20M]
4218
4219
  underflow_or_zero:
4220
    return PyFloat_FromDouble(negate ? 
-0.033
:
0.02.21k
);
  Branch (4220:31): [True: 33, False: 2.21k]
4221
4222
  overflow:
4223
    PyErr_SetString(PyExc_OverflowError,
4224
                    "integer division result too large for a float");
4225
  error:
4226
    return NULL;
4227
}
4228
4229
static PyObject *
4230
long_mod(PyObject *a, PyObject *b)
4231
{
4232
    PyLongObject *mod;
4233
4234
    CHECK_BINOP(a, b);
4235
4236
    if (l_mod((PyLongObject*)a, (PyLongObject*)b, &mod) < 0)
  Branch (4236:9): [True: 4, False: 1.33M]
4237
        mod = NULL;
4238
    return (PyObject *)mod;
4239
}
4240
4241
static PyObject *
4242
long_divmod(PyObject *a, PyObject *b)
4243
{
4244
    PyLongObject *div, *mod;
4245
    PyObject *z;
4246
4247
    CHECK_BINOP(a, b);
4248
4249
    if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
  Branch (4249:9): [True: 7, False: 1.20M]
4250
        return NULL;
4251
    }
4252
    z = PyTuple_New(2);
4253
    if (z != NULL) {
  Branch (4253:9): [True: 1.20M, False: 0]
4254
        PyTuple_SET_ITEM(z, 0, (PyObject *) div);
4255
        PyTuple_SET_ITEM(z, 1, (PyObject *) mod);
4256
    }
4257
    else {
4258
        Py_DECREF(div);
4259
        Py_DECREF(mod);
4260
    }
4261
    return z;
4262
}
4263
4264
4265
/* Compute an inverse to a modulo n, or raise ValueError if a is not
4266
   invertible modulo n. Assumes n is positive. The inverse returned
4267
   is whatever falls out of the extended Euclidean algorithm: it may
4268
   be either positive or negative, but will be smaller than n in
4269
   absolute value.
4270
4271
   Pure Python equivalent for long_invmod:
4272
4273
        def invmod(a, n):
4274
            b, c = 1, 0
4275
            while n:
4276
                q, r = divmod(a, n)
4277
                a, b, c, n = n, c, b - q*c, r
4278
4279
            # at this point a is the gcd of the original inputs
4280
            if a == 1:
4281
                return b
4282
            raise ValueError("Not invertible")
4283
*/
4284
4285
static PyLongObject *
4286
long_invmod(PyLongObject *a, PyLongObject *n)
4287
{
4288
    PyLongObject *b, *c;
4289
4290
    /* Should only ever be called for positive n */
4291
    assert(Py_SIZE(n) > 0);
4292
4293
    b = (PyLongObject *)PyLong_FromLong(1L);
4294
    if (b == NULL) {
  Branch (4294:9): [True: 0, False: 39.4k]
4295
        return NULL;
4296
    }
4297
    c = (PyLongObject *)PyLong_FromLong(0L);
4298
    if (c == NULL) {
  Branch (4298:9): [True: 0, False: 39.4k]
4299
        Py_DECREF(b);
4300
        return NULL;
4301
    }
4302
    Py_INCREF(a);
4303
    Py_INCREF(n);
4304
4305
    /* references now owned: a, b, c, n */
4306
    while (Py_SIZE(n) != 0) {
  Branch (4306:12): [True: 136k, False: 39.4k]
4307
        PyLongObject *q, *r, *s, *t;
4308
4309
        if (l_divmod(a, n, &q, &r) == -1) {
  Branch (4309:13): [True: 0, False: 136k]
4310
            goto Error;
4311
        }
4312
        Py_DECREF(a);
4313
        a = n;
4314
        n = r;
4315
        t = (PyLongObject *)long_mul(q, c);
4316
        Py_DECREF(q);
4317
        if (t == NULL) {
  Branch (4317:13): [True: 0, False: 136k]
4318
            goto Error;
4319
        }
4320
        s = (PyLongObject *)long_sub(b, t);
4321
        Py_DECREF(t);
4322
        if (s == NULL) {
  Branch (4322:13): [True: 0, False: 136k]
4323
            goto Error;
4324
        }
4325
        Py_DECREF(b);
4326
        b = c;
4327
        c = s;
4328
    }
4329
    /* references now owned: a, b, c, n */
4330
4331
    Py_DECREF(c);
4332
    Py_DECREF(n);
4333
    if (long_compare(a, (PyLongObject *)_PyLong_GetOne())) {
  Branch (4333:9): [True: 11.3k, False: 28.1k]
4334
        /* a != 1; we don't have an inverse. */
4335
        Py_DECREF(a);
4336
        Py_DECREF(b);
4337
        PyErr_SetString(PyExc_ValueError,
4338
                        "base is not invertible for the given modulus");
4339
        return NULL;
4340
    }
4341
    else {
4342
        /* a == 1; b gives an inverse modulo n */
4343
        Py_DECREF(a);
4344
        return b;
4345
    }
4346
4347
  Error:
4348
    Py_DECREF(a);
4349
    Py_DECREF(b);
4350
    Py_DECREF(c);
4351
    Py_DECREF(n);
4352
    return NULL;
4353
}
4354
4355
4356
/* pow(v, w, x) */
4357
static PyObject *
4358
long_pow(PyObject *v, PyObject *w, PyObject *x)
4359
{
4360
    PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
4361
    int negativeOutput = 0;  /* if x<0 return negative output */
4362
4363
    PyLongObject *z = NULL;  /* accumulated result */
4364
    Py_ssize_t i, j;             /* counters */
4365
    PyLongObject *temp = NULL;
4366
    PyLongObject *a2 = NULL; /* may temporarily hold a**2 % c */
4367
4368
    /* k-ary values.  If the exponent is large enough, table is
4369
     * precomputed so that table[i] == a**(2*i+1) % c for i in
4370
     * range(EXP_TABLE_LEN).
4371
     * Note: this is uninitialzed stack trash: don't pay to set it to known
4372
     * values unless it's needed. Instead ensure that num_table_entries is
4373
     * set to the number of entries actually filled whenever a branch to the
4374
     * Error or Done labels is possible.
4375
     */
4376
    PyLongObject *table[EXP_TABLE_LEN];
4377
    Py_ssize_t num_table_entries = 0;
4378
4379
    /* a, b, c = v, w, x */
4380
    CHECK_BINOP(v, w);
4381
    a = (PyLongObject*)v; Py_INCREF(a);
4382
    b = (PyLongObject*)w; Py_INCREF(b);
4383
    if (PyLong_Check(x)) {
4384
        c = (PyLongObject *)x;
4385
        Py_INCREF(x);
4386
    }
4387
    else if (x == Py_None)
  Branch (4387:14): [True: 1.26M, False: 1]
4388
        c = NULL;
4389
    else {
4390
        Py_DECREF(a);
4391
        Py_DECREF(b);
4392
        Py_RETURN_NOTIMPLEMENTED;
4393
    }
4394
4395
    if (Py_SIZE(b) < 0 && 
c == NULL48.7k
) {
  Branch (4395:9): [True: 48.7k, False: 2.13M]
  Branch (4395:27): [True: 8.16k, False: 40.5k]
4396
        /* if exponent is negative and there's no modulus:
4397
               return a float.  This works because we know
4398
               that this calls float_pow() which converts its
4399
               arguments to double. */
4400
        Py_DECREF(a);
4401
        Py_DECREF(b);
4402
        return PyFloat_Type.tp_as_number->nb_power(v, w, x);
4403
    }
4404
4405
    if (c) {
  Branch (4405:9): [True: 921k, False: 1.25M]
4406
        /* if modulus == 0:
4407
               raise ValueError() */
4408
        if (Py_SIZE(c) == 0) {
  Branch (4408:13): [True: 301, False: 921k]
4409
            PyErr_SetString(PyExc_ValueError,
4410
                            "pow() 3rd argument cannot be 0");
4411
            goto Error;
4412
        }
4413
4414
        /* if modulus < 0:
4415
               negativeOutput = True
4416
               modulus = -modulus */
4417
        if (Py_SIZE(c) < 0) {
  Branch (4417:13): [True: 31.5k, False: 889k]
4418
            negativeOutput = 1;
4419
            temp = (PyLongObject *)_PyLong_Copy(c);
4420
            if (temp == NULL)
  Branch (4420:17): [True: 0, False: 31.5k]
4421
                goto Error;
4422
            Py_DECREF(c);
4423
            c = temp;
4424
            temp = NULL;
4425
            _PyLong_Negate(&c);
4426
            if (c == NULL)
  Branch (4426:17): [True: 0, False: 31.5k]
4427
                goto Error;
4428
        }
4429
4430
        /* if modulus == 1:
4431
               return 0 */
4432
        if ((Py_SIZE(c) == 1) && 
(c->ob_digit[0] == 1)915k
) {
  Branch (4432:13): [True: 915k, False: 5.89k]
  Branch (4432:34): [True: 2.41k, False: 913k]
4433
            z = (PyLongObject *)PyLong_FromLong(0L);
4434
            goto Done;
4435
        }
4436
4437
        /* if exponent is negative, negate the exponent and
4438
           replace the base with a modular inverse */
4439
        if (Py_SIZE(b) < 0) {
  Branch (4439:13): [True: 39.4k, False: 879k]
4440
            temp = (PyLongObject *)_PyLong_Copy(b);
4441
            if (temp == NULL)
  Branch (4441:17): [True: 0, False: 39.4k]
4442
                goto Error;
4443
            Py_DECREF(b);
4444
            b = temp;
4445
            temp = NULL;
4446
            _PyLong_Negate(&b);
4447
            if (b == NULL)
  Branch (4447:17): [True: 0, False: 39.4k]
4448
                goto Error;
4449
4450
            temp = long_invmod(a, c);
4451
            if (temp == NULL)
  Branch (4451:17): [True: 11.3k, False: 28.1k]
4452
                goto Error;
4453
            Py_DECREF(a);
4454
            a = temp;
4455
            temp = NULL;
4456
        }
4457
4458
        /* Reduce base by modulus in some cases:
4459
           1. If base < 0.  Forcing the base non-negative makes things easier.
4460
           2. If base is obviously larger than the modulus.  The "small
4461
              exponent" case later can multiply directly by base repeatedly,
4462
              while the "large exponent" case multiplies directly by base 31
4463
              times.  It can be unboundedly faster to multiply by
4464
              base % modulus instead.
4465
           We could _always_ do this reduction, but l_mod() isn't cheap,
4466
           so we only do it when it buys something. */
4467
        if (Py_SIZE(a) < 0 || 
Py_SIZE883k
(a) > 883k
Py_SIZE883k
(c)) {
  Branch (4467:13): [True: 24.5k, False: 883k]
  Branch (4467:31): [True: 0, False: 883k]
4468
            if (l_mod(a, c, &temp) < 0)
  Branch (4468:17): [True: 0, False: 24.5k]
4469
                goto Error;
4470
            Py_DECREF(a);
4471
            a = temp;
4472
            temp = NULL;
4473
        }
4474
    }
4475
4476
    /* At this point a, b, and c are guaranteed non-negative UNLESS
4477
       c is NULL, in which case a may be negative. */
4478
4479
    z = (PyLongObject *)PyLong_FromLong(1L);
4480
    if (z == NULL)
  Branch (4480:9): [True: 0, False: 2.16M]
4481
        goto Error;
4482
4483
    /* Perform a modular reduction, X = X % c, but leave X alone if c
4484
     * is NULL.
4485
     */
4486
#define REDUCE(X)                                       \
4487
    do {                                                \
4488
        if (c != NULL) {                                \
4489
            if (l_mod(X, c, &temp) < 0)                 \
4490
                
goto Error0
; \
4491
            Py_XDECREF(X);                              \
4492
            X = temp;                                   \
4493
            temp = NULL;                                \
4494
        }                                               \
4495
    } while(0)
4496
4497
    /* Multiply two values, then reduce the result:
4498
       result = X*Y % c.  If c is NULL, skip the mod. */
4499
#define MULT(X, Y, result)                      \
4500
    do {                                        \
4501
        temp = (PyLongObject *)long_mul(X, Y);  \
4502
        if (temp == NULL)                       \
4503
            
goto Error0
; \
4504
        Py_XDECREF(result);                     \
4505
        result = temp;                          \
4506
        temp = NULL;                            \
4507
        REDUCE(result);                         \
4508
    } while(0)
4509
4510
    i = Py_SIZE(b);
4511
    digit bi = i ? 
b->ob_digit[i-1]2.11M
:
051.8k
;
  Branch (4511:16): [True: 2.11M, False: 51.8k]
4512
    digit bit;
4513
    if (i <= 1 && 
bi <= 32.16M
) {
  Branch (4513:9): [True: 2.16M, False: 161]
  Branch (4513:19): [True: 644k, False: 1.51M]
4514
        /* aim for minimal overhead */
4515
        if (bi >= 2) {
  Branch (4515:13): [True: 549k, False: 94.4k]
4516
            MULT(a, a, z);
4517
            if (bi == 3) {
  Branch (4517:17): [True: 92.1k, False: 457k]
4518
                MULT(z, a, z);
4519
            }
4520
        }
4521
        else if (bi == 1) {
  Branch (4521:18): [True: 42.6k, False: 51.8k]
4522
            /* Multiplying by 1 serves two purposes: if `a` is of an int
4523
             * subclass, makes the result an int (e.g., pow(False, 1) returns
4524
             * 0 instead of False), and potentially reduces `a` by the modulus.
4525
             */
4526
            MULT(a, z, z);
4527
        }
4528
        /* else bi is 0, and z==1 is correct */
4529
    }
4530
    else if (i <= HUGE_EXP_CUTOFF / PyLong_SHIFT ) {
  Branch (4530:14): [True: 1.51M, False: 160]
4531
        /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4532
        /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf    */
4533
4534
        /* Find the first significant exponent bit. Search right to left
4535
         * because we're primarily trying to cut overhead for small powers.
4536
         */
4537
        assert(bi);  /* else there is no significant bit */
4538
        Py_INCREF(a);
4539
        Py_DECREF(z);
4540
        z = a;
4541
        for (bit = 2; ; 
bit <<= 116.5M
) {
4542
            if (bit > bi) { /* found the first bit */
  Branch (4542:17): [True: 1.51M, False: 16.5M]
4543
                assert((bi & bit) == 0);
4544
                bit >>= 1;
4545
                assert(bi & bit);
4546
                break;
4547
            }
4548
        }
4549
        for (--i, bit >>= 1;;) {
4550
            for (; bit != 0; 
bit >>= 116.5M
) {
  Branch (4550:20): [True: 16.5M, False: 1.51M]
4551
                MULT(z, z, z);
4552
                if (bi & bit) {
  Branch (4552:21): [True: 5.78M, False: 10.7M]
4553
                    MULT(z, a, z);
4554
                }
4555
            }
4556
            if (--i < 0) {
  Branch (4556:17): [True: 1.51M, False: 1]
4557
                break;
4558
            }
4559
            bi = b->ob_digit[i];
4560
            bit = (digit)1 << (PyLong_SHIFT-1);
4561
        }
4562
    }
4563
    else {
4564
        /* Left-to-right k-ary sliding window exponentiation
4565
         * (Handbook of Applied Cryptography (HAC) Algorithm 14.85)
4566
         */
4567
        Py_INCREF(a);
4568
        table[0] = a;
4569
        num_table_entries = 1;
4570
        MULT(a, a, a2);
4571
        /* table[i] == a**(2*i + 1) % c */
4572
        
for (i = 1; 160
i < EXP_TABLE_LEN;
++i2.40k
) {
  Branch (4572:21): [True: 2.40k, False: 160]
4573
            table[i] = NULL; /* must set to known value for MULT */
4574
            MULT(table[i-1], a2, table[i]);
4575
            ++num_table_entries; /* incremented iff MULT succeeded */
4576
        }
4577
        Py_CLEAR(a2);
4578
4579
        /* Repeatedly extract the next (no more than) EXP_WINDOW_SIZE bits
4580
         * into `pending`, starting with the next 1 bit.  The current bit
4581
         * length of `pending` is `blen`.
4582
         */
4583
        int pending = 0, blen = 0;
4584
#define ABSORB_PENDING  do { \
4585
            int ntz = 0; /* number of trailing zeroes in `pending` */ \
4586
            assert(pending && blen); \
4587
            assert(pending >> (blen - 1)); \
4588
            assert(pending >> blen == 0); \
4589
            while ((pending & 1) == 0) { \
4590
                ++ntz; \
4591
                pending >>= 1; \
4592
            } \
4593
            assert(ntz < blen); \
4594
            blen -= ntz; \
4595
            do { \
4596
                MULT(z, z, z); \
4597
            } while (--blen); \
4598
            MULT(z, table[pending >> 1], z); \
4599
            
while (411k
ntz-- > 0) \
4600
                
MULT385k
(z, z, z); \
4601
            assert(blen == 0); \
4602
            pending = 0; \
4603
        } while(0)
4604
4605
        for (i = 
Py_SIZE160
(b) - 1; i >= 0;
--i82.4k
) {
  Branch (4605:34): [True: 82.4k, False: 160]
4606
            const digit bi = b->ob_digit[i];
4607
            for (j = 
PyLong_SHIFT82.4k
- 1; j >= 0;
--j2.47M
) {
  Branch (4607:40): [True: 2.47M, False: 82.4k]
4608
                const int bit = (bi >> j) & 1;
4609
                pending = (pending << 1) | bit;
4610
                if (pending) {
  Branch (4610:21): [True: 2.05M, False: 414k]
4611
                    ++blen;
4612
                    if (blen == EXP_WINDOW_SIZE)
  Branch (4612:25): [True: 411k, False: 1.64M]
4613
                        ABSORB_PENDING;
4614
                }
4615
                else /* absorb strings of 0 bits */
4616
                    MULT(z, z, z);
4617
            }
4618
        }
4619
        if (pending)
  Branch (4619:13): [True: 34, False: 126]
4620
            ABSORB_PENDING;
4621
    }
4622
4623
    if (negativeOutput && 
(24.5k
Py_SIZE24.5k
(z) != 0)) {
  Branch (4623:9): [True: 24.5k, False: 2.13M]
  Branch (4623:27): [True: 23.6k, False: 919]
4624
        temp = (PyLongObject *)long_sub(z, c);
4625
        if (temp == NULL)
  Branch (4625:13): [True: 0, False: 23.6k]
4626
            goto Error;
4627
        Py_DECREF(z);
4628
        z = temp;
4629
        temp = NULL;
4630
    }
4631
    goto Done;
4632
4633
  Error:
4634
    Py_CLEAR(z);
4635
    /* fall through */
4636
  Done:
4637
    for (i = 0; i < num_table_entries; 
++i2.56k
)
  Branch (4637:17): [True: 2.56k, False: 2.17M]
4638
        Py_DECREF(table[i]);
4639
    Py_DECREF(a);
4640
    Py_DECREF(b);
4641
    Py_XDECREF(c);
4642
    Py_XDECREF(a2);
4643
    Py_XDECREF(temp);
4644
    return (PyObject *)z;
4645
}
4646
4647
static PyObject *
4648
long_invert(PyLongObject *v)
4649
{
4650
    /* Implement ~x as -(x+1) */
4651
    PyLongObject *x;
4652
    if (IS_MEDIUM_VALUE(v))
4653
        return _PyLong_FromSTwoDigits(~medium_value(v));
4654
    x = (PyLongObject *) long_add(v, (PyLongObject *)_PyLong_GetOne());
4655
    if (x == NULL)
  Branch (4655:9): [True: 0, False: 11.5k]
4656
        return NULL;
4657
    _PyLong_Negate(&x);
4658
    /* No need for maybe_small_long here, since any small
4659
       longs will have been caught in the Py_SIZE <= 1 fast path. */
4660
    return (PyObject *)x;
4661
}
4662
4663
static PyObject *
4664
long_neg(PyLongObject *v)
4665
{
4666
    PyLongObject *z;
4667
    if (IS_MEDIUM_VALUE(v))
4668
        return _PyLong_FromSTwoDigits(-medium_value(v));
4669
    z = (PyLongObject *)_PyLong_Copy(v);
4670
    if (z != NULL)
  Branch (4670:9): [True: 223k, False: 0]
4671
        Py_SET_SIZE(z, -(Py_SIZE(v)));
4672
    return (PyObject *)z;
4673
}
4674
4675
static PyObject *
4676
long_abs(PyLongObject *v)
4677
{
4678
    if (Py_SIZE(v) < 0)
  Branch (4678:9): [True: 283k, False: 1.04M]
4679
        return long_neg(v);
4680
    else
4681
        return long_long((PyObject *)v);
4682
}
4683
4684
static int
4685
long_bool(PyLongObject *v)
4686
{
4687
    return Py_SIZE(v) != 0;
4688
}
4689
4690
/* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4691
static int
4692
divmod_shift(PyObject *shiftby, Py_ssize_t *wordshift, digit *remshift)
4693
{
4694
    assert(PyLong_Check(shiftby));
4695
    assert(Py_SIZE(shiftby) >= 0);
4696
    Py_ssize_t lshiftby = PyLong_AsSsize_t((PyObject *)shiftby);
4697
    if (lshiftby >= 0) {
  Branch (4697:9): [True: 2.72M, False: 6]
4698
        *wordshift = lshiftby / PyLong_SHIFT;
4699
        *remshift = lshiftby % PyLong_SHIFT;
4700
        return 0;
4701
    }
4702
    /* PyLong_Check(shiftby) is true and Py_SIZE(shiftby) >= 0, so it must
4703
       be that PyLong_AsSsize_t raised an OverflowError. */
4704
    assert(PyErr_ExceptionMatches(PyExc_OverflowError));
4705
    PyErr_Clear();
4706
    PyLongObject *wordshift_obj = divrem1((PyLongObject *)shiftby, PyLong_SHIFT, remshift);
4707
    if (wordshift_obj == NULL) {
  Branch (4707:9): [True: 0, False: 6]
4708
        return -1;
4709
    }
4710
    *wordshift = PyLong_AsSsize_t((PyObject *)wordshift_obj);
4711
    Py_DECREF(wordshift_obj);
4712
    if (*wordshift >= 0 && 
*wordshift < 0
PY_SSIZE_T_MAX0
/ (Py_ssize_t)sizeof(digit)) {
  Branch (4712:9): [True: 0, False: 6]
  Branch (4712:28): [True: 0, False: 0]
4713
        return 0;
4714
    }
4715
    PyErr_Clear();
4716
    /* Clip the value.  With such large wordshift the right shift
4717
       returns 0 and the left shift raises an error in _PyLong_New(). */
4718
    *wordshift = PY_SSIZE_T_MAX / sizeof(digit);
4719
    *remshift = 0;
4720
    return 0;
4721
}
4722
4723
/* Inner function for both long_rshift and _PyLong_Rshift, shifting an
4724
   integer right by PyLong_SHIFT*wordshift + remshift bits.
4725
   wordshift should be nonnegative. */
4726
4727
static PyObject *
4728
long_rshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
4729
{
4730
    PyLongObject *z = NULL;
4731
    Py_ssize_t newsize, hishift, size_a;
4732
    twodigits accum;
4733
    int a_negative;
4734
4735
    /* Total number of bits shifted must be nonnegative. */
4736
    assert(wordshift >= 0);
4737
    assert(remshift < PyLong_SHIFT);
4738
4739
    /* Fast path for small a. */
4740
    if (IS_MEDIUM_VALUE(a)) {
4741
        stwodigits m, x;
4742
        digit shift;
4743
        m = medium_value(a);
4744
        shift = wordshift == 0 ? 
remshift930k
:
PyLong_SHIFT5.82k
;
  Branch (4744:17): [True: 930k, False: 5.82k]
4745
        x = m < 0 ? 
~(~m >> shift)10.8k
:
m >> shift925k
;
  Branch (4745:13): [True: 10.8k, False: 925k]
4746
        return _PyLong_FromSTwoDigits(x);
4747
    }
4748
4749
    a_negative = Py_SIZE(a) < 0;
4750
    size_a = Py_ABS(Py_SIZE(a));
4751
4752
    if (a_negative) {
  Branch (4752:9): [True: 17.9k, False: 346k]
4753
        /* For negative 'a', adjust so that 0 < remshift <= PyLong_SHIFT,
4754
           while keeping PyLong_SHIFT*wordshift + remshift the same. This
4755
           ensures that 'newsize' is computed correctly below. */
4756
        if (remshift == 0) {
  Branch (4756:13): [True: 600, False: 17.3k]
4757
            if (wordshift == 0) {
  Branch (4757:17): [True: 301, False: 299]
4758
                /* Can only happen if the original shift was 0. */
4759
                return long_long((PyObject *)a);
4760
            }
4761
            remshift = PyLong_SHIFT;
4762
            --wordshift;
4763
        }
4764
    }
4765
4766
    assert(wordshift >= 0);
4767
    newsize = size_a - wordshift;
4768
    if (newsize <= 0) {
  Branch (4768:9): [True: 2, False: 363k]
4769
        /* Shifting all the bits of 'a' out gives either -1 or 0. */
4770
        return PyLong_FromLong(-a_negative);
4771
    }
4772
    z = _PyLong_New(newsize);
4773
    if (z == NULL) {
  Branch (4773:9): [True: 0, False: 363k]
4774
        return NULL;
4775
    }
4776
    hishift = PyLong_SHIFT - remshift;
4777
4778
    accum = a->ob_digit[wordshift];
4779
    if (a_negative) {
  Branch (4779:9): [True: 17.6k, False: 346k]
4780
        /*
4781
            For a positive integer a and nonnegative shift, we have:
4782
4783
                (-a) >> shift == -((a + 2**shift - 1) >> shift).
4784
4785
            In the addition `a + (2**shift - 1)`, the low `wordshift` digits of
4786
            `2**shift - 1` all have value `PyLong_MASK`, so we get a carry out
4787
            from the bottom `wordshift` digits when at least one of the least
4788
            significant `wordshift` digits of `a` is nonzero. Digit `wordshift`
4789
            of `2**shift - 1` has value `PyLong_MASK >> hishift`.
4790
        */
4791
        Py_SET_SIZE(z, -newsize);
4792
4793
        digit sticky = 0;
4794
        for (Py_ssize_t j = 0; j < wordshift; 
j++8.58k
) {
  Branch (4794:32): [True: 8.58k, False: 17.6k]
4795
            sticky |= a->ob_digit[j];
4796
        }
4797
        accum += (PyLong_MASK >> hishift) + (digit)(sticky != 0);
4798
    }
4799
4800
    accum >>= remshift;
4801
    for (Py_ssize_t i = 0, j = wordshift + 1; j < size_a; 
i++, j++757k
) {
  Branch (4801:47): [True: 757k, False: 363k]
4802
        accum += (twodigits)a->ob_digit[j] << hishift;
4803
        z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4804
        accum >>= PyLong_SHIFT;
4805
    }
4806
    assert(accum <= PyLong_MASK);
4807
    z->ob_digit[newsize - 1] = (digit)accum;
4808
4809
    z = maybe_small_long(long_normalize(z));
4810
    return (PyObject *)z;
4811
}
4812
4813
static PyObject *
4814
long_rshift(PyObject *a, PyObject *b)
4815
{
4816
    Py_ssize_t wordshift;
4817
    digit remshift;
4818
4819
    CHECK_BINOP(a, b);
4820
4821
    if (Py_SIZE(b) < 0) {
  Branch (4821:9): [True: 5, False: 1.18M]
4822
        PyErr_SetString(PyExc_ValueError, "negative shift count");
4823
        return NULL;
4824
    }
4825
    if (Py_SIZE(a) == 0) {
  Branch (4825:9): [True: 33.3k, False: 1.15M]
4826
        return PyLong_FromLong(0);
4827
    }
4828
    if (divmod_shift(b, &wordshift, &remshift) < 0)
  Branch (4828:9): [True: 0, False: 1.15M]
4829
        return NULL;
4830
    return long_rshift1((PyLongObject *)a, wordshift, remshift);
4831
}
4832
4833
/* Return a >> shiftby. */
4834
PyObject *
4835
_PyLong_Rshift(PyObject *a, size_t shiftby)
4836
{
4837
    Py_ssize_t wordshift;
4838
    digit remshift;
4839
4840
    assert(PyLong_Check(a));
4841
    if (Py_SIZE(a) == 0) {
  Branch (4841:9): [True: 0, False: 144k]
4842
        return PyLong_FromLong(0);
4843
    }
4844
    wordshift = shiftby / PyLong_SHIFT;
4845
    remshift = shiftby % PyLong_SHIFT;
4846
    return long_rshift1((PyLongObject *)a, wordshift, remshift);
4847
}
4848
4849
static PyObject *
4850
long_lshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
4851
{
4852
    PyLongObject *z = NULL;
4853
    Py_ssize_t oldsize, newsize, i, j;
4854
    twodigits accum;
4855
4856
    if (wordshift == 0 && 
IS_MEDIUM_VALUE657k
(a)) {
  Branch (4856:9): [True: 657k, False: 1.03M]
4857
        stwodigits m = medium_value(a);
4858
        // bypass undefined shift operator behavior
4859
        stwodigits x = m < 0 ? 
-(-m << remshift)10.6k
:
m << remshift359k
;
  Branch (4859:24): [True: 10.6k, False: 359k]
4860
        return _PyLong_FromSTwoDigits(x);
4861
    }
4862
4863
    oldsize = Py_ABS(Py_SIZE(a));
4864
    newsize = oldsize + wordshift;
4865
    if (remshift)
  Branch (4865:9): [True: 1.16M, False: 160k]
4866
        ++newsize;
4867
    z = _PyLong_New(newsize);
4868
    if (z == NULL)
  Branch (4868:9): [True: 0, False: 1.32M]
4869
        return NULL;
4870
    if (Py_SIZE(a) < 0) {
  Branch (4870:9): [True: 301k, False: 1.02M]
4871
        assert(Py_REFCNT(z) == 1);
4872
        Py_SET_SIZE(z, -Py_SIZE(z));
4873
    }
4874
    for (i = 0; i < wordshift; 
i++5.24M
)
  Branch (4874:17): [True: 5.24M, False: 1.32M]
4875
        z->ob_digit[i] = 0;
4876
    accum = 0;
4877
    for (j = 0; j < oldsize; 
i++, j++10.7M
) {
  Branch (4877:17): [True: 10.7M, False: 1.32M]
4878
        accum |= (twodigits)a->ob_digit[j] << remshift;
4879
        z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4880
        accum >>= PyLong_SHIFT;
4881
    }
4882
    if (remshift)
  Branch (4882:9): [True: 1.16M, False: 160k]
4883
        z->ob_digit[newsize-1] = (digit)accum;
4884
    else
4885
        assert(!accum);
4886
    z = long_normalize(z);
4887
    return (PyObject *) maybe_small_long(z);
4888
}
4889
4890
static PyObject *
4891
long_lshift(PyObject *a, PyObject *b)
4892
{
4893
    Py_ssize_t wordshift;
4894
    digit remshift;
4895
4896
    CHECK_BINOP(a, b);
4897
4898
    if (Py_SIZE(b) < 0) {
  Branch (4898:9): [True: 7, False: 1.61M]
4899
        PyErr_SetString(PyExc_ValueError, "negative shift count");
4900
        return NULL;
4901
    }
4902
    if (Py_SIZE(a) == 0) {
  Branch (4902:9): [True: 39.2k, False: 1.57M]
4903
        return PyLong_FromLong(0);
4904
    }
4905
    if (divmod_shift(b, &wordshift, &remshift) < 0)
  Branch (4905:9): [True: 0, False: 1.57M]
4906
        return NULL;
4907
    return long_lshift1((PyLongObject *)a, wordshift, remshift);
4908
}
4909
4910
/* Return a << shiftby. */
4911
PyObject *
4912
_PyLong_Lshift(PyObject *a, size_t shiftby)
4913
{
4914
    Py_ssize_t wordshift;
4915
    digit remshift;
4916
4917
    assert(PyLong_Check(a));
4918
    if (Py_SIZE(a) == 0) {
  Branch (4918:9): [True: 0, False: 121k]
4919
        return PyLong_FromLong(0);
4920
    }
4921
    wordshift = shiftby / PyLong_SHIFT;
4922
    remshift = shiftby % PyLong_SHIFT;
4923
    return long_lshift1((PyLongObject *)a, wordshift, remshift);
4924
}
4925
4926
/* Compute two's complement of digit vector a[0:m], writing result to
4927
   z[0:m].  The digit vector a need not be normalized, but should not
4928
   be entirely zero.  a and z may point to the same digit vector. */
4929
4930
static void
4931
v_complement(digit *z, digit *a, Py_ssize_t m)
4932
{
4933
    Py_ssize_t i;
4934
    digit carry = 1;
4935
    for (i = 0; i < m; 
++i3.77M
) {
  Branch (4935:17): [True: 3.77M, False: 701k]
4936
        carry += a[i] ^ PyLong_MASK;
4937
        z[i] = carry & PyLong_MASK;
4938
        carry >>= PyLong_SHIFT;
4939
    }
4940
    assert(carry == 0);
4941
}
4942
4943
/* Bitwise and/xor/or operations */
4944
4945
static PyObject *
4946
long_bitwise(PyLongObject *a,
4947
             char op,  /* '&', '|', '^' */
4948
             PyLongObject *b)
4949
{
4950
    int nega, negb, negz;
4951
    Py_ssize_t size_a, size_b, size_z, i;
4952
    PyLongObject *z;
4953
4954
    /* Bitwise operations for negative numbers operate as though
4955
       on a two's complement representation.  So convert arguments
4956
       from sign-magnitude to two's complement, and convert the
4957
       result back to sign-magnitude at the end. */
4958
4959
    /* If a is negative, replace it by its two's complement. */
4960
    size_a = Py_ABS(Py_SIZE(a));
4961
    nega = Py_SIZE(a) < 0;
4962
    if (nega) {
  Branch (4962:9): [True: 583k, False: 817k]
4963
        z = _PyLong_New(size_a);
4964
        if (z == NULL)
  Branch (4964:13): [True: 0, False: 583k]
4965
            return NULL;
4966
        v_complement(z->ob_digit, a->ob_digit, size_a);
4967
        a = z;
4968
    }
4969
    else
4970
        /* Keep reference count consistent. */
4971
        Py_INCREF(a);
4972
4973
    /* Same for b. */
4974
    size_b = Py_ABS(Py_SIZE(b));
4975
    negb = Py_SIZE(b) < 0;
4976
    if (negb) {
  Branch (4976:9): [True: 68.6k, False: 1.33M]
4977
        z = _PyLong_New(size_b);
4978
        if (z == NULL) {
  Branch (4978:13): [True: 0, False: 68.6k]
4979
            Py_DECREF(a);
4980
            return NULL;
4981
        }
4982
        v_complement(z->ob_digit, b->ob_digit, size_b);
4983
        b = z;
4984
    }
4985
    else
4986
        Py_INCREF(b);
4987
4988
    /* Swap a and b if necessary to ensure size_a >= size_b. */
4989
    if (size_a < size_b) {
  Branch (4989:9): [True: 54.7k, False: 1.34M]
4990
        z = a; a = b; b = z;
4991
        size_z = size_a; size_a = size_b; size_b = size_z;
4992
        negz = nega; nega = negb; negb = negz;
4993
    }
4994
4995
    /* JRH: The original logic here was to allocate the result value (z)
4996
       as the longer of the two operands.  However, there are some cases
4997
       where the result is guaranteed to be shorter than that: AND of two
4998
       positives, OR of two negatives: use the shorter number.  AND with
4999
       mixed signs: use the positive number.  OR with mixed signs: use the
5000
       negative number.
5001
    */
5002
    switch (op) {
5003
    case '^':
  Branch (5003:5): [True: 61.0k, False: 1.33M]
5004
        negz = nega ^ negb;
5005
        size_z = size_a;
5006
        break;
5007
    case '&':
  Branch (5007:5): [True: 1.19M, False: 209k]
5008
        negz = nega & negb;
5009
        size_z = negb ? 
size_a37.9k
:
size_b1.15M
;
  Branch (5009:18): [True: 37.9k, False: 1.15M]
5010
        break;
5011
    case '|':
  Branch (5011:5): [True: 148k, False: 1.25M]
5012
        negz = nega | negb;
5013
        size_z = negb ? 
size_b2.24k
:
size_a146k
;
  Branch (5013:18): [True: 2.24k, False: 146k]
5014
        break;
5015
    default:
  Branch (5015:5): [True: 0, False: 1.40M]
5016
        Py_UNREACHABLE();
5017
    }
5018
5019
    /* We allow an extra digit if z is negative, to make sure that
5020
       the final two's complement of z doesn't overflow. */
5021
    z = _PyLong_New(size_z + negz);
5022
    if (z == NULL) {
  Branch (5022:9): [True: 0, False: 1.40M]
5023
        Py_DECREF(a);
5024
        Py_DECREF(b);
5025
        return NULL;
5026
    }
5027
5028
    /* Compute digits for overlap of a and b. */
5029
    switch(op) {
5030
    case '&':
  Branch (5030:5): [True: 1.19M, False: 209k]
5031
        for (i = 0; i < size_b; 
++i1.27M
)
  Branch (5031:21): [True: 1.27M, False: 1.19M]
5032
            z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
5033
        break;
5034
    case '|':
  Branch (5034:5): [True: 148k, False: 1.25M]
5035
        for (i = 0; i < size_b; 
++i206k
)
  Branch (5035:21): [True: 206k, False: 148k]
5036
            z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
5037
        break;
5038
    case '^':
  Branch (5038:5): [True: 61.0k, False: 1.33M]
5039
        for (i = 0; i < size_b; 
++i1.09M
)
  Branch (5039:21): [True: 1.09M, False: 61.0k]
5040
            z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
5041
        break;
5042
    default:
  Branch (5042:5): [True: 0, False: 1.40M]
5043
        Py_UNREACHABLE();
5044
    }
5045
5046
    /* Copy any remaining digits of a, inverting if necessary. */
5047
    if (op == '^' && 
negb61.0k
)
  Branch (5047:9): [True: 61.0k, False: 1.33M]
  Branch (5047:22): [True: 26.0k, False: 34.9k]
5048
        
for (; 26.0k
i < size_z;
++i240k
)
  Branch (5048:16): [True: 240k, False: 26.0k]
5049
            z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
5050
    else if (i < size_z)
  Branch (5050:14): [True: 191k, False: 1.18M]
5051
        memcpy(&z->ob_digit[i], &a->ob_digit[i],
5052
               (size_z-i)*sizeof(digit));
5053
5054
    /* Complement result if negative. */
5055
    if (negz) {
  Branch (5055:9): [True: 49.8k, False: 1.35M]
5056
        Py_SET_SIZE(z, -(Py_SIZE(z)));
5057
        z->ob_digit[size_z] = PyLong_MASK;
5058
        v_complement(z->ob_digit, z->ob_digit, size_z+1);
5059
    }
5060
5061
    Py_DECREF(a);
5062
    Py_DECREF(b);
5063
    return (PyObject *)maybe_small_long(long_normalize(z));
5064
}
5065
5066
static PyObject *
5067
long_and(PyObject *a, PyObject *b)
5068
{
5069
    CHECK_BINOP(a, b);
5070
    PyLongObject *x = (PyLongObject*)a;
5071
    PyLongObject *y = (PyLongObject*)b;
5072
    if (IS_MEDIUM_VALUE(x) && 
IS_MEDIUM_VALUE3.96M
(y)) {
5073
        return _PyLong_FromSTwoDigits(medium_value(x) & medium_value(y));
5074
    }
5075
    return long_bitwise(x, '&', y);
5076
}
5077
5078
static PyObject *
5079
long_xor(PyObject *a, PyObject *b)
5080
{
5081
    CHECK_BINOP(a, b);
5082
    PyLongObject *x = (PyLongObject*)a;
5083
    PyLongObject *y = (PyLongObject*)b;
5084
    if (IS_MEDIUM_VALUE(x) && 
IS_MEDIUM_VALUE131k
(y)) {
5085
        return _PyLong_FromSTwoDigits(medium_value(x) ^ medium_value(y));
5086
    }
5087
    return long_bitwise(x, '^', y);
5088
}
5089
5090
static PyObject *
5091
long_or(PyObject *a, PyObject *b)
5092
{
5093
    CHECK_BINOP(a, b);
5094
    PyLongObject *x = (PyLongObject*)a;
5095
    PyLongObject *y = (PyLongObject*)b;
5096
    if (IS_MEDIUM_VALUE(x) && 
IS_MEDIUM_VALUE1.95M
(y)) {
5097
        return _PyLong_FromSTwoDigits(medium_value(x) | medium_value(y));
5098
    }
5099
    return long_bitwise(x, '|', y);
5100
}
5101
5102
static PyObject *
5103
long_long(PyObject *v)
5104
{
5105
    if (PyLong_CheckExact(v))
5106
        Py_INCREF(v);
5107
    else
5108
        v = _PyLong_Copy((PyLongObject *)v);
5109
    return v;
5110
}
5111
5112
PyObject *
5113
_PyLong_GCD(PyObject *aarg, PyObject *barg)
5114
{
5115
    PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
5116
    stwodigits x, y, q, s, t, c_carry, d_carry;
5117
    stwodigits A, B, C, D, T;
5118
    int nbits, k;
5119
    Py_ssize_t size_a, size_b, alloc_a, alloc_b;
5120
    digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
5121
5122
    a = (PyLongObject *)aarg;
5123
    b = (PyLongObject *)barg;
5124
    size_a = Py_SIZE(a);
5125
    size_b = Py_SIZE(b);
5126
    if (-2 <= size_a && 
size_a <= 2500k
&&
-2 <= size_b390k
&&
size_b <= 2390k
) {
  Branch (5126:9): [True: 500k, False: 40]
  Branch (5126:25): [True: 390k, False: 109k]
  Branch (5126:40): [True: 390k, False: 0]
  Branch (5126:56): [True: 320k, False: 70.0k]
5127
        Py_INCREF(a);
5128
        Py_INCREF(b);
5129
        goto simple;
5130
    }
5131
5132
    /* Initial reduction: make sure that 0 <= b <= a. */
5133
    a = (PyLongObject *)long_abs(a);
5134
    if (a == NULL)
  Branch (5134:9): [True: 0, False: 179k]
5135
        return NULL;
5136
    b = (PyLongObject *)long_abs(b);
5137
    if (b == NULL) {
  Branch (5137:9): [True: 0, False: 179k]
5138
        Py_DECREF(a);
5139
        return NULL;
5140
    }
5141
    if (long_compare(a, b) < 0) {
  Branch (5141:9): [True: 106k, False: 73.4k]
5142
        r = a;
5143
        a = b;
5144
        b = r;
5145
    }
5146
    /* We now own references to a and b */
5147
5148
    alloc_a = Py_SIZE(a);
5149
    alloc_b = Py_SIZE(b);
5150
    /* reduce until a fits into 2 digits */
5151
    while ((size_a = Py_SIZE(a)) > 2) {
  Branch (5151:12): [True: 279k, False: 115k]
5152
        nbits = bit_length_digit(a->ob_digit[size_a-1]);
5153
        /* extract top 2*PyLong_SHIFT bits of a into x, along with
5154
           corresponding bits of b into y */
5155
        size_b = Py_SIZE(b);
5156
        assert(size_b <= size_a);
5157
        if (size_b == 0) {
  Branch (5157:13): [True: 64.3k, False: 214k]
5158
            if (size_a < alloc_a) {
  Branch (5158:17): [True: 16, False: 64.3k]
5159
                r = (PyLongObject *)_PyLong_Copy(a);
5160
                Py_DECREF(a);
5161
            }
5162
            else
5163
                r = a;
5164
            Py_DECREF(b);
5165
            Py_XDECREF(c);
5166
            Py_XDECREF(d);
5167
            return (PyObject *)r;
5168
        }
5169
        x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
5170
             ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
5171
             (a->ob_digit[size_a-3] >> nbits));
5172
5173
        y = ((size_b >= size_a - 2 ? 
b->ob_digit[size_a-3] >> nbits185k
:
029.3k
) |
  Branch (5173:15): [True: 185k, False: 29.3k]
5174
             (size_b >= size_a - 1 ? 
(twodigits)b->ob_digit[size_a-2] << (152k
PyLong_SHIFT152k
-nbits) :
062.5k
) |
  Branch (5174:15): [True: 152k, False: 62.5k]
5175
             (size_b >= size_a ? 
(twodigits)b->ob_digit[size_a-1] << (2*99.9k
PyLong_SHIFT99.9k
-nbits) :
0114k
));
  Branch (5175:15): [True: 99.9k, False: 114k]
5176
5177
        /* inner loop of Lehmer's algorithm; A, B, C, D never grow
5178
           larger than PyLong_MASK during the algorithm. */
5179
        A = 1; B = 0; C = 0; D = 1;
5180
        for (k=0;; 
k++908k
) {
5181
            if (y-C == 0)
  Branch (5181:17): [True: 42.8k, False: 1.08M]
5182
                break;
5183
            q = (x+(A-1))/(y-C);
5184
            s = B+q*D;
5185
            t = x-q*y;
5186
            if (s > t)
  Branch (5186:17): [True: 172k, False: 908k]
5187
                break;
5188
            x = y; y = t;
5189
            t = A+q*C; A = D; B = C; C = s; D = t;
5190
        }
5191
5192
        if (k == 0) {
  Branch (5192:13): [True: 140k, False: 74.4k]
5193
            /* no progress; do a Euclidean step */
5194
            if (l_mod(a, b, &r) < 0)
  Branch (5194:17): [True: 0, False: 140k]
5195
                goto error;
5196
            Py_DECREF(a);
5197
            a = b;
5198
            b = r;
5199
            alloc_a = alloc_b;
5200
            alloc_b = Py_SIZE(b);
5201
            continue;
5202
        }
5203
5204
        /*
5205
          a, b = A*b-B*a, D*a-C*b if k is odd
5206
          a, b = A*a-B*b, D*b-C*a if k is even
5207
        */
5208
        if (k&1) {
  Branch (5208:13): [True: 37.5k, False: 36.8k]
5209
            T = -A; A = -B; B = T;
5210
            T = -C; C = -D; D = T;
5211
        }
5212
        if (c != NULL) {
  Branch (5212:13): [True: 24.4k, False: 49.9k]
5213
            Py_SET_SIZE(c, size_a);
5214
        }
5215
        else if (Py_REFCNT(a) == 1) {
  Branch (5215:18): [True: 16, False: 49.9k]
5216
            Py_INCREF(a);
5217
            c = a;
5218
        }
5219
        else {
5220
            alloc_a = size_a;
5221
            c = _PyLong_New(size_a);
5222
            if (c == NULL)
  Branch (5222:17): [True: 0, False: 49.9k]
5223
                goto error;
5224
        }
5225
5226
        if (d != NULL) {
  Branch (5226:13): [True: 24.4k, False: 49.9k]
5227
            Py_SET_SIZE(d, size_a);
5228
        }
5229
        else if (Py_REFCNT(b) == 1 && 
size_a <= alloc_b11.7k
) {
  Branch (5229:18): [True: 11.7k, False: 38.2k]
  Branch (5229:39): [True: 11.1k, False: 621]
5230
            Py_INCREF(b);
5231
            d = b;
5232
            Py_SET_SIZE(d, size_a);
5233
        }
5234
        else {
5235
            alloc_b = size_a;
5236
            d = _PyLong_New(size_a);
5237
            if (d == NULL)
  Branch (5237:17): [True: 0, False: 38.8k]
5238
                goto error;
5239
        }
5240
        a_end = a->ob_digit + size_a;
5241
        b_end = b->ob_digit + size_b;
5242
5243
        /* compute new a and new b in parallel */
5244
        a_digit = a->ob_digit;
5245
        b_digit = b->ob_digit;
5246
        c_digit = c->ob_digit;
5247
        d_digit = d->ob_digit;
5248
        c_carry = 0;
5249
        d_carry = 0;
5250
        while (b_digit < b_end) {
  Branch (5250:16): [True: 220k, False: 74.4k]
5251
            c_carry += (A * *a_digit) - (B * *b_digit);
5252
            d_carry += (D * *b_digit++) - (C * *a_digit++);
5253
            *c_digit++ = (digit)(c_carry & PyLong_MASK);
5254
            *d_digit++ = (digit)(d_carry & PyLong_MASK);
5255
            c_carry >>= PyLong_SHIFT;
5256
            d_carry >>= PyLong_SHIFT;
5257
        }
5258
        while (a_digit < a_end) {
  Branch (5258:16): [True: 35.5k, False: 74.4k]
5259
            c_carry += A * *a_digit;
5260
            d_carry -= C * *a_digit++;
5261
            *c_digit++ = (digit)(c_carry & PyLong_MASK);
5262
            *d_digit++ = (digit)(d_carry & PyLong_MASK);
5263
            c_carry >>= PyLong_SHIFT;
5264
            d_carry >>= PyLong_SHIFT;
5265
        }
5266
        assert(c_carry == 0);
5267
        assert(d_carry == 0);
5268
5269
        Py_INCREF(c);
5270
        Py_INCREF(d);
5271
        Py_DECREF(a);
5272
        Py_DECREF(b);
5273
        a = long_normalize(c);
5274
        b = long_normalize(d);
5275
    }
5276
    Py_XDECREF(c);
5277
    Py_XDECREF(d);
5278
5279
simple:
5280
    assert(Py_REFCNT(a) > 0);
5281
    assert(Py_REFCNT(b) > 0);
5282
/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
5283
   undefined behaviour when LONG_MAX type is smaller than 60 bits */
5284
#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
5285
    /* a fits into a long, so b must too */
5286
    x = PyLong_AsLong((PyObject *)a);
5287
    y = PyLong_AsLong((PyObject *)b);
5288
#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
5289
    x = PyLong_AsLongLong((PyObject *)a);
5290
    y = PyLong_AsLongLong((PyObject *)b);
5291
#else
5292
# error "_PyLong_GCD"
5293
#endif
5294
    x = Py_ABS(x);
5295
    y = Py_ABS(y);
5296
    Py_DECREF(a);
5297
    Py_DECREF(b);
5298
5299
    /* usual Euclidean algorithm for longs */
5300
    while (y != 0) {
  Branch (5300:12): [True: 4.37M, False: 435k]
5301
        t = y;
5302
        y = x % y;
5303
        x = t;
5304
    }
5305
#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
5306
    return PyLong_FromLong(x);
5307
#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
5308
    return PyLong_FromLongLong(x);
5309
#else
5310
# error "_PyLong_GCD"
5311
#endif
5312
5313
error:
5314
    Py_DECREF(a);
5315
    Py_DECREF(b);
5316
    Py_XDECREF(c);
5317
    Py_XDECREF(d);
5318
    return NULL;
5319
}
5320
5321
static PyObject *
5322
long_float(PyObject *v)
5323
{
5324
    double result;
5325
    result = PyLong_AsDouble(v);
5326
    if (result == -1.0 && 
PyErr_Occurred()65.6k
)
  Branch (5326:9): [True: 65.6k, False: 183k]
  Branch (5326:27): [True: 52, False: 65.6k]
5327
        return NULL;
5328
    return PyFloat_FromDouble(result);
5329
}
5330
5331
static PyObject *
5332
long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase);
5333
5334
/*[clinic input]
5335
@classmethod
5336
int.__new__ as long_new
5337
    x: object(c_default="NULL") = 0
5338
    /
5339
    base as obase: object(c_default="NULL") = 10
5340
[clinic start generated code]*/
5341
5342
static PyObject *
5343
long_new_impl(PyTypeObject *type, PyObject *x, PyObject *obase)
5344
/*[clinic end generated code: output=e47cfe777ab0f24c input=81c98f418af9eb6f]*/
5345
{
5346
    Py_ssize_t base;
5347
5348
    if (type != &PyLong_Type)
  Branch (5348:9): [True: 50.6k, False: 5.36M]
5349
        return long_subtype_new(type, x, obase); /* Wimp out */
5350
    if (x == NULL) {
  Branch (5350:9): [True: 21.0k, False: 5.34M]
5351
        if (obase != NULL) {
  Branch (5351:13): [True: 2, False: 21.0k]
5352
            PyErr_SetString(PyExc_TypeError,
5353
                            "int() missing string argument");
5354
            return NULL;
5355
        }
5356
        return PyLong_FromLong(0L);
5357
    }
5358
    if (obase == NULL)
  Branch (5358:9): [True: 5.10M, False: 237k]
5359
        return PyNumber_Long(x);
5360
5361
    base = PyNumber_AsSsize_t(obase, NULL);
5362
    if (base == -1 && 
PyErr_Occurred()2
)
  Branch (5362:9): [True: 2, False: 237k]
  Branch (5362:23): [True: 2, False: 0]
5363
        return NULL;
5364
    if ((base != 0 && 
base < 2188k
) ||
base > 36237k
) {
  Branch (5364:10): [True: 188k, False: 48.5k]
  Branch (5364:23): [True: 11, False: 188k]
  Branch (5364:36): [True: 9, False: 237k]
5365
        PyErr_SetString(PyExc_ValueError,
5366
                        "int() base must be >= 2 and <= 36, or 0");
5367
        return NULL;
5368
    }
5369
5370
    if (PyUnicode_Check(x))
5371
        return PyLong_FromUnicodeObject(x, (int)base);
5372
    else if (PyByteArray_Check(x) || 
PyBytes_Check47.0k
(x)) {
5373
        const char *string;
5374
        if (PyByteArray_Check(x))
5375
            string = PyByteArray_AS_STRING(x);
5376
        else
5377
            string = PyBytes_AS_STRING(x);
5378
        return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
5379
    }
5380
    else {
5381
        PyErr_SetString(PyExc_TypeError,
5382
                        "int() can't convert non-string with explicit base");
5383
        return NULL;
5384
    }
5385
}
5386
5387
/* Wimpy, slow approach to tp_new calls for subtypes of int:
5388
   first create a regular int from whatever arguments we got,
5389
   then allocate a subtype instance and initialize it from
5390
   the regular int.  The regular int is then thrown away.
5391
*/
5392
static PyObject *
5393
long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase)
5394
{
5395
    PyLongObject *tmp, *newobj;
5396
    Py_ssize_t i, n;
5397
5398
    assert(PyType_IsSubtype(type, &PyLong_Type));
5399
    tmp = (PyLongObject *)long_new_impl(&PyLong_Type, x, obase);
5400
    if (tmp == NULL)
  Branch (5400:9): [True: 0, False: 50.6k]
5401
        return NULL;
5402
    assert(PyLong_Check(tmp));
5403
    n = Py_SIZE(tmp);
5404
    if (n < 0)
  Branch (5404:9): [True: 7, False: 50.6k]
5405
        n = -n;
5406
    newobj = (PyLongObject *)type->tp_alloc(type, n);
5407
    if (newobj == NULL) {
  Branch (5407:9): [True: 0, False: 50.6k]
5408
        Py_DECREF(tmp);
5409
        return NULL;
5410
    }
5411
    assert(PyLong_Check(newobj));
5412
    Py_SET_SIZE(newobj, Py_SIZE(tmp));
5413
    for (i = 0; i < n; 
i++49.3k
) {
  Branch (5413:17): [True: 49.3k, False: 50.6k]
5414
        newobj->ob_digit[i] = tmp->ob_digit[i];
5415
    }
5416
    Py_DECREF(tmp);
5417
    return (PyObject *)newobj;
5418
}
5419
5420
/*[clinic input]
5421
int.__getnewargs__
5422
[clinic start generated code]*/
5423
5424
static PyObject *
5425
int___getnewargs___impl(PyObject *self)
5426
/*[clinic end generated code: output=839a49de3f00b61b input=5904770ab1fb8c75]*/
5427
{
5428
    return Py_BuildValue("(N)", _PyLong_Copy((PyLongObject *)self));
5429
}
5430
5431
static PyObject *
5432
long_get0(PyObject *Py_UNUSED(self), void *Py_UNUSED(context))
5433
{
5434
    return PyLong_FromLong(0L);
5435
}
5436
5437
static PyObject *
5438
long_get1(PyObject *Py_UNUSED(self), void *Py_UNUSED(ignored))
5439
{
5440
    return PyLong_FromLong(1L);
5441
}
5442
5443
/*[clinic input]
5444
int.__format__
5445
5446
    format_spec: unicode
5447
    /
5448
[clinic start generated code]*/
5449
5450
static PyObject *
5451
int___format___impl(PyObject *self, PyObject *format_spec)
5452
/*[clinic end generated code: output=b4929dee9ae18689 input=e31944a9b3e428b7]*/
5453
{
5454
    _PyUnicodeWriter writer;
5455
    int ret;
5456
5457
    _PyUnicodeWriter_Init(&writer);
5458
    ret = _PyLong_FormatAdvancedWriter(
5459
        &writer,
5460
        self,
5461
        format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
5462
    if (ret == -1) {
  Branch (5462:9): [True: 350, False: 1.76k]
5463
        _PyUnicodeWriter_Dealloc(&writer);
5464
        return NULL;
5465
    }
5466
    return _PyUnicodeWriter_Finish(&writer);
5467
}
5468
5469
/* Return a pair (q, r) such that a = b * q + r, and
5470
   abs(r) <= abs(b)/2, with equality possible only if q is even.
5471
   In other words, q == a / b, rounded to the nearest integer using
5472
   round-half-to-even. */
5473
5474
PyObject *
5475
_PyLong_DivmodNear(PyObject *a, PyObject *b)
5476
{
5477
    PyLongObject *quo = NULL, *rem = NULL;
5478
    PyObject *twice_rem, *result, *temp;
5479
    int quo_is_odd, quo_is_neg;
5480
    Py_ssize_t cmp;
5481
5482
    /* Equivalent Python code:
5483
5484
       def divmod_near(a, b):
5485
           q, r = divmod(a, b)
5486
           # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
5487
           # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
5488
           # positive, 2 * r < b if b negative.
5489
           greater_than_half = 2*r > b if b > 0 else 2*r < b
5490
           exactly_half = 2*r == b
5491
           if greater_than_half or exactly_half and q % 2 == 1:
5492
               q += 1
5493
               r -= b
5494
           return q, r
5495
5496
    */
5497
    if (!PyLong_Check(a) || !PyLong_Check(b)) {
  Branch (5497:9): [True: 0, False: 1.56k]
  Branch (5497:29): [True: 0, False: 1.56k]
5498
        PyErr_SetString(PyExc_TypeError,
5499
                        "non-integer arguments in division");
5500
        return NULL;
5501
    }
5502
5503
    /* Do a and b have different signs?  If so, quotient is negative. */
5504
    quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
5505
5506
    if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
  Branch (5506:9): [True: 2, False: 1.56k]
5507
        goto error;
5508
5509
    /* compare twice the remainder with the divisor, to see
5510
       if we need to adjust the quotient and remainder */
5511
    PyObject *one = _PyLong_GetOne();  // borrowed reference
5512
    twice_rem = long_lshift((PyObject *)rem, one);
5513
    if (twice_rem == NULL)
  Branch (5513:9): [True: 0, False: 1.56k]
5514
        goto error;
5515
    if (quo_is_neg) {
  Branch (5515:9): [True: 555, False: 1.01k]
5516
        temp = long_neg((PyLongObject*)twice_rem);
5517
        Py_DECREF(twice_rem);
5518
        twice_rem = temp;
5519
        if (twice_rem == NULL)
  Branch (5519:13): [True: 0, False: 555]
5520
            goto error;
5521
    }
5522
    cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
5523
    Py_DECREF(twice_rem);
5524
5525
    quo_is_odd = Py_SIZE(quo) != 0 && 
((quo->ob_digit[0] & 1) != 0)1.52k
;
  Branch (5525:18): [True: 1.52k, False: 44]
  Branch (5525:39): [True: 562, False: 960]
5526
    if ((Py_SIZE(b) < 0 ? 
cmp < 024
:
cmp > 01.54k
) ||
(1.03k
cmp == 01.03k
&&
quo_is_odd128
)) {
  Branch (5526:9): [True: 528, False: 1.03k]
  Branch (5526:10): [True: 24, False: 1.54k]
  Branch (5526:50): [True: 128, False: 910]
  Branch (5526:62): [True: 63, False: 65]
5527
        /* fix up quotient */
5528
        if (quo_is_neg)
  Branch (5528:13): [True: 247, False: 344]
5529
            temp = long_sub(quo, (PyLongObject *)one);
5530
        else
5531
            temp = long_add(quo, (PyLongObject *)one);
5532
        Py_DECREF(quo);
5533
        quo = (PyLongObject *)temp;
5534
        if (quo == NULL)
  Branch (5534:13): [True: 0, False: 591]
5535
            goto error;
5536
        /* and remainder */
5537
        if (quo_is_neg)
  Branch (5537:13): [True: 247, False: 344]
5538
            temp = long_add(rem, (PyLongObject *)b);
5539
        else
5540
            temp = long_sub(rem, (PyLongObject *)b);
5541
        Py_DECREF(rem);
5542
        rem = (PyLongObject *)temp;
5543
        if (rem == NULL)
  Branch (5543:13): [True: 0, False: 591]
5544
            goto error;
5545
    }
5546
5547
    result = PyTuple_New(2);
5548
    if (result == NULL)
  Branch (5548:9): [True: 0, False: 1.56k]
5549
        goto error;
5550
5551
    /* PyTuple_SET_ITEM steals references */
5552
    PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
5553
    PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
5554
    return result;
5555
5556
  error:
5557
    Py_XDECREF(quo);
5558
    Py_XDECREF(rem);
5559
    return NULL;
5560
}
5561
5562
/*[clinic input]
5563
int.__round__
5564
5565
    ndigits as o_ndigits: object = NULL
5566
    /
5567
5568
Rounding an Integral returns itself.
5569
5570
Rounding with an ndigits argument also returns an integer.
5571
[clinic start generated code]*/
5572
5573
static PyObject *
5574
int___round___impl(PyObject *self, PyObject *o_ndigits)
5575
/*[clinic end generated code: output=954fda6b18875998 input=1614cf23ec9e18c3]*/
5576
{
5577
    PyObject *temp, *result, *ndigits;
5578
5579
    /* To round an integer m to the nearest 10**n (n positive), we make use of
5580
     * the divmod_near operation, defined by:
5581
     *
5582
     *   divmod_near(a, b) = (q, r)
5583
     *
5584
     * where q is the nearest integer to the quotient a / b (the
5585
     * nearest even integer in the case of a tie) and r == a - q * b.
5586
     * Hence q * b = a - r is the nearest multiple of b to a,
5587
     * preferring even multiples in the case of a tie.
5588
     *
5589
     * So the nearest multiple of 10**n to m is:
5590
     *
5591
     *   m - divmod_near(m, 10**n)[1].
5592
     */
5593
    if (o_ndigits == NULL)
  Branch (5593:9): [True: 168, False: 1.67k]
5594
        return long_long(self);
5595
5596
    ndigits = _PyNumber_Index(o_ndigits);
5597
    if (ndigits == NULL)
  Branch (5597:9): [True: 3, False: 1.67k]
5598
        return NULL;
5599
5600
    /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
5601
    if (Py_SIZE(ndigits) >= 0) {
  Branch (5601:9): [True: 512, False: 1.16k]
5602
        Py_DECREF(ndigits);
5603
        return long_long(self);
5604
    }
5605
5606
    /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
5607
    temp = long_neg((PyLongObject*)ndigits);
5608
    Py_DECREF(ndigits);
5609
    ndigits = temp;
5610
    if (ndigits == NULL)
  Branch (5610:9): [True: 0, False: 1.16k]
5611
        return NULL;
5612
5613
    result = PyLong_FromLong(10L);
5614
    if (result == NULL) {
  Branch (5614:9): [True: 0, False: 1.16k]
5615
        Py_DECREF(ndigits);
5616
        return NULL;
5617
    }
5618
5619
    temp = long_pow(result, ndigits, Py_None);
5620
    Py_DECREF(ndigits);
5621
    Py_DECREF(result);
5622
    result = temp;
5623
    if (result == NULL)
  Branch (5623:9): [True: 0, False: 1.16k]
5624
        return NULL;
5625
5626
    temp = _PyLong_DivmodNear(self, result);
5627
    Py_DECREF(result);
5628
    result = temp;
5629
    if (result == NULL)
  Branch (5629:9): [True: 0, False: 1.16k]
5630
        return NULL;
5631
5632
    temp = long_sub((PyLongObject *)self,
5633
                    (PyLongObject *)PyTuple_GET_ITEM(result, 1));
5634
    Py_DECREF(result);
5635
    result = temp;
5636
5637
    return result;
5638
}
5639
5640
/*[clinic input]
5641
int.__sizeof__ -> Py_ssize_t
5642
5643
Returns size in memory, in bytes.
5644
[clinic start generated code]*/
5645
5646
static Py_ssize_t
5647
int___sizeof___impl(PyObject *self)
5648
/*[clinic end generated code: output=3303f008eaa6a0a5 input=9b51620c76fc4507]*/
5649
{
5650
    Py_ssize_t res;
5651
5652
    res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(self))*sizeof(digit);
5653
    return res;
5654
}
5655
5656
/*[clinic input]
5657
int.bit_length
5658
5659
Number of bits necessary to represent self in binary.
5660
5661
>>> bin(37)
5662
'0b100101'
5663
>>> (37).bit_length()
5664
6
5665
[clinic start generated code]*/
5666
5667
static PyObject *
5668
int_bit_length_impl(PyObject *self)
5669
/*[clinic end generated code: output=fc1977c9353d6a59 input=e4eb7a587e849a32]*/
5670
{
5671
    PyLongObject *result, *x, *y;
5672
    Py_ssize_t ndigits;
5673
    int msd_bits;
5674
    digit msd;
5675
5676
    assert(self != NULL);
5677
    assert(PyLong_Check(self));
5678
5679
    ndigits = Py_ABS(Py_SIZE(self));
5680
    if (ndigits == 0)
  Branch (5680:9): [True: 6.14k, False: 5.04M]
5681
        return PyLong_FromLong(0);
5682
5683
    msd = ((PyLongObject *)self)->ob_digit[ndigits-1];
5684
    msd_bits = bit_length_digit(msd);
5685
5686
    if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
  Branch (5686:9): [True: 5.04M, False: 0]
5687
        return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
5688
5689
    /* expression above may overflow; use Python integers instead */
5690
    result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5691
    if (result == NULL)
  Branch (5691:9): [True: 0, False: 0]
5692
        return NULL;
5693
    x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5694
    if (x == NULL)
  Branch (5694:9): [True: 0, False: 0]
5695
        goto error;
5696
    y = (PyLongObject *)long_mul(result, x);
5697
    Py_DECREF(x);
5698
    if (y == NULL)
  Branch (5698:9): [True: 0, False: 0]
5699
        goto error;
5700
    Py_DECREF(result);
5701
    result = y;
5702
5703
    x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5704
    if (x == NULL)
  Branch (5704:9): [True: 0, False: 0]
5705
        goto error;
5706
    y = (PyLongObject *)long_add(result, x);
5707
    Py_DECREF(x);
5708
    if (y == NULL)
  Branch (5708:9): [True: 0, False: 0]
5709
        goto error;
5710
    Py_DECREF(result);
5711
    result = y;
5712
5713
    return (PyObject *)result;
5714
5715
  error:
5716
    Py_DECREF(result);
5717
    return NULL;
5718
}
5719
5720
static int
5721
popcount_digit(digit d)
5722
{
5723
    // digit can be larger than uint32_t, but only PyLong_SHIFT bits
5724
    // of it will be ever used.
5725
    static_assert(PyLong_SHIFT <= 32, "digit is larger than uint32_t");
5726
    return _Py_popcount32((uint32_t)d);
5727
}
5728
5729
/*[clinic input]
5730
int.bit_count
5731
5732
Number of ones in the binary representation of the absolute value of self.
5733
5734
Also known as the population count.
5735
5736
>>> bin(13)
5737
'0b1101'
5738
>>> (13).bit_count()
5739
3
5740
[clinic start generated code]*/
5741
5742
static PyObject *
5743
int_bit_count_impl(PyObject *self)
5744
/*[clinic end generated code: output=2e571970daf1e5c3 input=7e0adef8e8ccdf2e]*/
5745
{
5746
    assert(self != NULL);
5747
    assert(PyLong_Check(self));
5748
5749
    PyLongObject *z = (PyLongObject *)self;
5750
    Py_ssize_t ndigits = Py_ABS(Py_SIZE(z));
5751
    Py_ssize_t bit_count = 0;
5752
5753
    /* Each digit has up to PyLong_SHIFT ones, so the accumulated bit count
5754
       from the first PY_SSIZE_T_MAX/PyLong_SHIFT digits can't overflow a
5755
       Py_ssize_t. */
5756
    Py_ssize_t ndigits_fast = Py_MIN(ndigits, PY_SSIZE_T_MAX/PyLong_SHIFT);
5757
    for (Py_ssize_t i = 0; i < ndigits_fast; 
i++176k
) {
  Branch (5757:28): [True: 176k, False: 2.05k]
5758
        bit_count += popcount_digit(z->ob_digit[i]);
5759
    }
5760
5761
    PyObject *result = PyLong_FromSsize_t(bit_count);
5762
    if (result == NULL) {
  Branch (5762:9): [True: 0, False: 2.05k]
5763
        return NULL;
5764
    }
5765
5766
    /* Use Python integers if bit_count would overflow. */
5767
    for (Py_ssize_t i = ndigits_fast; i < ndigits; 
i++0
) {
  Branch (5767:39): [True: 0, False: 2.05k]
5768
        PyObject *x = PyLong_FromLong(popcount_digit(z->ob_digit[i]));
5769
        if (x == NULL) {
  Branch (5769:13): [True: 0, False: 0]
5770
            goto error;
5771
        }
5772
        PyObject *y = long_add((PyLongObject *)result, (PyLongObject *)x);
5773
        Py_DECREF(x);
5774
        if (y == NULL) {
  Branch (5774:13): [True: 0, False: 0]
5775
            goto error;
5776
        }
5777
        Py_DECREF(result);
5778
        result = y;
5779
    }
5780
5781
    return result;
5782
5783
  error:
5784
    Py_DECREF(result);
5785
    return NULL;
5786
}
5787
5788
/*[clinic input]
5789
int.as_integer_ratio
5790
5791
Return integer ratio.
5792
5793
Return a pair of integers, whose ratio is exactly equal to the original int
5794
and with a positive denominator.
5795
5796
>>> (10).as_integer_ratio()
5797
(10, 1)
5798
>>> (-10).as_integer_ratio()
5799
(-10, 1)
5800
>>> (0).as_integer_ratio()
5801
(0, 1)
5802
[clinic start generated code]*/
5803
5804
static PyObject *
5805
int_as_integer_ratio_impl(PyObject *self)
5806
/*[clinic end generated code: output=e60803ae1cc8621a input=55ce3058e15de393]*/
5807
{
5808
    PyObject *ratio_tuple;
5809
    PyObject *numerator = long_long(self);
5810
    if (numerator == NULL) {
  Branch (5810:9): [True: 0, False: 79.9k]
5811
        return NULL;
5812
    }
5813
    ratio_tuple = PyTuple_Pack(2, numerator, _PyLong_GetOne());
5814
    Py_DECREF(numerator);
5815
    return ratio_tuple;
5816
}
5817
5818
/*[clinic input]
5819
int.to_bytes
5820
5821
    length: Py_ssize_t = 1
5822
        Length of bytes object to use.  An OverflowError is raised if the
5823
        integer is not representable with the given number of bytes.  Default
5824
        is length 1.
5825
    byteorder: unicode(c_default="NULL") = "big"
5826
        The byte order used to represent the integer.  If byteorder is 'big',
5827
        the most significant byte is at the beginning of the byte array.  If
5828
        byteorder is 'little', the most significant byte is at the end of the
5829
        byte array.  To request the native byte order of the host system, use
5830
        `sys.byteorder' as the byte order value.  Default is to use 'big'.
5831
    *
5832
    signed as is_signed: bool = False
5833
        Determines whether two's complement is used to represent the integer.
5834
        If signed is False and a negative integer is given, an OverflowError
5835
        is raised.
5836
5837
Return an array of bytes representing an integer.
5838
[clinic start generated code]*/
5839
5840
static PyObject *
5841
int_to_bytes_impl(PyObject *self, Py_ssize_t length, PyObject *byteorder,
5842
                  int is_signed)
5843
/*[clinic end generated code: output=89c801df114050a3 input=d42ecfb545039d71]*/
5844
{
5845
    int little_endian;
5846
    PyObject *bytes;
5847
5848
    if (byteorder == NULL)
  Branch (5848:9): [True: 967, False: 207k]
5849
        little_endian = 0;
5850
    else if (_PyUnicode_Equal(byteorder, &_Py_ID(little)))
  Branch (5850:14): [True: 6.08k, False: 201k]
5851
        little_endian = 1;
5852
    else if (_PyUnicode_Equal(byteorder, &_Py_ID(big)))
  Branch (5852:14): [True: 201k, False: 0]
5853
        little_endian = 0;
5854
    else {
5855
        PyErr_SetString(PyExc_ValueError,
5856
            "byteorder must be either 'little' or 'big'");
5857
        return NULL;
5858
    }
5859
5860
    if (length < 0) {
  Branch (5860:9): [True: 0, False: 208k]
5861
        PyErr_SetString(PyExc_ValueError,
5862
                        "length argument must be non-negative");
5863
        return NULL;
5864
    }
5865
5866
    bytes = PyBytes_FromStringAndSize(NULL, length);
5867
    if (bytes == NULL)
  Branch (5867:9): [True: 0, False: 208k]
5868
        return NULL;
5869
5870
    if (_PyLong_AsByteArray((PyLongObject *)self,
  Branch (5870:9): [True: 11, False: 208k]
5871
                            (unsigned char *)PyBytes_AS_STRING(bytes),
5872
                            length, little_endian, is_signed) < 0) {
5873
        Py_DECREF(bytes);
5874
        return NULL;
5875
    }
5876
5877
    return bytes;
5878
}
5879
5880
/*[clinic input]
5881
@classmethod
5882
int.from_bytes
5883
5884
    bytes as bytes_obj: object
5885
        Holds the array of bytes to convert.  The argument must either
5886
        support the buffer protocol or be an iterable object producing bytes.
5887
        Bytes and bytearray are examples of built-in objects that support the
5888
        buffer protocol.
5889
    byteorder: unicode(c_default="NULL") = "big"
5890
        The byte order used to represent the integer.  If byteorder is 'big',
5891
        the most significant byte is at the beginning of the byte array.  If
5892
        byteorder is 'little', the most significant byte is at the end of the
5893
        byte array.  To request the native byte order of the host system, use
5894
        `sys.byteorder' as the byte order value.  Default is to use 'big'.
5895
    *
5896
    signed as is_signed: bool = False
5897
        Indicates whether two's complement is used to represent the integer.
5898
5899
Return the integer represented by the given array of bytes.
5900
[clinic start generated code]*/
5901
5902
static PyObject *
5903
int_from_bytes_impl(PyTypeObject *type, PyObject *bytes_obj,
5904
                    PyObject *byteorder, int is_signed)
5905
/*[clinic end generated code: output=efc5d68e31f9314f input=33326dccdd655553]*/
5906
{
5907
    int little_endian;
5908
    PyObject *long_obj, *bytes;
5909
5910
    if (byteorder == NULL)
  Branch (5910:9): [True: 165k, False: 23.3k]
5911
        little_endian = 0;
5912
    else if (_PyUnicode_Equal(byteorder, &_Py_ID(little)))
  Branch (5912:14): [True: 21.7k, False: 1.57k]
5913
        little_endian = 1;
5914
    else if (_PyUnicode_Equal(byteorder, &_Py_ID(big)))
  Branch (5914:14): [True: 1.57k, False: 2]
5915
        little_endian = 0;
5916
    else {
5917
        PyErr_SetString(PyExc_ValueError,
5918
            "byteorder must be either 'little' or 'big'");
5919
        return NULL;
5920
    }
5921
5922
    bytes = PyObject_Bytes(bytes_obj);
5923
    if (bytes == NULL)
  Branch (5923:9): [True: 71, False: 188k]
5924
        return NULL;
5925
5926
    long_obj = _PyLong_FromByteArray(
5927
        (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
5928
        little_endian, is_signed);
5929
    Py_DECREF(bytes);
5930
5931
    if (long_obj != NULL && type != &PyLong_Type) {
  Branch (5931:9): [True: 188k, False: 0]
  Branch (5931:29): [True: 14, False: 188k]
5932
        Py_SETREF(long_obj, PyObject_CallOneArg((PyObject *)type, long_obj));
5933
    }
5934
5935
    return long_obj;
5936
}
5937
5938
static PyObject *
5939
long_long_meth(PyObject *self, PyObject *Py_UNUSED(ignored))
5940
{
5941
    return long_long(self);
5942
}
5943
5944
static PyMethodDef long_methods[] = {
5945
    {"conjugate",       long_long_meth, METH_NOARGS,
5946
     "Returns self, the complex conjugate of any int."},
5947
    INT_BIT_LENGTH_METHODDEF
5948
    INT_BIT_COUNT_METHODDEF
5949
    INT_TO_BYTES_METHODDEF
5950
    INT_FROM_BYTES_METHODDEF
5951
    INT_AS_INTEGER_RATIO_METHODDEF
5952
    {"__trunc__",       long_long_meth, METH_NOARGS,
5953
     "Truncating an Integral returns itself."},
5954
    {"__floor__",       long_long_meth, METH_NOARGS,
5955
     "Flooring an Integral returns itself."},
5956
    {"__ceil__",        long_long_meth, METH_NOARGS,
5957
     "Ceiling of an Integral returns itself."},
5958
    INT___ROUND___METHODDEF
5959
    INT___GETNEWARGS___METHODDEF
5960
    INT___FORMAT___METHODDEF
5961
    INT___SIZEOF___METHODDEF
5962
    {NULL,              NULL}           /* sentinel */
5963
};
5964
5965
static PyGetSetDef long_getset[] = {
5966
    {"real",
5967
     (getter)long_long_meth, (setter)NULL,
5968
     "the real part of a complex number",
5969
     NULL},
5970
    {"imag",
5971
     long_get0, (setter)NULL,
5972
     "the imaginary part of a complex number",
5973
     NULL},
5974
    {"numerator",
5975
     (getter)long_long_meth, (setter)NULL,
5976
     "the numerator of a rational number in lowest terms",
5977
     NULL},
5978
    {"denominator",
5979
     long_get1, (setter)NULL,
5980
     "the denominator of a rational number in lowest terms",
5981
     NULL},
5982
    {NULL}  /* Sentinel */
5983
};
5984
5985
PyDoc_STRVAR(long_doc,
5986
"int([x]) -> integer\n\
5987
int(x, base=10) -> integer\n\
5988
\n\
5989
Convert a number or string to an integer, or return 0 if no arguments\n\
5990
are given.  If x is a number, return x.__int__().  For floating point\n\
5991
numbers, this truncates towards zero.\n\
5992
\n\
5993
If x is not a number or if base is given, then x must be a string,\n\
5994
bytes, or bytearray instance representing an integer literal in the\n\
5995
given base.  The literal can be preceded by '+' or '-' and be surrounded\n\
5996
by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.\n\
5997
Base 0 means to interpret the base from the string as an integer literal.\n\
5998
>>> int('0b100', base=0)\n\
5999
4");
6000
6001
static PyNumberMethods long_as_number = {
6002
    (binaryfunc)long_add,       /*nb_add*/
6003
    (binaryfunc)long_sub,       /*nb_subtract*/
6004
    (binaryfunc)long_mul,       /*nb_multiply*/
6005
    long_mod,                   /*nb_remainder*/
6006
    long_divmod,                /*nb_divmod*/
6007
    long_pow,                   /*nb_power*/
6008
    (unaryfunc)long_neg,        /*nb_negative*/
6009
    long_long,                  /*tp_positive*/
6010
    (unaryfunc)long_abs,        /*tp_absolute*/
6011
    (inquiry)long_bool,         /*tp_bool*/
6012
    (unaryfunc)long_invert,     /*nb_invert*/
6013
    long_lshift,                /*nb_lshift*/
6014
    long_rshift,                /*nb_rshift*/
6015
    long_and,                   /*nb_and*/
6016
    long_xor,                   /*nb_xor*/
6017
    long_or,                    /*nb_or*/
6018
    long_long,                  /*nb_int*/
6019
    0,                          /*nb_reserved*/
6020
    long_float,                 /*nb_float*/
6021
    0,                          /* nb_inplace_add */
6022
    0,                          /* nb_inplace_subtract */
6023
    0,                          /* nb_inplace_multiply */
6024
    0,                          /* nb_inplace_remainder */
6025
    0,                          /* nb_inplace_power */
6026
    0,                          /* nb_inplace_lshift */
6027
    0,                          /* nb_inplace_rshift */
6028
    0,                          /* nb_inplace_and */
6029
    0,                          /* nb_inplace_xor */
6030
    0,                          /* nb_inplace_or */
6031
    long_div,                   /* nb_floor_divide */
6032
    long_true_divide,           /* nb_true_divide */
6033
    0,                          /* nb_inplace_floor_divide */
6034
    0,                          /* nb_inplace_true_divide */
6035
    long_long,                  /* nb_index */
6036
};
6037
6038
PyTypeObject PyLong_Type = {
6039
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
6040
    "int",                                      /* tp_name */
6041
    offsetof(PyLongObject, ob_digit),           /* tp_basicsize */
6042
    sizeof(digit),                              /* tp_itemsize */
6043
    0,                                          /* tp_dealloc */
6044
    0,                                          /* tp_vectorcall_offset */
6045
    0,                                          /* tp_getattr */
6046
    0,                                          /* tp_setattr */
6047
    0,                                          /* tp_as_async */
6048
    long_to_decimal_string,                     /* tp_repr */
6049
    &long_as_number,                            /* tp_as_number */
6050
    0,                                          /* tp_as_sequence */
6051
    0,                                          /* tp_as_mapping */
6052
    (hashfunc)long_hash,                        /* tp_hash */
6053
    0,                                          /* tp_call */
6054
    0,                                          /* tp_str */
6055
    PyObject_GenericGetAttr,                    /* tp_getattro */
6056
    0,                                          /* tp_setattro */
6057
    0,                                          /* tp_as_buffer */
6058
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
6059
        Py_TPFLAGS_LONG_SUBCLASS |
6060
        _Py_TPFLAGS_MATCH_SELF,               /* tp_flags */
6061
    long_doc,                                   /* tp_doc */
6062
    0,                                          /* tp_traverse */
6063
    0,                                          /* tp_clear */
6064
    long_richcompare,                           /* tp_richcompare */
6065
    0,                                          /* tp_weaklistoffset */
6066
    0,                                          /* tp_iter */
6067
    0,                                          /* tp_iternext */
6068
    long_methods,                               /* tp_methods */
6069
    0,                                          /* tp_members */
6070
    long_getset,                                /* tp_getset */
6071
    0,                                          /* tp_base */
6072
    0,                                          /* tp_dict */
6073
    0,                                          /* tp_descr_get */
6074
    0,                                          /* tp_descr_set */
6075
    0,                                          /* tp_dictoffset */
6076
    0,                                          /* tp_init */
6077
    0,                                          /* tp_alloc */
6078
    long_new,                                   /* tp_new */
6079
    PyObject_Free,                              /* tp_free */
6080
};
6081
6082
static PyTypeObject Int_InfoType;
6083
6084
PyDoc_STRVAR(int_info__doc__,
6085
"sys.int_info\n\
6086
\n\
6087
A named tuple that holds information about Python's\n\
6088
internal representation of integers.  The attributes are read only.");
6089
6090
static PyStructSequence_Field int_info_fields[] = {
6091
    {"bits_per_digit", "size of a digit in bits"},
6092
    {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
6093
    {NULL, NULL}
6094
};
6095
6096
static PyStructSequence_Desc int_info_desc = {
6097
    "sys.int_info",   /* name */
6098
    int_info__doc__,  /* doc */
6099
    int_info_fields,  /* fields */
6100
    2                 /* number of fields */
6101
};
6102
6103
PyObject *
6104
PyLong_GetInfo(void)
6105
{
6106
    PyObject* int_info;
6107
    int field = 0;
6108
    int_info = PyStructSequence_New(&Int_InfoType);
6109
    if (int_info == NULL)
  Branch (6109:9): [True: 0, False: 278]
6110
        return NULL;
6111
    PyStructSequence_SET_ITEM(int_info, field++,
6112
                              PyLong_FromLong(PyLong_SHIFT));
6113
    PyStructSequence_SET_ITEM(int_info, field++,
6114
                              PyLong_FromLong(sizeof(digit)));
6115
    if (PyErr_Occurred()) {
  Branch (6115:9): [True: 0, False: 278]
6116
        Py_CLEAR(int_info);
6117
        return NULL;
6118
    }
6119
    return int_info;
6120
}
6121
6122
6123
/* runtime lifecycle */
6124
6125
PyStatus
6126
_PyLong_InitTypes(PyInterpreterState *interp)
6127
{
6128
    if (!_Py_IsMainInterpreter(interp)) {
  Branch (6128:9): [True: 171, False: 107]
6129
        return _PyStatus_OK();
6130
    }
6131
6132
    if (PyType_Ready(&PyLong_Type) < 0) {
  Branch (6132:9): [True: 0, False: 107]
6133
        return _PyStatus_ERR("Can't initialize int type");
6134
    }
6135
6136
    /* initialize int_info */
6137
    if (Int_InfoType.tp_name == NULL) {
  Branch (6137:9): [True: 107, False: 0]
6138
        if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0) {
  Branch (6138:13): [True: 0, False: 107]
6139
            return _PyStatus_ERR("can't init int info type");
6140
        }
6141
    }
6142
6143
    return _PyStatus_OK();
6144
}
6145
6146
6147
void
6148
_PyLong_FiniTypes(PyInterpreterState *interp)
6149
{
6150
    if (!_Py_IsMainInterpreter(interp)) {
  Branch (6150:9): [True: 169, False: 103]
6151
        return;
6152
    }
6153
6154
    _PyStructSequence_FiniType(&Int_InfoType);
6155
}