Coverage Report

Created: 2025-09-05 07:10

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