Coverage Report

Created: 2026-12-01 06:09

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