Coverage Report

Created: 2025-07-11 06:59

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