~ubuntu-branches/ubuntu/maverick/python3.1/maverick

« back to all changes in this revision

Viewing changes to Objects/longobject.c

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2009-03-23 00:01:27 UTC
  • Revision ID: james.westby@ubuntu.com-20090323000127-5fstfxju4ufrhthq
Tags: upstream-3.1~a1+20090322
ImportĀ upstreamĀ versionĀ 3.1~a1+20090322

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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
#include "structseq.h"
 
8
 
 
9
#include <ctype.h>
 
10
#include <stddef.h>
 
11
 
 
12
#ifndef NSMALLPOSINTS
 
13
#define NSMALLPOSINTS           257
 
14
#endif
 
15
#ifndef NSMALLNEGINTS
 
16
#define NSMALLNEGINTS           5
 
17
#endif
 
18
 
 
19
/* convert a PyLong of size 1, 0 or -1 to an sdigit */
 
20
#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] :   \
 
21
                         (Py_SIZE(x) == 0 ? (sdigit)0 :                 \
 
22
                          (sdigit)(x)->ob_digit[0]))
 
23
#define ABS(x) ((x) < 0 ? -(x) : (x))
 
24
 
 
25
#if NSMALLNEGINTS + NSMALLPOSINTS > 0
 
26
/* Small integers are preallocated in this array so that they
 
27
   can be shared.
 
28
   The integers that are preallocated are those in the range
 
29
   -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
 
30
*/
 
31
static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
 
32
#ifdef COUNT_ALLOCS
 
33
int quick_int_allocs, quick_neg_int_allocs;
 
34
#endif
 
35
 
 
36
static PyObject *
 
37
get_small_int(sdigit ival)
 
38
{
 
39
        PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
 
40
        Py_INCREF(v);
 
41
#ifdef COUNT_ALLOCS
 
42
        if (ival >= 0)
 
43
                quick_int_allocs++;
 
44
        else
 
45
                quick_neg_int_allocs++;
 
46
#endif
 
47
        return v;
 
48
}
 
49
#define CHECK_SMALL_INT(ival) \
 
50
        do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
 
51
                return get_small_int((sdigit)ival); \
 
52
        } while(0)
 
53
 
 
54
static PyLongObject * 
 
55
maybe_small_long(PyLongObject *v)
 
56
{
 
57
        if (v && ABS(Py_SIZE(v)) <= 1) {
 
58
                sdigit ival = MEDIUM_VALUE(v);
 
59
                if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
 
60
                        Py_DECREF(v);
 
61
                        return (PyLongObject *)get_small_int(ival);
 
62
                }
 
63
        }
 
64
        return v;
 
65
}
 
66
#else
 
67
#define CHECK_SMALL_INT(ival)
 
68
#define maybe_small_long(val) (val)
 
69
#endif
 
70
 
 
71
/* If a freshly-allocated long is already shared, it must
 
72
   be a small integer, so negating it must go to PyLong_FromLong */
 
73
#define NEGATE(x) \
 
74
        do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x);  \
 
75
           else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x));  \
 
76
                   Py_DECREF(x); (x) = (PyLongObject*)tmp; }       \
 
77
        while(0)
 
78
/* For long multiplication, use the O(N**2) school algorithm unless
 
79
 * both operands contain more than KARATSUBA_CUTOFF digits (this
 
80
 * being an internal Python long digit, in base BASE).
 
81
 */
 
82
#define KARATSUBA_CUTOFF 70
 
83
#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
 
84
 
 
85
/* For exponentiation, use the binary left-to-right algorithm
 
86
 * unless the exponent contains more than FIVEARY_CUTOFF digits.
 
87
 * In that case, do 5 bits at a time.  The potential drawback is that
 
88
 * a table of 2**5 intermediate results is computed.
 
89
 */
 
90
#define FIVEARY_CUTOFF 8
 
91
 
 
92
#undef MIN
 
93
#undef MAX
 
94
#define MAX(x, y) ((x) < (y) ? (y) : (x))
 
95
#define MIN(x, y) ((x) > (y) ? (y) : (x))
 
96
 
 
97
#define SIGCHECK(PyTryBlock) \
 
98
        if (--_Py_Ticker < 0) { \
 
99
                _Py_Ticker = _Py_CheckInterval; \
 
100
                if (PyErr_CheckSignals()) PyTryBlock \
 
101
        }
 
102
 
 
103
/* Normalize (remove leading zeros from) a long int object.
 
104
   Doesn't attempt to free the storage--in most cases, due to the nature
 
105
   of the algorithms used, this could save at most be one word anyway. */
 
106
 
 
107
static PyLongObject *
 
108
long_normalize(register PyLongObject *v)
 
109
{
 
110
        Py_ssize_t j = ABS(Py_SIZE(v));
 
111
        Py_ssize_t i = j;
 
112
 
 
113
        while (i > 0 && v->ob_digit[i-1] == 0)
 
114
                --i;
 
115
        if (i != j)
 
116
                Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
 
117
        return v;
 
118
}
 
119
 
 
120
/* Allocate a new long int object with size digits.
 
121
   Return NULL and set exception if we run out of memory. */
 
122
 
 
123
#define MAX_LONG_DIGITS \
 
124
        ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
 
125
 
 
126
PyLongObject *
 
127
_PyLong_New(Py_ssize_t size)
 
128
{
 
129
        PyLongObject *result;
 
130
        /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
 
131
           sizeof(digit)*size.  Previous incarnations of this code used
 
132
           sizeof(PyVarObject) instead of the offsetof, but this risks being
 
133
           incorrect in the presence of padding between the PyVarObject header
 
134
           and the digits. */
 
135
        if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
 
136
                PyErr_SetString(PyExc_OverflowError,
 
137
                                "too many digits in integer");
 
138
                return NULL;
 
139
        }
 
140
        result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
 
141
                                 size*sizeof(digit));
 
142
        if (!result) {
 
143
                PyErr_NoMemory();
 
144
                return NULL;
 
145
        }
 
146
        return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
 
147
}
 
148
 
 
149
PyObject *
 
150
_PyLong_Copy(PyLongObject *src)
 
151
{
 
152
        PyLongObject *result;
 
153
        Py_ssize_t i;
 
154
 
 
155
        assert(src != NULL);
 
156
        i = Py_SIZE(src);
 
157
        if (i < 0)
 
158
                i = -(i);
 
159
        if (i < 2) {
 
160
                sdigit ival = src->ob_digit[0];
 
161
                if (Py_SIZE(src) < 0)
 
162
                        ival = -ival;
 
163
                CHECK_SMALL_INT(ival);
 
164
        }
 
165
        result = _PyLong_New(i);
 
166
        if (result != NULL) {
 
167
                Py_SIZE(result) = Py_SIZE(src);
 
168
                while (--i >= 0)
 
169
                        result->ob_digit[i] = src->ob_digit[i];
 
170
        }
 
171
        return (PyObject *)result;
 
172
}
 
173
 
 
174
/* Create a new long int object from a C long int */
 
175
 
 
176
PyObject *
 
177
PyLong_FromLong(long ival)
 
178
{
 
179
        PyLongObject *v;
 
180
        unsigned long abs_ival;
 
181
        unsigned long t;  /* unsigned so >> doesn't propagate sign bit */
 
182
        int ndigits = 0;
 
183
        int sign = 1;
 
184
 
 
185
        CHECK_SMALL_INT(ival);
 
186
 
 
187
        if (ival < 0) {
 
188
                /* negate: can't write this as abs_ival = -ival since that
 
189
                   invokes undefined behaviour when ival is LONG_MIN */
 
190
                abs_ival = 0U-(unsigned long)ival;
 
191
                sign = -1;
 
192
        }
 
193
        else {
 
194
                abs_ival = (unsigned long)ival;
 
195
        }
 
196
 
 
197
        /* Fast path for single-digit ints */
 
198
        if (!(abs_ival >> PyLong_SHIFT)) {
 
199
                v = _PyLong_New(1);
 
200
                if (v) {
 
201
                        Py_SIZE(v) = sign;
 
202
                        v->ob_digit[0] = Py_SAFE_DOWNCAST(
 
203
                                abs_ival, unsigned long, digit);
 
204
                }
 
205
                return (PyObject*)v;
 
206
        }
 
207
 
 
208
#if PyLONG_SHIFT==15
 
209
        /* 2 digits */
 
210
        if (!(abs_ival >> 2*PyLong_SHIFT)) {
 
211
                v = _PyLong_New(2);
 
212
                if (v) {
 
213
                        Py_SIZE(v) = 2*sign;
 
214
                        v->ob_digit[0] = Py_SAFE_DOWNCAST(
 
215
                                abs_ival & PyLong_MASK, unsigned long, digit);
 
216
                        v->ob_digit[1] = Py_SAFE_DOWNCAST(
 
217
                              abs_ival >> PyLong_SHIFT, unsigned long, digit);
 
218
                }
 
219
                return (PyObject*)v;
 
220
        }
 
221
#endif
 
222
 
 
223
        /* Larger numbers: loop to determine number of digits */
 
224
        t = abs_ival;
 
225
        while (t) {
 
226
                ++ndigits;
 
227
                t >>= PyLong_SHIFT;
 
228
        }
 
229
        v = _PyLong_New(ndigits);
 
230
        if (v != NULL) {
 
231
                digit *p = v->ob_digit;
 
232
                Py_SIZE(v) = ndigits*sign;
 
233
                t = abs_ival;
 
234
                while (t) {
 
235
                        *p++ = Py_SAFE_DOWNCAST(
 
236
                                t & PyLong_MASK, unsigned long, digit);
 
237
                        t >>= PyLong_SHIFT;
 
238
                }
 
239
        }
 
240
        return (PyObject *)v;
 
241
}
 
242
 
 
243
/* Create a new long int object from a C unsigned long int */
 
244
 
 
245
PyObject *
 
246
PyLong_FromUnsignedLong(unsigned long ival)
 
247
{
 
248
        PyLongObject *v;
 
249
        unsigned long t;
 
250
        int ndigits = 0;
 
251
 
 
252
        if (ival < PyLong_BASE)
 
253
                return PyLong_FromLong(ival);
 
254
        /* Count the number of Python digits. */
 
255
        t = (unsigned long)ival;
 
256
        while (t) {
 
257
                ++ndigits;
 
258
                t >>= PyLong_SHIFT;
 
259
        }
 
260
        v = _PyLong_New(ndigits);
 
261
        if (v != NULL) {
 
262
                digit *p = v->ob_digit;
 
263
                Py_SIZE(v) = ndigits;
 
264
                while (ival) {
 
265
                        *p++ = (digit)(ival & PyLong_MASK);
 
266
                        ival >>= PyLong_SHIFT;
 
267
                }
 
268
        }
 
269
        return (PyObject *)v;
 
270
}
 
271
 
 
272
/* Create a new long int object from a C double */
 
273
 
 
274
PyObject *
 
275
PyLong_FromDouble(double dval)
 
276
{
 
277
        PyLongObject *v;
 
278
        double frac;
 
279
        int i, ndig, expo, neg;
 
280
        neg = 0;
 
281
        if (Py_IS_INFINITY(dval)) {
 
282
                PyErr_SetString(PyExc_OverflowError,
 
283
                        "cannot convert float infinity to integer");
 
284
                return NULL;
 
285
        }
 
286
        if (Py_IS_NAN(dval)) {
 
287
                PyErr_SetString(PyExc_ValueError,
 
288
                        "cannot convert float NaN to integer");
 
289
                return NULL;
 
290
        }
 
291
        if (dval < 0.0) {
 
292
                neg = 1;
 
293
                dval = -dval;
 
294
        }
 
295
        frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
 
296
        if (expo <= 0)
 
297
                return PyLong_FromLong(0L);
 
298
        ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
 
299
        v = _PyLong_New(ndig);
 
300
        if (v == NULL)
 
301
                return NULL;
 
302
        frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
 
303
        for (i = ndig; --i >= 0; ) {
 
304
                digit bits = (digit)frac;
 
305
                v->ob_digit[i] = bits;
 
306
                frac = frac - (double)bits;
 
307
                frac = ldexp(frac, PyLong_SHIFT);
 
308
        }
 
309
        if (neg)
 
310
                Py_SIZE(v) = -(Py_SIZE(v));
 
311
        return (PyObject *)v;
 
312
}
 
313
 
 
314
/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
 
315
 * anything about what happens when a signed integer operation overflows,
 
316
 * and some compilers think they're doing you a favor by being "clever"
 
317
 * then.  The bit pattern for the largest postive signed long is
 
318
 * (unsigned long)LONG_MAX, and for the smallest negative signed long
 
319
 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
 
320
 * However, some other compilers warn about applying unary minus to an
 
321
 * unsigned operand.  Hence the weird "0-".
 
322
 */
 
323
#define PY_ABS_LONG_MIN         (0-(unsigned long)LONG_MIN)
 
324
#define PY_ABS_SSIZE_T_MIN      (0-(size_t)PY_SSIZE_T_MIN)
 
325
 
 
326
/* Get a C long int from a long int object.
 
327
   Returns -1 and sets an error condition if overflow occurs. */
 
328
 
 
329
long
 
330
PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
 
331
{
 
332
        /* This version by Tim Peters */
 
333
        register PyLongObject *v;
 
334
        unsigned long x, prev;
 
335
        long res;
 
336
        Py_ssize_t i;
 
337
        int sign;
 
338
        int do_decref = 0; /* if nb_int was called */
 
339
 
 
340
        *overflow = 0;
 
341
        if (vv == NULL) {
 
342
                PyErr_BadInternalCall();
 
343
                return -1;
 
344
        }
 
345
 
 
346
        if (!PyLong_Check(vv)) {
 
347
                PyNumberMethods *nb;
 
348
                if ((nb = vv->ob_type->tp_as_number) == NULL ||
 
349
                    nb->nb_int == NULL) {
 
350
                        PyErr_SetString(PyExc_TypeError, "an integer is required");
 
351
                        return -1;
 
352
                }
 
353
                vv = (*nb->nb_int) (vv);
 
354
                if (vv == NULL)
 
355
                        return -1;
 
356
                do_decref = 1;
 
357
                if (!PyLong_Check(vv)) {
 
358
                        Py_DECREF(vv);
 
359
                        PyErr_SetString(PyExc_TypeError,
 
360
                                        "nb_int should return int object");
 
361
                        return -1;
 
362
                }
 
363
        }
 
364
 
 
365
        res = -1;
 
366
        v = (PyLongObject *)vv;
 
367
        i = Py_SIZE(v);
 
368
 
 
369
        switch (i) {
 
370
        case -1:
 
371
                res = -(sdigit)v->ob_digit[0];
 
372
                break;
 
373
        case 0:
 
374
                res = 0;
 
375
                break;
 
376
        case 1:
 
377
                res = v->ob_digit[0];
 
378
                break;
 
379
        default:
 
380
                sign = 1;
 
381
                x = 0;
 
382
                if (i < 0) {
 
383
                        sign = -1;
 
384
                        i = -(i);
 
385
                }
 
386
                while (--i >= 0) {
 
387
                        prev = x;
 
388
                        x = (x << PyLong_SHIFT) + v->ob_digit[i];
 
389
                        if ((x >> PyLong_SHIFT) != prev) {
 
390
                                *overflow = Py_SIZE(v) > 0 ? 1 : -1;
 
391
                                goto exit;
 
392
                        }
 
393
                }
 
394
                /* Haven't lost any bits, but casting to long requires extra care
 
395
                 * (see comment above).
 
396
                 */
 
397
                if (x <= (unsigned long)LONG_MAX) {
 
398
                        res = (long)x * sign;
 
399
                }
 
400
                else if (sign < 0 && x == PY_ABS_LONG_MIN) {
 
401
                        res = LONG_MIN;
 
402
                }
 
403
                else {
 
404
                        *overflow = Py_SIZE(v) > 0 ? 1 : -1;
 
405
                        /* res is already set to -1 */
 
406
                }       
 
407
        }
 
408
 exit:
 
409
        if (do_decref) {
 
410
                Py_DECREF(vv);
 
411
        }
 
412
        return res;
 
413
}
 
414
 
 
415
long 
 
416
PyLong_AsLong(PyObject *obj)
 
417
{
 
418
        int overflow;
 
419
        long result = PyLong_AsLongAndOverflow(obj, &overflow);
 
420
        if (overflow) {
 
421
                /* XXX: could be cute and give a different 
 
422
                   message for overflow == -1 */
 
423
                PyErr_SetString(PyExc_OverflowError,
 
424
                                "Python int too large to convert to C long");
 
425
        }
 
426
        return result;
 
427
}
 
428
 
 
429
/* Get a Py_ssize_t from a long int object.
 
430
   Returns -1 and sets an error condition if overflow occurs. */
 
431
 
 
432
Py_ssize_t
 
433
PyLong_AsSsize_t(PyObject *vv) {
 
434
        register PyLongObject *v;
 
435
        size_t x, prev;
 
436
        Py_ssize_t i;
 
437
        int sign;
 
438
 
 
439
        if (vv == NULL || !PyLong_Check(vv)) {
 
440
                PyErr_BadInternalCall();
 
441
                return -1;
 
442
        }
 
443
        v = (PyLongObject *)vv;
 
444
        i = Py_SIZE(v);
 
445
        switch (i) {
 
446
        case -1: return -(sdigit)v->ob_digit[0];
 
447
        case 0: return 0;
 
448
        case 1: return v->ob_digit[0];
 
449
        }
 
450
        sign = 1;
 
451
        x = 0;
 
452
        if (i < 0) {
 
453
                sign = -1;
 
454
                i = -(i);
 
455
        }
 
456
        while (--i >= 0) {
 
457
                prev = x;
 
458
                x = (x << PyLong_SHIFT) + v->ob_digit[i];
 
459
                if ((x >> PyLong_SHIFT) != prev)
 
460
                        goto overflow;
 
461
        }
 
462
        /* Haven't lost any bits, but casting to a signed type requires
 
463
         * extra care (see comment above).
 
464
         */
 
465
        if (x <= (size_t)PY_SSIZE_T_MAX) {
 
466
                return (Py_ssize_t)x * sign;
 
467
        }
 
468
        else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
 
469
                return PY_SSIZE_T_MIN;
 
470
        }
 
471
        /* else overflow */
 
472
 
 
473
 overflow:
 
474
        PyErr_SetString(PyExc_OverflowError,
 
475
                        "Python int too large to convert to C ssize_t");
 
476
        return -1;
 
477
}
 
478
 
 
479
/* Get a C unsigned long int from a long int object.
 
480
   Returns -1 and sets an error condition if overflow occurs. */
 
481
 
 
482
unsigned long
 
483
PyLong_AsUnsignedLong(PyObject *vv)
 
484
{
 
485
        register PyLongObject *v;
 
486
        unsigned long x, prev;
 
487
        Py_ssize_t i;
 
488
 
 
489
        if (vv == NULL || !PyLong_Check(vv)) {
 
490
                PyErr_BadInternalCall();
 
491
                return (unsigned long) -1;
 
492
        }
 
493
        v = (PyLongObject *)vv;
 
494
        i = Py_SIZE(v);
 
495
        x = 0;
 
496
        if (i < 0) {
 
497
                PyErr_SetString(PyExc_OverflowError,
 
498
                           "can't convert negative value to unsigned int");
 
499
                return (unsigned long) -1;
 
500
        }
 
501
        switch (i) {
 
502
        case 0: return 0;
 
503
        case 1: return v->ob_digit[0];
 
504
        }
 
505
        while (--i >= 0) {
 
506
                prev = x;
 
507
                x = (x << PyLong_SHIFT) + v->ob_digit[i];
 
508
                if ((x >> PyLong_SHIFT) != prev) {
 
509
                        PyErr_SetString(PyExc_OverflowError,
 
510
                         "python int too large to convert to C unsigned long");
 
511
                        return (unsigned long) -1;
 
512
                }
 
513
        }
 
514
        return x;
 
515
}
 
516
 
 
517
/* Get a C unsigned long int from a long int object.
 
518
   Returns -1 and sets an error condition if overflow occurs. */
 
519
 
 
520
size_t
 
521
PyLong_AsSize_t(PyObject *vv)
 
522
{
 
523
        register PyLongObject *v;
 
524
        size_t x, prev;
 
525
        Py_ssize_t i;
 
526
 
 
527
        if (vv == NULL || !PyLong_Check(vv)) {
 
528
                PyErr_BadInternalCall();
 
529
                return (unsigned long) -1;
 
530
        }
 
531
        v = (PyLongObject *)vv;
 
532
        i = Py_SIZE(v);
 
533
        x = 0;
 
534
        if (i < 0) {
 
535
                PyErr_SetString(PyExc_OverflowError,
 
536
                           "can't convert negative value to size_t");
 
537
                return (size_t) -1;
 
538
        }
 
539
        switch (i) {
 
540
        case 0: return 0;
 
541
        case 1: return v->ob_digit[0];
 
542
        }
 
543
        while (--i >= 0) {
 
544
                prev = x;
 
545
                x = (x << PyLong_SHIFT) + v->ob_digit[i];
 
546
                if ((x >> PyLong_SHIFT) != prev) {
 
547
                        PyErr_SetString(PyExc_OverflowError,
 
548
                            "Python int too large to convert to C size_t");
 
549
                        return (unsigned long) -1;
 
550
                }
 
551
        }
 
552
        return x;
 
553
}
 
554
 
 
555
/* Get a C unsigned long int from a long int object, ignoring the high bits.
 
556
   Returns -1 and sets an error condition if an error occurs. */
 
557
 
 
558
static unsigned long
 
559
_PyLong_AsUnsignedLongMask(PyObject *vv)
 
560
{
 
561
        register PyLongObject *v;
 
562
        unsigned long x;
 
563
        Py_ssize_t i;
 
564
        int sign;
 
565
 
 
566
        if (vv == NULL || !PyLong_Check(vv)) {
 
567
                PyErr_BadInternalCall();
 
568
                return (unsigned long) -1;
 
569
        }
 
570
        v = (PyLongObject *)vv;
 
571
        i = Py_SIZE(v);
 
572
        switch (i) {
 
573
        case 0: return 0;
 
574
        case 1: return v->ob_digit[0];
 
575
        }
 
576
        sign = 1;
 
577
        x = 0;
 
578
        if (i < 0) {
 
579
                sign = -1;
 
580
                i = -i;
 
581
        }
 
582
        while (--i >= 0) {
 
583
                x = (x << PyLong_SHIFT) + v->ob_digit[i];
 
584
        }
 
585
        return x * sign;
 
586
}
 
587
 
 
588
unsigned long
 
589
PyLong_AsUnsignedLongMask(register PyObject *op)
 
590
{
 
591
        PyNumberMethods *nb;
 
592
        PyLongObject *lo;
 
593
        unsigned long val;
 
594
 
 
595
        if (op && PyLong_Check(op))
 
596
                return _PyLong_AsUnsignedLongMask(op);
 
597
 
 
598
        if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
 
599
            nb->nb_int == NULL) {
 
600
                PyErr_SetString(PyExc_TypeError, "an integer is required");
 
601
                return (unsigned long)-1;
 
602
        }
 
603
 
 
604
        lo = (PyLongObject*) (*nb->nb_int) (op);
 
605
        if (lo == NULL)
 
606
                return (unsigned long)-1;
 
607
        if (PyLong_Check(lo)) {
 
608
                val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
 
609
                Py_DECREF(lo);
 
610
                if (PyErr_Occurred())
 
611
                        return (unsigned long)-1;
 
612
                return val;
 
613
        }
 
614
        else
 
615
        {
 
616
                Py_DECREF(lo);
 
617
                PyErr_SetString(PyExc_TypeError,
 
618
                                "nb_int should return int object");
 
619
                return (unsigned long)-1;
 
620
        }
 
621
}
 
622
 
 
623
int
 
624
_PyLong_Sign(PyObject *vv)
 
625
{
 
626
        PyLongObject *v = (PyLongObject *)vv;
 
627
 
 
628
        assert(v != NULL);
 
629
        assert(PyLong_Check(v));
 
630
 
 
631
        return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
 
632
}
 
633
 
 
634
size_t
 
635
_PyLong_NumBits(PyObject *vv)
 
636
{
 
637
        PyLongObject *v = (PyLongObject *)vv;
 
638
        size_t result = 0;
 
639
        Py_ssize_t ndigits;
 
640
 
 
641
        assert(v != NULL);
 
642
        assert(PyLong_Check(v));
 
643
        ndigits = ABS(Py_SIZE(v));
 
644
        assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
 
645
        if (ndigits > 0) {
 
646
                digit msd = v->ob_digit[ndigits - 1];
 
647
 
 
648
                result = (ndigits - 1) * PyLong_SHIFT;
 
649
                if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
 
650
                        goto Overflow;
 
651
                do {
 
652
                        ++result;
 
653
                        if (result == 0)
 
654
                                goto Overflow;
 
655
                        msd >>= 1;
 
656
                } while (msd);
 
657
        }
 
658
        return result;
 
659
 
 
660
Overflow:
 
661
        PyErr_SetString(PyExc_OverflowError, "int has too many bits "
 
662
                        "to express in a platform size_t");
 
663
        return (size_t)-1;
 
664
}
 
665
 
 
666
PyObject *
 
667
_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
 
668
                      int little_endian, int is_signed)
 
669
{
 
670
        const unsigned char* pstartbyte;/* LSB of bytes */
 
671
        int incr;                       /* direction to move pstartbyte */
 
672
        const unsigned char* pendbyte;  /* MSB of bytes */
 
673
        size_t numsignificantbytes;     /* number of bytes that matter */
 
674
        Py_ssize_t ndigits;             /* number of Python long digits */
 
675
        PyLongObject* v;                /* result */
 
676
        Py_ssize_t idigit = 0;          /* next free index in v->ob_digit */
 
677
 
 
678
        if (n == 0)
 
679
                return PyLong_FromLong(0L);
 
680
 
 
681
        if (little_endian) {
 
682
                pstartbyte = bytes;
 
683
                pendbyte = bytes + n - 1;
 
684
                incr = 1;
 
685
        }
 
686
        else {
 
687
                pstartbyte = bytes + n - 1;
 
688
                pendbyte = bytes;
 
689
                incr = -1;
 
690
        }
 
691
 
 
692
        if (is_signed)
 
693
                is_signed = *pendbyte >= 0x80;
 
694
 
 
695
        /* Compute numsignificantbytes.  This consists of finding the most
 
696
           significant byte.  Leading 0 bytes are insignficant if the number
 
697
           is positive, and leading 0xff bytes if negative. */
 
698
        {
 
699
                size_t i;
 
700
                const unsigned char* p = pendbyte;
 
701
                const int pincr = -incr;  /* search MSB to LSB */
 
702
                const unsigned char insignficant = is_signed ? 0xff : 0x00;
 
703
 
 
704
                for (i = 0; i < n; ++i, p += pincr) {
 
705
                        if (*p != insignficant)
 
706
                                break;
 
707
                }
 
708
                numsignificantbytes = n - i;
 
709
                /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
 
710
                   actually has 2 significant bytes.  OTOH, 0xff0001 ==
 
711
                   -0x00ffff, so we wouldn't *need* to bump it there; but we
 
712
                   do for 0xffff = -0x0001.  To be safe without bothering to
 
713
                   check every case, bump it regardless. */
 
714
                if (is_signed && numsignificantbytes < n)
 
715
                        ++numsignificantbytes;
 
716
        }
 
717
 
 
718
        /* How many Python long digits do we need?  We have
 
719
           8*numsignificantbytes bits, and each Python long digit has
 
720
           PyLong_SHIFT bits, so it's the ceiling of the quotient. */
 
721
        /* catch overflow before it happens */
 
722
        if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
 
723
                PyErr_SetString(PyExc_OverflowError,
 
724
                                "byte array too long to convert to int");
 
725
                return NULL;
 
726
        }
 
727
        ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
 
728
        v = _PyLong_New(ndigits);
 
729
        if (v == NULL)
 
730
                return NULL;
 
731
 
 
732
        /* Copy the bits over.  The tricky parts are computing 2's-comp on
 
733
           the fly for signed numbers, and dealing with the mismatch between
 
734
           8-bit bytes and (probably) 15-bit Python digits.*/
 
735
        {
 
736
                size_t i;
 
737
                twodigits carry = 1;            /* for 2's-comp calculation */
 
738
                twodigits accum = 0;            /* sliding register */
 
739
                unsigned int accumbits = 0;     /* number of bits in accum */
 
740
                const unsigned char* p = pstartbyte;
 
741
 
 
742
                for (i = 0; i < numsignificantbytes; ++i, p += incr) {
 
743
                        twodigits thisbyte = *p;
 
744
                        /* Compute correction for 2's comp, if needed. */
 
745
                        if (is_signed) {
 
746
                                thisbyte = (0xff ^ thisbyte) + carry;
 
747
                                carry = thisbyte >> 8;
 
748
                                thisbyte &= 0xff;
 
749
                        }
 
750
                        /* Because we're going LSB to MSB, thisbyte is
 
751
                           more significant than what's already in accum,
 
752
                           so needs to be prepended to accum. */
 
753
                        accum |= (twodigits)thisbyte << accumbits;
 
754
                        accumbits += 8;
 
755
                        if (accumbits >= PyLong_SHIFT) {
 
756
                                /* There's enough to fill a Python digit. */
 
757
                                assert(idigit < ndigits);
 
758
                                v->ob_digit[idigit] = (digit)(accum &
 
759
                                                              PyLong_MASK);
 
760
                                ++idigit;
 
761
                                accum >>= PyLong_SHIFT;
 
762
                                accumbits -= PyLong_SHIFT;
 
763
                                assert(accumbits < PyLong_SHIFT);
 
764
                        }
 
765
                }
 
766
                assert(accumbits < PyLong_SHIFT);
 
767
                if (accumbits) {
 
768
                        assert(idigit < ndigits);
 
769
                        v->ob_digit[idigit] = (digit)accum;
 
770
                        ++idigit;
 
771
                }
 
772
        }
 
773
 
 
774
        Py_SIZE(v) = is_signed ? -idigit : idigit;
 
775
        return (PyObject *)long_normalize(v);
 
776
}
 
777
 
 
778
int
 
779
_PyLong_AsByteArray(PyLongObject* v,
 
780
                    unsigned char* bytes, size_t n,
 
781
                    int little_endian, int is_signed)
 
782
{
 
783
        Py_ssize_t i;           /* index into v->ob_digit */
 
784
        Py_ssize_t ndigits;             /* |v->ob_size| */
 
785
        twodigits accum;        /* sliding register */
 
786
        unsigned int accumbits; /* # bits in accum */
 
787
        int do_twos_comp;       /* store 2's-comp?  is_signed and v < 0 */
 
788
        digit carry;            /* for computing 2's-comp */
 
789
        size_t j;               /* # bytes filled */
 
790
        unsigned char* p;       /* pointer to next byte in bytes */
 
791
        int pincr;              /* direction to move p */
 
792
 
 
793
        assert(v != NULL && PyLong_Check(v));
 
794
 
 
795
        if (Py_SIZE(v) < 0) {
 
796
                ndigits = -(Py_SIZE(v));
 
797
                if (!is_signed) {
 
798
                        PyErr_SetString(PyExc_OverflowError,
 
799
                                "can't convert negative int to unsigned");
 
800
                        return -1;
 
801
                }
 
802
                do_twos_comp = 1;
 
803
        }
 
804
        else {
 
805
                ndigits = Py_SIZE(v);
 
806
                do_twos_comp = 0;
 
807
        }
 
808
 
 
809
        if (little_endian) {
 
810
                p = bytes;
 
811
                pincr = 1;
 
812
        }
 
813
        else {
 
814
                p = bytes + n - 1;
 
815
                pincr = -1;
 
816
        }
 
817
 
 
818
        /* Copy over all the Python digits.
 
819
           It's crucial that every Python digit except for the MSD contribute
 
820
           exactly PyLong_SHIFT bits to the total, so first assert that the long is
 
821
           normalized. */
 
822
        assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
 
823
        j = 0;
 
824
        accum = 0;
 
825
        accumbits = 0;
 
826
        carry = do_twos_comp ? 1 : 0;
 
827
        for (i = 0; i < ndigits; ++i) {
 
828
                digit thisdigit = v->ob_digit[i];
 
829
                if (do_twos_comp) {
 
830
                        thisdigit = (thisdigit ^ PyLong_MASK) + carry;
 
831
                        carry = thisdigit >> PyLong_SHIFT;
 
832
                        thisdigit &= PyLong_MASK;
 
833
                }
 
834
                /* Because we're going LSB to MSB, thisdigit is more
 
835
                   significant than what's already in accum, so needs to be
 
836
                   prepended to accum. */
 
837
                accum |= (twodigits)thisdigit << accumbits;
 
838
 
 
839
                /* The most-significant digit may be (probably is) at least
 
840
                   partly empty. */
 
841
                if (i == ndigits - 1) {
 
842
                        /* Count # of sign bits -- they needn't be stored,
 
843
                         * although for signed conversion we need later to
 
844
                         * make sure at least one sign bit gets stored. */
 
845
                        digit s = do_twos_comp ? thisdigit ^ PyLong_MASK :
 
846
                                                thisdigit;
 
847
                        while (s != 0) {
 
848
                                s >>= 1;
 
849
                                accumbits++;
 
850
                        }
 
851
                }
 
852
                else
 
853
                        accumbits += PyLong_SHIFT;
 
854
 
 
855
                /* Store as many bytes as possible. */
 
856
                while (accumbits >= 8) {
 
857
                        if (j >= n)
 
858
                                goto Overflow;
 
859
                        ++j;
 
860
                        *p = (unsigned char)(accum & 0xff);
 
861
                        p += pincr;
 
862
                        accumbits -= 8;
 
863
                        accum >>= 8;
 
864
                }
 
865
        }
 
866
 
 
867
        /* Store the straggler (if any). */
 
868
        assert(accumbits < 8);
 
869
        assert(carry == 0);  /* else do_twos_comp and *every* digit was 0 */
 
870
        if (accumbits > 0) {
 
871
                if (j >= n)
 
872
                        goto Overflow;
 
873
                ++j;
 
874
                if (do_twos_comp) {
 
875
                        /* Fill leading bits of the byte with sign bits
 
876
                           (appropriately pretending that the long had an
 
877
                           infinite supply of sign bits). */
 
878
                        accum |= (~(twodigits)0) << accumbits;
 
879
                }
 
880
                *p = (unsigned char)(accum & 0xff);
 
881
                p += pincr;
 
882
        }
 
883
        else if (j == n && n > 0 && is_signed) {
 
884
                /* The main loop filled the byte array exactly, so the code
 
885
                   just above didn't get to ensure there's a sign bit, and the
 
886
                   loop below wouldn't add one either.  Make sure a sign bit
 
887
                   exists. */
 
888
                unsigned char msb = *(p - pincr);
 
889
                int sign_bit_set = msb >= 0x80;
 
890
                assert(accumbits == 0);
 
891
                if (sign_bit_set == do_twos_comp)
 
892
                        return 0;
 
893
                else
 
894
                        goto Overflow;
 
895
        }
 
896
 
 
897
        /* Fill remaining bytes with copies of the sign bit. */
 
898
        {
 
899
                unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
 
900
                for ( ; j < n; ++j, p += pincr)
 
901
                        *p = signbyte;
 
902
        }
 
903
 
 
904
        return 0;
 
905
 
 
906
Overflow:
 
907
        PyErr_SetString(PyExc_OverflowError, "int too big to convert");
 
908
        return -1;
 
909
 
 
910
}
 
911
 
 
912
double
 
913
_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
 
914
{
 
915
/* NBITS_WANTED should be > the number of bits in a double's precision,
 
916
   but small enough so that 2**NBITS_WANTED is within the normal double
 
917
   range.  nbitsneeded is set to 1 less than that because the most-significant
 
918
   Python digit contains at least 1 significant bit, but we don't want to
 
919
   bother counting them (catering to the worst case cheaply).
 
920
 
 
921
   57 is one more than VAX-D double precision; I (Tim) don't know of a double
 
922
   format with more precision than that; it's 1 larger so that we add in at
 
923
   least one round bit to stand in for the ignored least-significant bits.
 
924
*/
 
925
#define NBITS_WANTED 57
 
926
        PyLongObject *v;
 
927
        double x;
 
928
        const double multiplier = (double)(1L << PyLong_SHIFT);
 
929
        Py_ssize_t i;
 
930
        int sign;
 
931
        int nbitsneeded;
 
932
 
 
933
        if (vv == NULL || !PyLong_Check(vv)) {
 
934
                PyErr_BadInternalCall();
 
935
                return -1;
 
936
        }
 
937
        v = (PyLongObject *)vv;
 
938
        i = Py_SIZE(v);
 
939
        sign = 1;
 
940
        if (i < 0) {
 
941
                sign = -1;
 
942
                i = -(i);
 
943
        }
 
944
        else if (i == 0) {
 
945
                *exponent = 0;
 
946
                return 0.0;
 
947
        }
 
948
        --i;
 
949
        x = (double)v->ob_digit[i];
 
950
        nbitsneeded = NBITS_WANTED - 1;
 
951
        /* Invariant:  i Python digits remain unaccounted for. */
 
952
        while (i > 0 && nbitsneeded > 0) {
 
953
                --i;
 
954
                x = x * multiplier + (double)v->ob_digit[i];
 
955
                nbitsneeded -= PyLong_SHIFT;
 
956
        }
 
957
        /* There are i digits we didn't shift in.  Pretending they're all
 
958
           zeroes, the true value is x * 2**(i*PyLong_SHIFT). */
 
959
        *exponent = i;
 
960
        assert(x > 0.0);
 
961
        return x * sign;
 
962
#undef NBITS_WANTED
 
963
}
 
964
 
 
965
/* Get a C double from a long int object. */
 
966
 
 
967
double
 
968
PyLong_AsDouble(PyObject *vv)
 
969
{
 
970
        int e = -1;
 
971
        double x;
 
972
 
 
973
        if (vv == NULL || !PyLong_Check(vv)) {
 
974
                PyErr_BadInternalCall();
 
975
                return -1;
 
976
        }
 
977
        x = _PyLong_AsScaledDouble(vv, &e);
 
978
        if (x == -1.0 && PyErr_Occurred())
 
979
                return -1.0;
 
980
        /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
 
981
           set correctly after a successful _PyLong_AsScaledDouble() call */
 
982
        assert(e >= 0);
 
983
        if (e > INT_MAX / PyLong_SHIFT)
 
984
                goto overflow;
 
985
        errno = 0;
 
986
        x = ldexp(x, e * PyLong_SHIFT);
 
987
        if (Py_OVERFLOWED(x))
 
988
                goto overflow;
 
989
        return x;
 
990
 
 
991
overflow:
 
992
        PyErr_SetString(PyExc_OverflowError,
 
993
                "Python int too large to convert to C double");
 
994
        return -1.0;
 
995
}
 
996
 
 
997
/* Create a new long (or int) object from a C pointer */
 
998
 
 
999
PyObject *
 
1000
PyLong_FromVoidPtr(void *p)
 
1001
{
 
1002
#ifndef HAVE_LONG_LONG
 
1003
#   error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
 
1004
#endif
 
1005
#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
 
1006
#   error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
 
1007
#endif
 
1008
        /* special-case null pointer */
 
1009
        if (!p)
 
1010
                return PyLong_FromLong(0);
 
1011
        return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
 
1012
 
 
1013
}
 
1014
 
 
1015
/* Get a C pointer from a long object (or an int object in some cases) */
 
1016
 
 
1017
void *
 
1018
PyLong_AsVoidPtr(PyObject *vv)
 
1019
{
 
1020
        /* This function will allow int or long objects. If vv is neither,
 
1021
           then the PyLong_AsLong*() functions will raise the exception:
 
1022
           PyExc_SystemError, "bad argument to internal function"
 
1023
        */
 
1024
#if SIZEOF_VOID_P <= SIZEOF_LONG
 
1025
        long x;
 
1026
 
 
1027
        if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
 
1028
                x = PyLong_AsLong(vv);
 
1029
        else
 
1030
                x = PyLong_AsUnsignedLong(vv);
 
1031
#else
 
1032
 
 
1033
#ifndef HAVE_LONG_LONG
 
1034
#   error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
 
1035
#endif
 
1036
#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
 
1037
#   error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
 
1038
#endif
 
1039
        PY_LONG_LONG x;
 
1040
 
 
1041
        if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
 
1042
                x = PyLong_AsLongLong(vv);
 
1043
        else
 
1044
                x = PyLong_AsUnsignedLongLong(vv);
 
1045
 
 
1046
#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
 
1047
 
 
1048
        if (x == -1 && PyErr_Occurred())
 
1049
                return NULL;
 
1050
        return (void *)x;
 
1051
}
 
1052
 
 
1053
#ifdef HAVE_LONG_LONG
 
1054
 
 
1055
/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
 
1056
 * rewritten to use the newer PyLong_{As,From}ByteArray API.
 
1057
 */
 
1058
 
 
1059
#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
 
1060
 
 
1061
/* Create a new long int object from a C PY_LONG_LONG int. */
 
1062
 
 
1063
PyObject *
 
1064
PyLong_FromLongLong(PY_LONG_LONG ival)
 
1065
{
 
1066
        PyLongObject *v;
 
1067
        unsigned PY_LONG_LONG abs_ival;
 
1068
        unsigned PY_LONG_LONG t;  /* unsigned so >> doesn't propagate sign bit */
 
1069
        int ndigits = 0;
 
1070
        int negative = 0;
 
1071
 
 
1072
        CHECK_SMALL_INT(ival);
 
1073
        if (ival < 0) {
 
1074
                /* avoid signed overflow on negation;  see comments
 
1075
                   in PyLong_FromLong above. */
 
1076
                abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
 
1077
                negative = 1;
 
1078
        }
 
1079
        else {
 
1080
                abs_ival = (unsigned PY_LONG_LONG)ival;
 
1081
        }
 
1082
 
 
1083
        /* Count the number of Python digits.
 
1084
           We used to pick 5 ("big enough for anything"), but that's a
 
1085
           waste of time and space given that 5*15 = 75 bits are rarely
 
1086
           needed. */
 
1087
        t = abs_ival;
 
1088
        while (t) {
 
1089
                ++ndigits;
 
1090
                t >>= PyLong_SHIFT;
 
1091
        }
 
1092
        v = _PyLong_New(ndigits);
 
1093
        if (v != NULL) {
 
1094
                digit *p = v->ob_digit;
 
1095
                Py_SIZE(v) = negative ? -ndigits : ndigits;
 
1096
                t = abs_ival;
 
1097
                while (t) {
 
1098
                        *p++ = (digit)(t & PyLong_MASK);
 
1099
                        t >>= PyLong_SHIFT;
 
1100
                }
 
1101
        }
 
1102
        return (PyObject *)v;
 
1103
}
 
1104
 
 
1105
/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
 
1106
 
 
1107
PyObject *
 
1108
PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
 
1109
{
 
1110
        PyLongObject *v;
 
1111
        unsigned PY_LONG_LONG t;
 
1112
        int ndigits = 0;
 
1113
 
 
1114
        if (ival < PyLong_BASE)
 
1115
                return PyLong_FromLong((long)ival);
 
1116
        /* Count the number of Python digits. */
 
1117
        t = (unsigned PY_LONG_LONG)ival;
 
1118
        while (t) {
 
1119
                ++ndigits;
 
1120
                t >>= PyLong_SHIFT;
 
1121
        }
 
1122
        v = _PyLong_New(ndigits);
 
1123
        if (v != NULL) {
 
1124
                digit *p = v->ob_digit;
 
1125
                Py_SIZE(v) = ndigits;
 
1126
                while (ival) {
 
1127
                        *p++ = (digit)(ival & PyLong_MASK);
 
1128
                        ival >>= PyLong_SHIFT;
 
1129
                }
 
1130
        }
 
1131
        return (PyObject *)v;
 
1132
}
 
1133
 
 
1134
/* Create a new long int object from a C Py_ssize_t. */
 
1135
 
 
1136
PyObject *
 
1137
PyLong_FromSsize_t(Py_ssize_t ival)
 
1138
{
 
1139
        PyLongObject *v;
 
1140
        size_t abs_ival;
 
1141
        size_t t;  /* unsigned so >> doesn't propagate sign bit */
 
1142
        int ndigits = 0;
 
1143
        int negative = 0;
 
1144
 
 
1145
        CHECK_SMALL_INT(ival);
 
1146
        if (ival < 0) {
 
1147
                /* avoid signed overflow when ival = SIZE_T_MIN */
 
1148
                abs_ival = (size_t)(-1-ival)+1;
 
1149
                negative = 1;
 
1150
        }
 
1151
        else {
 
1152
                abs_ival = (size_t)ival;
 
1153
        }
 
1154
 
 
1155
        /* Count the number of Python digits. */
 
1156
        t = abs_ival;
 
1157
        while (t) {
 
1158
                ++ndigits;
 
1159
                t >>= PyLong_SHIFT;
 
1160
        }
 
1161
        v = _PyLong_New(ndigits);
 
1162
        if (v != NULL) {
 
1163
                digit *p = v->ob_digit;
 
1164
                Py_SIZE(v) = negative ? -ndigits : ndigits;
 
1165
                t = abs_ival;
 
1166
                while (t) {
 
1167
                        *p++ = (digit)(t & PyLong_MASK);
 
1168
                        t >>= PyLong_SHIFT;
 
1169
                }
 
1170
        }
 
1171
        return (PyObject *)v;
 
1172
}
 
1173
 
 
1174
/* Create a new long int object from a C size_t. */
 
1175
 
 
1176
PyObject *
 
1177
PyLong_FromSize_t(size_t ival)
 
1178
{
 
1179
        PyLongObject *v;
 
1180
        size_t t;
 
1181
        int ndigits = 0;
 
1182
 
 
1183
        if (ival < PyLong_BASE)
 
1184
                return PyLong_FromLong(ival);
 
1185
        /* Count the number of Python digits. */
 
1186
        t = ival;
 
1187
        while (t) {
 
1188
                ++ndigits;
 
1189
                t >>= PyLong_SHIFT;
 
1190
        }
 
1191
        v = _PyLong_New(ndigits);
 
1192
        if (v != NULL) {
 
1193
                digit *p = v->ob_digit;
 
1194
                Py_SIZE(v) = ndigits;
 
1195
                while (ival) {
 
1196
                        *p++ = (digit)(ival & PyLong_MASK);
 
1197
                        ival >>= PyLong_SHIFT;
 
1198
                }
 
1199
        }
 
1200
        return (PyObject *)v;
 
1201
}
 
1202
 
 
1203
/* Get a C PY_LONG_LONG int from a long int object.
 
1204
   Return -1 and set an error if overflow occurs. */
 
1205
 
 
1206
PY_LONG_LONG
 
1207
PyLong_AsLongLong(PyObject *vv)
 
1208
{
 
1209
        PyLongObject *v;
 
1210
        PY_LONG_LONG bytes;
 
1211
        int one = 1;
 
1212
        int res;
 
1213
 
 
1214
        if (vv == NULL) {
 
1215
                PyErr_BadInternalCall();
 
1216
                return -1;
 
1217
        }
 
1218
        if (!PyLong_Check(vv)) {
 
1219
                PyNumberMethods *nb;
 
1220
                PyObject *io;
 
1221
                if ((nb = vv->ob_type->tp_as_number) == NULL ||
 
1222
                    nb->nb_int == NULL) {
 
1223
                        PyErr_SetString(PyExc_TypeError, "an integer is required");
 
1224
                        return -1;
 
1225
                }
 
1226
                io = (*nb->nb_int) (vv);
 
1227
                if (io == NULL)
 
1228
                        return -1;
 
1229
                if (PyLong_Check(io)) {
 
1230
                        bytes = PyLong_AsLongLong(io);
 
1231
                        Py_DECREF(io);
 
1232
                        return bytes;
 
1233
                }
 
1234
                Py_DECREF(io);
 
1235
                PyErr_SetString(PyExc_TypeError, "integer conversion failed");
 
1236
                return -1;
 
1237
        }
 
1238
 
 
1239
        v = (PyLongObject*)vv;
 
1240
        switch(Py_SIZE(v)) {
 
1241
        case -1: return -(sdigit)v->ob_digit[0];
 
1242
        case 0: return 0;
 
1243
        case 1: return v->ob_digit[0];
 
1244
        }
 
1245
        res = _PyLong_AsByteArray(
 
1246
                        (PyLongObject *)vv, (unsigned char *)&bytes,
 
1247
                        SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
 
1248
 
 
1249
        /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
 
1250
        if (res < 0)
 
1251
                return (PY_LONG_LONG)-1;
 
1252
        else
 
1253
                return bytes;
 
1254
}
 
1255
 
 
1256
/* Get a C unsigned PY_LONG_LONG int from a long int object.
 
1257
   Return -1 and set an error if overflow occurs. */
 
1258
 
 
1259
unsigned PY_LONG_LONG
 
1260
PyLong_AsUnsignedLongLong(PyObject *vv)
 
1261
{
 
1262
        PyLongObject *v;
 
1263
        unsigned PY_LONG_LONG bytes;
 
1264
        int one = 1;
 
1265
        int res;
 
1266
 
 
1267
        if (vv == NULL || !PyLong_Check(vv)) {
 
1268
                PyErr_BadInternalCall();
 
1269
                return (unsigned PY_LONG_LONG)-1;
 
1270
        }
 
1271
 
 
1272
        v = (PyLongObject*)vv;
 
1273
        switch(Py_SIZE(v)) {
 
1274
        case 0: return 0;
 
1275
        case 1: return v->ob_digit[0];
 
1276
        }
 
1277
 
 
1278
        res = _PyLong_AsByteArray(
 
1279
                        (PyLongObject *)vv, (unsigned char *)&bytes,
 
1280
                        SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
 
1281
 
 
1282
        /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
 
1283
        if (res < 0)
 
1284
                return (unsigned PY_LONG_LONG)res;
 
1285
        else
 
1286
                return bytes;
 
1287
}
 
1288
 
 
1289
/* Get a C unsigned long int from a long int object, ignoring the high bits.
 
1290
   Returns -1 and sets an error condition if an error occurs. */
 
1291
 
 
1292
static unsigned PY_LONG_LONG
 
1293
_PyLong_AsUnsignedLongLongMask(PyObject *vv)
 
1294
{
 
1295
        register PyLongObject *v;
 
1296
        unsigned PY_LONG_LONG x;
 
1297
        Py_ssize_t i;
 
1298
        int sign;
 
1299
 
 
1300
        if (vv == NULL || !PyLong_Check(vv)) {
 
1301
                PyErr_BadInternalCall();
 
1302
                return (unsigned long) -1;
 
1303
        }
 
1304
        v = (PyLongObject *)vv;
 
1305
        switch(Py_SIZE(v)) {
 
1306
        case 0: return 0;
 
1307
        case 1: return v->ob_digit[0];
 
1308
        }
 
1309
        i = Py_SIZE(v);
 
1310
        sign = 1;
 
1311
        x = 0;
 
1312
        if (i < 0) {
 
1313
                sign = -1;
 
1314
                i = -i;
 
1315
        }
 
1316
        while (--i >= 0) {
 
1317
                x = (x << PyLong_SHIFT) + v->ob_digit[i];
 
1318
        }
 
1319
        return x * sign;
 
1320
}
 
1321
 
 
1322
unsigned PY_LONG_LONG
 
1323
PyLong_AsUnsignedLongLongMask(register PyObject *op)
 
1324
{
 
1325
        PyNumberMethods *nb;
 
1326
        PyLongObject *lo;
 
1327
        unsigned PY_LONG_LONG val;
 
1328
 
 
1329
        if (op && PyLong_Check(op))
 
1330
                return _PyLong_AsUnsignedLongLongMask(op);
 
1331
 
 
1332
        if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
 
1333
            nb->nb_int == NULL) {
 
1334
                PyErr_SetString(PyExc_TypeError, "an integer is required");
 
1335
                return (unsigned PY_LONG_LONG)-1;
 
1336
        }
 
1337
 
 
1338
        lo = (PyLongObject*) (*nb->nb_int) (op);
 
1339
        if (lo == NULL)
 
1340
                return (unsigned PY_LONG_LONG)-1;
 
1341
        if (PyLong_Check(lo)) {
 
1342
                val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
 
1343
                Py_DECREF(lo);
 
1344
                if (PyErr_Occurred())
 
1345
                        return (unsigned PY_LONG_LONG)-1;
 
1346
                return val;
 
1347
        }
 
1348
        else
 
1349
        {
 
1350
                Py_DECREF(lo);
 
1351
                PyErr_SetString(PyExc_TypeError,
 
1352
                                "nb_int should return int object");
 
1353
                return (unsigned PY_LONG_LONG)-1;
 
1354
        }
 
1355
}
 
1356
#undef IS_LITTLE_ENDIAN
 
1357
 
 
1358
#endif /* HAVE_LONG_LONG */
 
1359
 
 
1360
#define CHECK_BINOP(v,w) \
 
1361
        if (!PyLong_Check(v) || !PyLong_Check(w)) { \
 
1362
                Py_INCREF(Py_NotImplemented); \
 
1363
                return Py_NotImplemented; \
 
1364
        }
 
1365
 
 
1366
/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required.  x[0:n]
 
1367
 * is modified in place, by adding y to it.  Carries are propagated as far as
 
1368
 * x[m-1], and the remaining carry (0 or 1) is returned.
 
1369
 */
 
1370
static digit
 
1371
v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
 
1372
{
 
1373
        Py_ssize_t i;
 
1374
        digit carry = 0;
 
1375
 
 
1376
        assert(m >= n);
 
1377
        for (i = 0; i < n; ++i) {
 
1378
                carry += x[i] + y[i];
 
1379
                x[i] = carry & PyLong_MASK;
 
1380
                carry >>= PyLong_SHIFT;
 
1381
                assert((carry & 1) == carry);
 
1382
        }
 
1383
        for (; carry && i < m; ++i) {
 
1384
                carry += x[i];
 
1385
                x[i] = carry & PyLong_MASK;
 
1386
                carry >>= PyLong_SHIFT;
 
1387
                assert((carry & 1) == carry);
 
1388
        }
 
1389
        return carry;
 
1390
}
 
1391
 
 
1392
/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required.  x[0:n]
 
1393
 * is modified in place, by subtracting y from it.  Borrows are propagated as
 
1394
 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
 
1395
 */
 
1396
static digit
 
1397
v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
 
1398
{
 
1399
        Py_ssize_t i;
 
1400
        digit borrow = 0;
 
1401
 
 
1402
        assert(m >= n);
 
1403
        for (i = 0; i < n; ++i) {
 
1404
                borrow = x[i] - y[i] - borrow;
 
1405
                x[i] = borrow & PyLong_MASK;
 
1406
                borrow >>= PyLong_SHIFT;
 
1407
                borrow &= 1;    /* keep only 1 sign bit */
 
1408
        }
 
1409
        for (; borrow && i < m; ++i) {
 
1410
                borrow = x[i] - borrow;
 
1411
                x[i] = borrow & PyLong_MASK;
 
1412
                borrow >>= PyLong_SHIFT;
 
1413
                borrow &= 1;
 
1414
        }
 
1415
        return borrow;
 
1416
}
 
1417
 
 
1418
/* Multiply by a single digit, ignoring the sign. */
 
1419
 
 
1420
static PyLongObject *
 
1421
mul1(PyLongObject *a, digit n)
 
1422
{
 
1423
        Py_ssize_t size_a = ABS(Py_SIZE(a));
 
1424
        PyLongObject *z = _PyLong_New(size_a+1);
 
1425
        twodigits carry = 0;
 
1426
        Py_ssize_t i;
 
1427
 
 
1428
        if (z == NULL)
 
1429
                return NULL;
 
1430
        for (i = 0; i < size_a; ++i) {
 
1431
                carry += (twodigits)a->ob_digit[i] * n;
 
1432
                z->ob_digit[i] = (digit) (carry & PyLong_MASK);
 
1433
                carry >>= PyLong_SHIFT;
 
1434
        }
 
1435
        z->ob_digit[i] = (digit) carry;
 
1436
        return long_normalize(z);
 
1437
}
 
1438
 
 
1439
/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
 
1440
   in pout, and returning the remainder.  pin and pout point at the LSD.
 
1441
   It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
 
1442
   _PyLong_Format, but that should be done with great care since longs are
 
1443
   immutable. */
 
1444
 
 
1445
static digit
 
1446
inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
 
1447
{
 
1448
        twodigits rem = 0;
 
1449
 
 
1450
        assert(n > 0 && n <= PyLong_MASK);
 
1451
        pin += size;
 
1452
        pout += size;
 
1453
        while (--size >= 0) {
 
1454
                digit hi;
 
1455
                rem = (rem << PyLong_SHIFT) + *--pin;
 
1456
                *--pout = hi = (digit)(rem / n);
 
1457
                rem -= (twodigits)hi * n;
 
1458
        }
 
1459
        return (digit)rem;
 
1460
}
 
1461
 
 
1462
/* Divide a long integer by a digit, returning both the quotient
 
1463
   (as function result) and the remainder (through *prem).
 
1464
   The sign of a is ignored; n should not be zero. */
 
1465
 
 
1466
static PyLongObject *
 
1467
divrem1(PyLongObject *a, digit n, digit *prem)
 
1468
{
 
1469
        const Py_ssize_t size = ABS(Py_SIZE(a));
 
1470
        PyLongObject *z;
 
1471
 
 
1472
        assert(n > 0 && n <= PyLong_MASK);
 
1473
        z = _PyLong_New(size);
 
1474
        if (z == NULL)
 
1475
                return NULL;
 
1476
        *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
 
1477
        return long_normalize(z);
 
1478
}
 
1479
 
 
1480
/* Convert a long int object to a string, using a given conversion base.
 
1481
   Return a string object.
 
1482
   If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
 
1483
 
 
1484
PyObject *
 
1485
_PyLong_Format(PyObject *aa, int base)
 
1486
{
 
1487
        register PyLongObject *a = (PyLongObject *)aa;
 
1488
        PyObject *str;
 
1489
        Py_ssize_t i, j, sz;
 
1490
        Py_ssize_t size_a;
 
1491
        Py_UNICODE *p;
 
1492
        int bits;
 
1493
        char sign = '\0';
 
1494
 
 
1495
        if (a == NULL || !PyLong_Check(a)) {
 
1496
                PyErr_BadInternalCall();
 
1497
                return NULL;
 
1498
        }
 
1499
        assert(base >= 2 && base <= 36);
 
1500
        size_a = ABS(Py_SIZE(a));
 
1501
 
 
1502
        /* Compute a rough upper bound for the length of the string */
 
1503
        i = base;
 
1504
        bits = 0;
 
1505
        while (i > 1) {
 
1506
                ++bits;
 
1507
                i >>= 1;
 
1508
        }
 
1509
        i = 5;
 
1510
        j = size_a*PyLong_SHIFT + bits-1;
 
1511
        sz = i + j / bits;
 
1512
        if (j / PyLong_SHIFT < size_a || sz < i) {
 
1513
                PyErr_SetString(PyExc_OverflowError,
 
1514
                                "int is too large to format");
 
1515
                return NULL;
 
1516
        }
 
1517
        str = PyUnicode_FromUnicode(NULL, sz);
 
1518
        if (str == NULL)
 
1519
                return NULL;
 
1520
        p = PyUnicode_AS_UNICODE(str) + sz;
 
1521
        *p = '\0';
 
1522
        if (Py_SIZE(a) < 0)
 
1523
                sign = '-';
 
1524
 
 
1525
        if (Py_SIZE(a) == 0) {
 
1526
                *--p = '0';
 
1527
        }
 
1528
        else if ((base & (base - 1)) == 0) {
 
1529
                /* JRH: special case for power-of-2 bases */
 
1530
                twodigits accum = 0;
 
1531
                int accumbits = 0;      /* # of bits in accum */
 
1532
                int basebits = 1;       /* # of bits in base-1 */
 
1533
                i = base;
 
1534
                while ((i >>= 1) > 1)
 
1535
                        ++basebits;
 
1536
 
 
1537
                for (i = 0; i < size_a; ++i) {
 
1538
                        accum |= (twodigits)a->ob_digit[i] << accumbits;
 
1539
                        accumbits += PyLong_SHIFT;
 
1540
                        assert(accumbits >= basebits);
 
1541
                        do {
 
1542
                                char cdigit = (char)(accum & (base - 1));
 
1543
                                cdigit += (cdigit < 10) ? '0' : 'a'-10;
 
1544
                                assert(p > PyUnicode_AS_UNICODE(str));
 
1545
                                *--p = cdigit;
 
1546
                                accumbits -= basebits;
 
1547
                                accum >>= basebits;
 
1548
                        } while (i < size_a-1 ? accumbits >= basebits :
 
1549
                                                accum > 0);
 
1550
                }
 
1551
        }
 
1552
        else {
 
1553
                /* Not 0, and base not a power of 2.  Divide repeatedly by
 
1554
                   base, but for speed use the highest power of base that
 
1555
                   fits in a digit. */
 
1556
                Py_ssize_t size = size_a;
 
1557
                digit *pin = a->ob_digit;
 
1558
                PyLongObject *scratch;
 
1559
                /* powbasw <- largest power of base that fits in a digit. */
 
1560
                digit powbase = base;  /* powbase == base ** power */
 
1561
                int power = 1;
 
1562
                for (;;) {
 
1563
                        twodigits newpow = powbase * (twodigits)base;
 
1564
                        if (newpow >> PyLong_SHIFT)  /* doesn't fit in a digit */
 
1565
                                break;
 
1566
                        powbase = (digit)newpow;
 
1567
                        ++power;
 
1568
                }
 
1569
 
 
1570
                /* Get a scratch area for repeated division. */
 
1571
                scratch = _PyLong_New(size);
 
1572
                if (scratch == NULL) {
 
1573
                        Py_DECREF(str);
 
1574
                        return NULL;
 
1575
                }
 
1576
 
 
1577
                /* Repeatedly divide by powbase. */
 
1578
                do {
 
1579
                        int ntostore = power;
 
1580
                        digit rem = inplace_divrem1(scratch->ob_digit,
 
1581
                                                     pin, size, powbase);
 
1582
                        pin = scratch->ob_digit; /* no need to use a again */
 
1583
                        if (pin[size - 1] == 0)
 
1584
                                --size;
 
1585
                        SIGCHECK({
 
1586
                                Py_DECREF(scratch);
 
1587
                                Py_DECREF(str);
 
1588
                                return NULL;
 
1589
                        })
 
1590
 
 
1591
                        /* Break rem into digits. */
 
1592
                        assert(ntostore > 0);
 
1593
                        do {
 
1594
                                digit nextrem = (digit)(rem / base);
 
1595
                                char c = (char)(rem - nextrem * base);
 
1596
                                assert(p > PyUnicode_AS_UNICODE(str));
 
1597
                                c += (c < 10) ? '0' : 'a'-10;
 
1598
                                *--p = c;
 
1599
                                rem = nextrem;
 
1600
                                --ntostore;
 
1601
                                /* Termination is a bit delicate:  must not
 
1602
                                   store leading zeroes, so must get out if
 
1603
                                   remaining quotient and rem are both 0. */
 
1604
                        } while (ntostore && (size || rem));
 
1605
                } while (size != 0);
 
1606
                Py_DECREF(scratch);
 
1607
        }
 
1608
 
 
1609
        if (base == 16) {
 
1610
                *--p = 'x';
 
1611
                *--p = '0';
 
1612
        }
 
1613
        else if (base == 8) {
 
1614
                *--p = 'o';
 
1615
                *--p = '0';
 
1616
        }
 
1617
        else if (base == 2) {
 
1618
                *--p = 'b';
 
1619
                *--p = '0';
 
1620
        }
 
1621
        else if (base != 10) {
 
1622
                *--p = '#';
 
1623
                *--p = '0' + base%10;
 
1624
                if (base > 10)
 
1625
                        *--p = '0' + base/10;
 
1626
        }
 
1627
        if (sign)
 
1628
                *--p = sign;
 
1629
        if (p != PyUnicode_AS_UNICODE(str)) {
 
1630
                Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
 
1631
                assert(p > q);
 
1632
                do {
 
1633
                } while ((*q++ = *p++) != '\0');
 
1634
                q--;
 
1635
                if (PyUnicode_Resize(&str, (Py_ssize_t) (q - PyUnicode_AS_UNICODE(str)))) {
 
1636
                        Py_DECREF(str);
 
1637
                        return NULL;
 
1638
                }
 
1639
        }
 
1640
        return (PyObject *)str;
 
1641
}
 
1642
 
 
1643
/* Table of digit values for 8-bit string -> integer conversion.
 
1644
 * '0' maps to 0, ..., '9' maps to 9.
 
1645
 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
 
1646
 * All other indices map to 37.
 
1647
 * Note that when converting a base B string, a char c is a legitimate
 
1648
 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
 
1649
 */
 
1650
unsigned char _PyLong_DigitValue[256] = {
 
1651
        37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
 
1652
        37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
 
1653
        37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
 
1654
        0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  37, 37, 37, 37, 37, 37,
 
1655
        37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
 
1656
        25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
 
1657
        37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
 
1658
        25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
 
1659
        37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
 
1660
        37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
 
1661
        37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
 
1662
        37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
 
1663
        37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
 
1664
        37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
 
1665
        37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
 
1666
        37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
 
1667
};
 
1668
 
 
1669
/* *str points to the first digit in a string of base `base` digits.  base
 
1670
 * is a power of 2 (2, 4, 8, 16, or 32).  *str is set to point to the first
 
1671
 * non-digit (which may be *str!).  A normalized long is returned.
 
1672
 * The point to this routine is that it takes time linear in the number of
 
1673
 * string characters.
 
1674
 */
 
1675
static PyLongObject *
 
1676
long_from_binary_base(char **str, int base)
 
1677
{
 
1678
        char *p = *str;
 
1679
        char *start = p;
 
1680
        int bits_per_char;
 
1681
        Py_ssize_t n;
 
1682
        PyLongObject *z;
 
1683
        twodigits accum;
 
1684
        int bits_in_accum;
 
1685
        digit *pdigit;
 
1686
 
 
1687
        assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
 
1688
        n = base;
 
1689
        for (bits_per_char = -1; n; ++bits_per_char)
 
1690
                n >>= 1;
 
1691
        /* n <- total # of bits needed, while setting p to end-of-string */
 
1692
        n = 0;
 
1693
        while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
 
1694
                ++p;
 
1695
        *str = p;
 
1696
        /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
 
1697
        n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
 
1698
        if (n / bits_per_char < p - start) {
 
1699
                PyErr_SetString(PyExc_ValueError,
 
1700
                                "int string too large to convert");
 
1701
                return NULL;
 
1702
        }
 
1703
        n = n / PyLong_SHIFT;
 
1704
        z = _PyLong_New(n);
 
1705
        if (z == NULL)
 
1706
                return NULL;
 
1707
        /* Read string from right, and fill in long from left; i.e.,
 
1708
         * from least to most significant in both.
 
1709
         */
 
1710
        accum = 0;
 
1711
        bits_in_accum = 0;
 
1712
        pdigit = z->ob_digit;
 
1713
        while (--p >= start) {
 
1714
                int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
 
1715
                assert(k >= 0 && k < base);
 
1716
                accum |= (twodigits)k << bits_in_accum;
 
1717
                bits_in_accum += bits_per_char;
 
1718
                if (bits_in_accum >= PyLong_SHIFT) {
 
1719
                        *pdigit++ = (digit)(accum & PyLong_MASK);
 
1720
                        assert(pdigit - z->ob_digit <= n);
 
1721
                        accum >>= PyLong_SHIFT;
 
1722
                        bits_in_accum -= PyLong_SHIFT;
 
1723
                        assert(bits_in_accum < PyLong_SHIFT);
 
1724
                }
 
1725
        }
 
1726
        if (bits_in_accum) {
 
1727
                assert(bits_in_accum <= PyLong_SHIFT);
 
1728
                *pdigit++ = (digit)accum;
 
1729
                assert(pdigit - z->ob_digit <= n);
 
1730
        }
 
1731
        while (pdigit - z->ob_digit < n)
 
1732
                *pdigit++ = 0;
 
1733
        return long_normalize(z);
 
1734
}
 
1735
 
 
1736
PyObject *
 
1737
PyLong_FromString(char *str, char **pend, int base)
 
1738
{
 
1739
        int sign = 1, error_if_nonzero = 0;
 
1740
        char *start, *orig_str = str;
 
1741
        PyLongObject *z = NULL;
 
1742
        PyObject *strobj;
 
1743
        Py_ssize_t slen;
 
1744
 
 
1745
        if ((base != 0 && base < 2) || base > 36) {
 
1746
                PyErr_SetString(PyExc_ValueError,
 
1747
                                "int() arg 2 must be >= 2 and <= 36");
 
1748
                return NULL;
 
1749
        }
 
1750
        while (*str != '\0' && isspace(Py_CHARMASK(*str)))
 
1751
                str++;
 
1752
        if (*str == '+')
 
1753
                ++str;
 
1754
        else if (*str == '-') {
 
1755
                ++str;
 
1756
                sign = -1;
 
1757
        }
 
1758
        if (base == 0) {
 
1759
                if (str[0] != '0')
 
1760
                        base = 10;
 
1761
                else if (str[1] == 'x' || str[1] == 'X')
 
1762
                        base = 16;
 
1763
                else if (str[1] == 'o' || str[1] == 'O')
 
1764
                        base = 8;
 
1765
                else if (str[1] == 'b' || str[1] == 'B')
 
1766
                        base = 2;
 
1767
                else {
 
1768
                        /* "old" (C-style) octal literal, now invalid.
 
1769
                           it might still be zero though */
 
1770
                        error_if_nonzero = 1;
 
1771
                        base = 10;
 
1772
                }
 
1773
        }
 
1774
        if (str[0] == '0' &&
 
1775
            ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
 
1776
             (base == 8  && (str[1] == 'o' || str[1] == 'O')) ||
 
1777
             (base == 2  && (str[1] == 'b' || str[1] == 'B'))))
 
1778
                str += 2;
 
1779
 
 
1780
        start = str;
 
1781
        if ((base & (base - 1)) == 0)
 
1782
                z = long_from_binary_base(&str, base);
 
1783
        else {
 
1784
/***
 
1785
Binary bases can be converted in time linear in the number of digits, because
 
1786
Python's representation base is binary.  Other bases (including decimal!) use
 
1787
the simple quadratic-time algorithm below, complicated by some speed tricks.
 
1788
 
 
1789
First some math:  the largest integer that can be expressed in N base-B digits
 
1790
is B**N-1.  Consequently, if we have an N-digit input in base B, the worst-
 
1791
case number of Python digits needed to hold it is the smallest integer n s.t.
 
1792
 
 
1793
    BASE**n-1 >= B**N-1  [or, adding 1 to both sides]
 
1794
    BASE**n >= B**N      [taking logs to base BASE]
 
1795
    n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
 
1796
 
 
1797
The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
 
1798
this quickly.  A Python long with that much space is reserved near the start,
 
1799
and the result is computed into it.
 
1800
 
 
1801
The input string is actually treated as being in base base**i (i.e., i digits
 
1802
are processed at a time), where two more static arrays hold:
 
1803
 
 
1804
    convwidth_base[base] = the largest integer i such that base**i <= BASE
 
1805
    convmultmax_base[base] = base ** convwidth_base[base]
 
1806
 
 
1807
The first of these is the largest i such that i consecutive input digits
 
1808
must fit in a single Python digit.  The second is effectively the input
 
1809
base we're really using.
 
1810
 
 
1811
Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
 
1812
convmultmax_base[base], the result is "simply"
 
1813
 
 
1814
   (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
 
1815
 
 
1816
where B = convmultmax_base[base].
 
1817
 
 
1818
Error analysis:  as above, the number of Python digits `n` needed is worst-
 
1819
case
 
1820
 
 
1821
    n >= N * log(B)/log(BASE)
 
1822
 
 
1823
where `N` is the number of input digits in base `B`.  This is computed via
 
1824
 
 
1825
    size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
 
1826
 
 
1827
below.  Two numeric concerns are how much space this can waste, and whether
 
1828
the computed result can be too small.  To be concrete, assume BASE = 2**15,
 
1829
which is the default (and it's unlikely anyone changes that).
 
1830
 
 
1831
Waste isn't a problem:  provided the first input digit isn't 0, the difference
 
1832
between the worst-case input with N digits and the smallest input with N
 
1833
digits is about a factor of B, but B is small compared to BASE so at most
 
1834
one allocated Python digit can remain unused on that count.  If
 
1835
N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
 
1836
and adding 1 returns a result 1 larger than necessary.  However, that can't
 
1837
happen:  whenever B is a power of 2, long_from_binary_base() is called
 
1838
instead, and it's impossible for B**i to be an integer power of 2**15 when
 
1839
B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
 
1840
an exact integer when B is not a power of 2, since B**i has a prime factor
 
1841
other than 2 in that case, but (2**15)**j's only prime factor is 2).
 
1842
 
 
1843
The computed result can be too small if the true value of N*log(B)/log(BASE)
 
1844
is a little bit larger than an exact integer, but due to roundoff errors (in
 
1845
computing log(B), log(BASE), their quotient, and/or multiplying that by N)
 
1846
yields a numeric result a little less than that integer.  Unfortunately, "how
 
1847
close can a transcendental function get to an integer over some range?"
 
1848
questions are generally theoretically intractable.  Computer analysis via
 
1849
continued fractions is practical:  expand log(B)/log(BASE) via continued
 
1850
fractions, giving a sequence i/j of "the best" rational approximations.  Then
 
1851
j*log(B)/log(BASE) is approximately equal to (the integer) i.  This shows that
 
1852
we can get very close to being in trouble, but very rarely.  For example,
 
1853
76573 is a denominator in one of the continued-fraction approximations to
 
1854
log(10)/log(2**15), and indeed:
 
1855
 
 
1856
    >>> log(10)/log(2**15)*76573
 
1857
    16958.000000654003
 
1858
 
 
1859
is very close to an integer.  If we were working with IEEE single-precision,
 
1860
rounding errors could kill us.  Finding worst cases in IEEE double-precision
 
1861
requires better-than-double-precision log() functions, and Tim didn't bother.
 
1862
Instead the code checks to see whether the allocated space is enough as each
 
1863
new Python digit is added, and copies the whole thing to a larger long if not.
 
1864
This should happen extremely rarely, and in fact I don't have a test case
 
1865
that triggers it(!).  Instead the code was tested by artificially allocating
 
1866
just 1 digit at the start, so that the copying code was exercised for every
 
1867
digit beyond the first.
 
1868
***/
 
1869
                register twodigits c;   /* current input character */
 
1870
                Py_ssize_t size_z;
 
1871
                int i;
 
1872
                int convwidth;
 
1873
                twodigits convmultmax, convmult;
 
1874
                digit *pz, *pzstop;
 
1875
                char* scan;
 
1876
 
 
1877
                static double log_base_BASE[37] = {0.0e0,};
 
1878
                static int convwidth_base[37] = {0,};
 
1879
                static twodigits convmultmax_base[37] = {0,};
 
1880
 
 
1881
                if (log_base_BASE[base] == 0.0) {
 
1882
                        twodigits convmax = base;
 
1883
                        int i = 1;
 
1884
 
 
1885
                        log_base_BASE[base] = log((double)base) /
 
1886
                                                log((double)PyLong_BASE);
 
1887
                        for (;;) {
 
1888
                                twodigits next = convmax * base;
 
1889
                                if (next > PyLong_BASE)
 
1890
                                        break;
 
1891
                                convmax = next;
 
1892
                                ++i;
 
1893
                        }
 
1894
                        convmultmax_base[base] = convmax;
 
1895
                        assert(i > 0);
 
1896
                        convwidth_base[base] = i;
 
1897
                }
 
1898
 
 
1899
                /* Find length of the string of numeric characters. */
 
1900
                scan = str;
 
1901
                while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
 
1902
                        ++scan;
 
1903
 
 
1904
                /* Create a long object that can contain the largest possible
 
1905
                 * integer with this base and length.  Note that there's no
 
1906
                 * need to initialize z->ob_digit -- no slot is read up before
 
1907
                 * being stored into.
 
1908
                 */
 
1909
                size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
 
1910
                /* Uncomment next line to test exceedingly rare copy code */
 
1911
                /* size_z = 1; */
 
1912
                assert(size_z > 0);
 
1913
                z = _PyLong_New(size_z);
 
1914
                if (z == NULL)
 
1915
                        return NULL;
 
1916
                Py_SIZE(z) = 0;
 
1917
 
 
1918
                /* `convwidth` consecutive input digits are treated as a single
 
1919
                 * digit in base `convmultmax`.
 
1920
                 */
 
1921
                convwidth = convwidth_base[base];
 
1922
                convmultmax = convmultmax_base[base];
 
1923
 
 
1924
                /* Work ;-) */
 
1925
                while (str < scan) {
 
1926
                        /* grab up to convwidth digits from the input string */
 
1927
                        c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
 
1928
                        for (i = 1; i < convwidth && str != scan; ++i, ++str) {
 
1929
                                c = (twodigits)(c *  base +
 
1930
                                        (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
 
1931
                                assert(c < PyLong_BASE);
 
1932
                        }
 
1933
 
 
1934
                        convmult = convmultmax;
 
1935
                        /* Calculate the shift only if we couldn't get
 
1936
                         * convwidth digits.
 
1937
                         */
 
1938
                        if (i != convwidth) {
 
1939
                                convmult = base;
 
1940
                                for ( ; i > 1; --i)
 
1941
                                        convmult *= base;
 
1942
                        }
 
1943
 
 
1944
                        /* Multiply z by convmult, and add c. */
 
1945
                        pz = z->ob_digit;
 
1946
                        pzstop = pz + Py_SIZE(z);
 
1947
                        for (; pz < pzstop; ++pz) {
 
1948
                                c += (twodigits)*pz * convmult;
 
1949
                                *pz = (digit)(c & PyLong_MASK);
 
1950
                                c >>= PyLong_SHIFT;
 
1951
                        }
 
1952
                        /* carry off the current end? */
 
1953
                        if (c) {
 
1954
                                assert(c < PyLong_BASE);
 
1955
                                if (Py_SIZE(z) < size_z) {
 
1956
                                        *pz = (digit)c;
 
1957
                                        ++Py_SIZE(z);
 
1958
                                }
 
1959
                                else {
 
1960
                                        PyLongObject *tmp;
 
1961
                                        /* Extremely rare.  Get more space. */
 
1962
                                        assert(Py_SIZE(z) == size_z);
 
1963
                                        tmp = _PyLong_New(size_z + 1);
 
1964
                                        if (tmp == NULL) {
 
1965
                                                Py_DECREF(z);
 
1966
                                                return NULL;
 
1967
                                        }
 
1968
                                        memcpy(tmp->ob_digit,
 
1969
                                               z->ob_digit,
 
1970
                                               sizeof(digit) * size_z);
 
1971
                                        Py_DECREF(z);
 
1972
                                        z = tmp;
 
1973
                                        z->ob_digit[size_z] = (digit)c;
 
1974
                                        ++size_z;
 
1975
                                }
 
1976
                        }
 
1977
                }
 
1978
        }
 
1979
        if (z == NULL)
 
1980
                return NULL;
 
1981
        if (error_if_nonzero) {
 
1982
                /* reset the base to 0, else the exception message
 
1983
                   doesn't make too much sense */
 
1984
                base = 0;
 
1985
                if (Py_SIZE(z) != 0)
 
1986
                        goto onError;
 
1987
                /* there might still be other problems, therefore base
 
1988
                   remains zero here for the same reason */
 
1989
        }
 
1990
        if (str == start)
 
1991
                goto onError;
 
1992
        if (sign < 0)
 
1993
                Py_SIZE(z) = -(Py_SIZE(z));
 
1994
        while (*str && isspace(Py_CHARMASK(*str)))
 
1995
                str++;
 
1996
        if (*str != '\0')
 
1997
                goto onError;
 
1998
        if (pend)
 
1999
                *pend = str;
 
2000
        long_normalize(z);
 
2001
        return (PyObject *) maybe_small_long(z);
 
2002
 
 
2003
 onError:
 
2004
        Py_XDECREF(z);
 
2005
        slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
 
2006
        strobj = PyUnicode_FromStringAndSize(orig_str, slen);
 
2007
        if (strobj == NULL)
 
2008
                return NULL;
 
2009
        PyErr_Format(PyExc_ValueError,
 
2010
                     "invalid literal for int() with base %d: %R",
 
2011
                     base, strobj);
 
2012
        Py_DECREF(strobj);
 
2013
        return NULL;
 
2014
}
 
2015
 
 
2016
PyObject *
 
2017
PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
 
2018
{
 
2019
        PyObject *result;
 
2020
        char *buffer = (char *)PyMem_MALLOC(length+1);
 
2021
 
 
2022
        if (buffer == NULL)
 
2023
                return NULL;
 
2024
 
 
2025
        if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
 
2026
                PyMem_FREE(buffer);
 
2027
                return NULL;
 
2028
        }
 
2029
        result = PyLong_FromString(buffer, NULL, base);
 
2030
        PyMem_FREE(buffer);
 
2031
        return result;
 
2032
}
 
2033
 
 
2034
/* forward */
 
2035
static PyLongObject *x_divrem
 
2036
        (PyLongObject *, PyLongObject *, PyLongObject **);
 
2037
static PyObject *long_long(PyObject *v);
 
2038
 
 
2039
/* Long division with remainder, top-level routine */
 
2040
 
 
2041
static int
 
2042
long_divrem(PyLongObject *a, PyLongObject *b,
 
2043
            PyLongObject **pdiv, PyLongObject **prem)
 
2044
{
 
2045
        Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
 
2046
        PyLongObject *z;
 
2047
 
 
2048
        if (size_b == 0) {
 
2049
                PyErr_SetString(PyExc_ZeroDivisionError,
 
2050
                                "integer division or modulo by zero");
 
2051
                return -1;
 
2052
        }
 
2053
        if (size_a < size_b ||
 
2054
            (size_a == size_b &&
 
2055
             a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
 
2056
                /* |a| < |b|. */
 
2057
                *pdiv = (PyLongObject*)PyLong_FromLong(0);
 
2058
                if (*pdiv == NULL)
 
2059
                        return -1;
 
2060
                Py_INCREF(a);
 
2061
                *prem = (PyLongObject *) a;
 
2062
                return 0;
 
2063
        }
 
2064
        if (size_b == 1) {
 
2065
                digit rem = 0;
 
2066
                z = divrem1(a, b->ob_digit[0], &rem);
 
2067
                if (z == NULL)
 
2068
                        return -1;
 
2069
                *prem = (PyLongObject *) PyLong_FromLong((long)rem);
 
2070
                if (*prem == NULL) {
 
2071
                        Py_DECREF(z);
 
2072
                        return -1;
 
2073
                }
 
2074
        }
 
2075
        else {
 
2076
                z = x_divrem(a, b, prem);
 
2077
                if (z == NULL)
 
2078
                        return -1;
 
2079
        }
 
2080
        /* Set the signs.
 
2081
           The quotient z has the sign of a*b;
 
2082
           the remainder r has the sign of a,
 
2083
           so a = b*z + r. */
 
2084
        if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
 
2085
                NEGATE(z);
 
2086
        if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
 
2087
                NEGATE(*prem);
 
2088
        *pdiv = maybe_small_long(z);
 
2089
        return 0;
 
2090
}
 
2091
 
 
2092
/* Unsigned long division with remainder -- the algorithm */
 
2093
 
 
2094
static PyLongObject *
 
2095
x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
 
2096
{
 
2097
        Py_ssize_t size_v = ABS(Py_SIZE(v1)), size_w = ABS(Py_SIZE(w1));
 
2098
        digit d = (digit) ((twodigits)PyLong_BASE / (w1->ob_digit[size_w-1] + 1));
 
2099
        PyLongObject *v = mul1(v1, d);
 
2100
        PyLongObject *w = mul1(w1, d);
 
2101
        PyLongObject *a;
 
2102
        Py_ssize_t j, k;
 
2103
 
 
2104
        if (v == NULL || w == NULL) {
 
2105
                Py_XDECREF(v);
 
2106
                Py_XDECREF(w);
 
2107
                return NULL;
 
2108
        }
 
2109
 
 
2110
        assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
 
2111
        assert(Py_REFCNT(v) == 1); /* Since v will be used as accumulator! */
 
2112
        assert(size_w == ABS(Py_SIZE(w))); /* That's how d was calculated */
 
2113
 
 
2114
        size_v = ABS(Py_SIZE(v));
 
2115
        k = size_v - size_w;
 
2116
        a = _PyLong_New(k + 1);
 
2117
 
 
2118
        for (j = size_v; a != NULL && k >= 0; --j, --k) {
 
2119
                digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
 
2120
                twodigits q;
 
2121
                stwodigits carry = 0;
 
2122
                Py_ssize_t i;
 
2123
 
 
2124
                SIGCHECK({
 
2125
                        Py_DECREF(a);
 
2126
                        a = NULL;
 
2127
                        break;
 
2128
                })
 
2129
                if (vj == w->ob_digit[size_w-1])
 
2130
                        q = PyLong_MASK;
 
2131
                else
 
2132
                        q = (((twodigits)vj << PyLong_SHIFT) + v->ob_digit[j-1]) /
 
2133
                                w->ob_digit[size_w-1];
 
2134
 
 
2135
                while (w->ob_digit[size_w-2]*q >
 
2136
                                ((
 
2137
                                        ((twodigits)vj << PyLong_SHIFT)
 
2138
                                        + v->ob_digit[j-1]
 
2139
                                        - q*w->ob_digit[size_w-1]
 
2140
                                                                ) << PyLong_SHIFT)
 
2141
                                + v->ob_digit[j-2])
 
2142
                        --q;
 
2143
 
 
2144
                for (i = 0; i < size_w && i+k < size_v; ++i) {
 
2145
                        twodigits z = w->ob_digit[i] * q;
 
2146
                        digit zz = (digit) (z >> PyLong_SHIFT);
 
2147
                        carry += v->ob_digit[i+k] - z
 
2148
                                + ((twodigits)zz << PyLong_SHIFT);
 
2149
                        v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
 
2150
                        carry = Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
 
2151
                                                          carry, PyLong_SHIFT);
 
2152
                        carry -= zz;
 
2153
                }
 
2154
 
 
2155
                if (i+k < size_v) {
 
2156
                        carry += v->ob_digit[i+k];
 
2157
                        v->ob_digit[i+k] = 0;
 
2158
                }
 
2159
 
 
2160
                if (carry == 0)
 
2161
                        a->ob_digit[k] = (digit) q;
 
2162
                else {
 
2163
                        assert(carry == -1);
 
2164
                        a->ob_digit[k] = (digit) q-1;
 
2165
                        carry = 0;
 
2166
                        for (i = 0; i < size_w && i+k < size_v; ++i) {
 
2167
                                carry += v->ob_digit[i+k] + w->ob_digit[i];
 
2168
                                v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
 
2169
                                carry = Py_ARITHMETIC_RIGHT_SHIFT(
 
2170
                                                stwodigits,
 
2171
                                                carry, PyLong_SHIFT);
 
2172
                        }
 
2173
                }
 
2174
        } /* for j, k */
 
2175
 
 
2176
        if (a == NULL)
 
2177
                *prem = NULL;
 
2178
        else {
 
2179
                a = long_normalize(a);
 
2180
                *prem = divrem1(v, d, &d);
 
2181
                /* d receives the (unused) remainder */
 
2182
                if (*prem == NULL) {
 
2183
                        Py_DECREF(a);
 
2184
                        a = NULL;
 
2185
                }
 
2186
        }
 
2187
        Py_DECREF(v);
 
2188
        Py_DECREF(w);
 
2189
        return a;
 
2190
}
 
2191
 
 
2192
/* Methods */
 
2193
 
 
2194
static void
 
2195
long_dealloc(PyObject *v)
 
2196
{
 
2197
        Py_TYPE(v)->tp_free(v);
 
2198
}
 
2199
 
 
2200
static PyObject *
 
2201
long_repr(PyObject *v)
 
2202
{
 
2203
        return _PyLong_Format(v, 10);
 
2204
}
 
2205
 
 
2206
static int
 
2207
long_compare(PyLongObject *a, PyLongObject *b)
 
2208
{
 
2209
        Py_ssize_t sign;
 
2210
 
 
2211
        if (Py_SIZE(a) != Py_SIZE(b)) {
 
2212
                if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0)
 
2213
                        sign = 0;
 
2214
                else
 
2215
                        sign = Py_SIZE(a) - Py_SIZE(b);
 
2216
        }
 
2217
        else {
 
2218
                Py_ssize_t i = ABS(Py_SIZE(a));
 
2219
                while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
 
2220
                        ;
 
2221
                if (i < 0)
 
2222
                        sign = 0;
 
2223
                else {
 
2224
                        sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
 
2225
                        if (Py_SIZE(a) < 0)
 
2226
                                sign = -sign;
 
2227
                }
 
2228
        }
 
2229
        return sign < 0 ? -1 : sign > 0 ? 1 : 0;
 
2230
}
 
2231
 
 
2232
#define TEST_COND(cond) \
 
2233
        ((cond) ? Py_True : Py_False)
 
2234
 
 
2235
static PyObject *
 
2236
long_richcompare(PyObject *self, PyObject *other, int op)
 
2237
{
 
2238
        int result;
 
2239
        PyObject *v;
 
2240
        CHECK_BINOP(self, other);
 
2241
        if (self == other)
 
2242
                result = 0;
 
2243
        else
 
2244
                result = long_compare((PyLongObject*)self, (PyLongObject*)other);
 
2245
        /* Convert the return value to a Boolean */
 
2246
        switch (op) {
 
2247
        case Py_EQ:
 
2248
                v = TEST_COND(result == 0);
 
2249
                break;
 
2250
        case Py_NE:
 
2251
                v = TEST_COND(result != 0);
 
2252
                break;
 
2253
        case Py_LE:
 
2254
                v = TEST_COND(result <= 0);
 
2255
                break;
 
2256
        case Py_GE:
 
2257
                v = TEST_COND(result >= 0);
 
2258
                break;
 
2259
        case Py_LT:
 
2260
                v = TEST_COND(result == -1);
 
2261
                break;
 
2262
        case Py_GT:
 
2263
                v = TEST_COND(result == 1);
 
2264
                break;
 
2265
        default:
 
2266
                PyErr_BadArgument();
 
2267
                return NULL;
 
2268
        }
 
2269
        Py_INCREF(v);
 
2270
        return v;
 
2271
}
 
2272
 
 
2273
static long
 
2274
long_hash(PyLongObject *v)
 
2275
{
 
2276
        unsigned long x;
 
2277
        Py_ssize_t i;
 
2278
        int sign;
 
2279
 
 
2280
        /* This is designed so that Python ints and longs with the
 
2281
           same value hash to the same value, otherwise comparisons
 
2282
           of mapping keys will turn out weird */
 
2283
        i = Py_SIZE(v);
 
2284
        switch(i) {
 
2285
        case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
 
2286
        case 0: return 0;
 
2287
        case 1: return v->ob_digit[0];
 
2288
        }
 
2289
        sign = 1;
 
2290
        x = 0;
 
2291
        if (i < 0) {
 
2292
                sign = -1;
 
2293
                i = -(i);
 
2294
        }
 
2295
        /* The following loop produces a C unsigned long x such that x is
 
2296
           congruent to the absolute value of v modulo ULONG_MAX.  The
 
2297
           resulting x is nonzero if and only if v is. */
 
2298
        while (--i >= 0) {
 
2299
                /* Force a native long #-bits (32 or 64) circular shift */
 
2300
                x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT);
 
2301
                x += v->ob_digit[i];
 
2302
                /* If the addition above overflowed we compensate by
 
2303
                   incrementing.  This preserves the value modulo
 
2304
                   ULONG_MAX. */
 
2305
                if (x < v->ob_digit[i])
 
2306
                        x++;
 
2307
        }
 
2308
        x = x * sign;
 
2309
        if (x == (unsigned long)-1)
 
2310
                x = (unsigned long)-2;
 
2311
        return (long)x;
 
2312
}
 
2313
 
 
2314
 
 
2315
/* Add the absolute values of two long integers. */
 
2316
 
 
2317
static PyLongObject *
 
2318
x_add(PyLongObject *a, PyLongObject *b)
 
2319
{
 
2320
        Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
 
2321
        PyLongObject *z;
 
2322
        Py_ssize_t i;
 
2323
        digit carry = 0;
 
2324
 
 
2325
        /* Ensure a is the larger of the two: */
 
2326
        if (size_a < size_b) {
 
2327
                { PyLongObject *temp = a; a = b; b = temp; }
 
2328
                { Py_ssize_t size_temp = size_a;
 
2329
                  size_a = size_b;
 
2330
                  size_b = size_temp; }
 
2331
        }
 
2332
        z = _PyLong_New(size_a+1);
 
2333
        if (z == NULL)
 
2334
                return NULL;
 
2335
        for (i = 0; i < size_b; ++i) {
 
2336
                carry += a->ob_digit[i] + b->ob_digit[i];
 
2337
                z->ob_digit[i] = carry & PyLong_MASK;
 
2338
                carry >>= PyLong_SHIFT;
 
2339
        }
 
2340
        for (; i < size_a; ++i) {
 
2341
                carry += a->ob_digit[i];
 
2342
                z->ob_digit[i] = carry & PyLong_MASK;
 
2343
                carry >>= PyLong_SHIFT;
 
2344
        }
 
2345
        z->ob_digit[i] = carry;
 
2346
        return long_normalize(z);
 
2347
}
 
2348
 
 
2349
/* Subtract the absolute values of two integers. */
 
2350
 
 
2351
static PyLongObject *
 
2352
x_sub(PyLongObject *a, PyLongObject *b)
 
2353
{
 
2354
        Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
 
2355
        PyLongObject *z;
 
2356
        Py_ssize_t i;
 
2357
        int sign = 1;
 
2358
        digit borrow = 0;
 
2359
 
 
2360
        /* Ensure a is the larger of the two: */
 
2361
        if (size_a < size_b) {
 
2362
                sign = -1;
 
2363
                { PyLongObject *temp = a; a = b; b = temp; }
 
2364
                { Py_ssize_t size_temp = size_a;
 
2365
                  size_a = size_b;
 
2366
                  size_b = size_temp; }
 
2367
        }
 
2368
        else if (size_a == size_b) {
 
2369
                /* Find highest digit where a and b differ: */
 
2370
                i = size_a;
 
2371
                while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
 
2372
                        ;
 
2373
                if (i < 0)
 
2374
                        return (PyLongObject *)PyLong_FromLong(0);
 
2375
                if (a->ob_digit[i] < b->ob_digit[i]) {
 
2376
                        sign = -1;
 
2377
                        { PyLongObject *temp = a; a = b; b = temp; }
 
2378
                }
 
2379
                size_a = size_b = i+1;
 
2380
        }
 
2381
        z = _PyLong_New(size_a);
 
2382
        if (z == NULL)
 
2383
                return NULL;
 
2384
        for (i = 0; i < size_b; ++i) {
 
2385
                /* The following assumes unsigned arithmetic
 
2386
                   works module 2**N for some N>PyLong_SHIFT. */
 
2387
                borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
 
2388
                z->ob_digit[i] = borrow & PyLong_MASK;
 
2389
                borrow >>= PyLong_SHIFT;
 
2390
                borrow &= 1; /* Keep only one sign bit */
 
2391
        }
 
2392
        for (; i < size_a; ++i) {
 
2393
                borrow = a->ob_digit[i] - borrow;
 
2394
                z->ob_digit[i] = borrow & PyLong_MASK;
 
2395
                borrow >>= PyLong_SHIFT;
 
2396
                borrow &= 1; /* Keep only one sign bit */
 
2397
        }
 
2398
        assert(borrow == 0);
 
2399
        if (sign < 0)
 
2400
                NEGATE(z);
 
2401
        return long_normalize(z);
 
2402
}
 
2403
 
 
2404
static PyObject *
 
2405
long_add(PyLongObject *a, PyLongObject *b)
 
2406
{
 
2407
        PyLongObject *z;
 
2408
 
 
2409
        CHECK_BINOP(a, b);
 
2410
 
 
2411
        if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
 
2412
                PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
 
2413
                                                  MEDIUM_VALUE(b));
 
2414
                return result;
 
2415
        }
 
2416
        if (Py_SIZE(a) < 0) {
 
2417
                if (Py_SIZE(b) < 0) {
 
2418
                        z = x_add(a, b);
 
2419
                        if (z != NULL && Py_SIZE(z) != 0)
 
2420
                                Py_SIZE(z) = -(Py_SIZE(z));
 
2421
                }
 
2422
                else
 
2423
                        z = x_sub(b, a);
 
2424
        }
 
2425
        else {
 
2426
                if (Py_SIZE(b) < 0)
 
2427
                        z = x_sub(a, b);
 
2428
                else
 
2429
                        z = x_add(a, b);
 
2430
        }
 
2431
        return (PyObject *)z;
 
2432
}
 
2433
 
 
2434
static PyObject *
 
2435
long_sub(PyLongObject *a, PyLongObject *b)
 
2436
{
 
2437
        PyLongObject *z;
 
2438
 
 
2439
        CHECK_BINOP(a, b);
 
2440
 
 
2441
        if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
 
2442
                PyObject* r;
 
2443
                r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
 
2444
                return r;
 
2445
        }
 
2446
        if (Py_SIZE(a) < 0) {
 
2447
                if (Py_SIZE(b) < 0)
 
2448
                        z = x_sub(a, b);
 
2449
                else
 
2450
                        z = x_add(a, b);
 
2451
                if (z != NULL && Py_SIZE(z) != 0)
 
2452
                        Py_SIZE(z) = -(Py_SIZE(z));
 
2453
        }
 
2454
        else {
 
2455
                if (Py_SIZE(b) < 0)
 
2456
                        z = x_add(a, b);
 
2457
                else
 
2458
                        z = x_sub(a, b);
 
2459
        }
 
2460
        return (PyObject *)z;
 
2461
}
 
2462
 
 
2463
/* Grade school multiplication, ignoring the signs.
 
2464
 * Returns the absolute value of the product, or NULL if error.
 
2465
 */
 
2466
static PyLongObject *
 
2467
x_mul(PyLongObject *a, PyLongObject *b)
 
2468
{
 
2469
        PyLongObject *z;
 
2470
        Py_ssize_t size_a = ABS(Py_SIZE(a));
 
2471
        Py_ssize_t size_b = ABS(Py_SIZE(b));
 
2472
        Py_ssize_t i;
 
2473
 
 
2474
        z = _PyLong_New(size_a + size_b);
 
2475
        if (z == NULL)
 
2476
                return NULL;
 
2477
 
 
2478
        memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
 
2479
        if (a == b) {
 
2480
                /* Efficient squaring per HAC, Algorithm 14.16:
 
2481
                 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
 
2482
                 * Gives slightly less than a 2x speedup when a == b,
 
2483
                 * via exploiting that each entry in the multiplication
 
2484
                 * pyramid appears twice (except for the size_a squares).
 
2485
                 */
 
2486
                for (i = 0; i < size_a; ++i) {
 
2487
                        twodigits carry;
 
2488
                        twodigits f = a->ob_digit[i];
 
2489
                        digit *pz = z->ob_digit + (i << 1);
 
2490
                        digit *pa = a->ob_digit + i + 1;
 
2491
                        digit *paend = a->ob_digit + size_a;
 
2492
 
 
2493
                        SIGCHECK({
 
2494
                                Py_DECREF(z);
 
2495
                                return NULL;
 
2496
                        })
 
2497
 
 
2498
                        carry = *pz + f * f;
 
2499
                        *pz++ = (digit)(carry & PyLong_MASK);
 
2500
                        carry >>= PyLong_SHIFT;
 
2501
                        assert(carry <= PyLong_MASK);
 
2502
 
 
2503
                        /* Now f is added in twice in each column of the
 
2504
                         * pyramid it appears.  Same as adding f<<1 once.
 
2505
                         */
 
2506
                        f <<= 1;
 
2507
                        while (pa < paend) {
 
2508
                                carry += *pz + *pa++ * f;
 
2509
                                *pz++ = (digit)(carry & PyLong_MASK);
 
2510
                                carry >>= PyLong_SHIFT;
 
2511
                                assert(carry <= (PyLong_MASK << 1));
 
2512
                        }
 
2513
                        if (carry) {
 
2514
                                carry += *pz;
 
2515
                                *pz++ = (digit)(carry & PyLong_MASK);
 
2516
                                carry >>= PyLong_SHIFT;
 
2517
                        }
 
2518
                        if (carry)
 
2519
                                *pz += (digit)(carry & PyLong_MASK);
 
2520
                        assert((carry >> PyLong_SHIFT) == 0);
 
2521
                }
 
2522
        }
 
2523
        else {  /* a is not the same as b -- gradeschool long mult */
 
2524
                for (i = 0; i < size_a; ++i) {
 
2525
                        twodigits carry = 0;
 
2526
                        twodigits f = a->ob_digit[i];
 
2527
                        digit *pz = z->ob_digit + i;
 
2528
                        digit *pb = b->ob_digit;
 
2529
                        digit *pbend = b->ob_digit + size_b;
 
2530
 
 
2531
                        SIGCHECK({
 
2532
                                Py_DECREF(z);
 
2533
                                return NULL;
 
2534
                        })
 
2535
 
 
2536
                        while (pb < pbend) {
 
2537
                                carry += *pz + *pb++ * f;
 
2538
                                *pz++ = (digit)(carry & PyLong_MASK);
 
2539
                                carry >>= PyLong_SHIFT;
 
2540
                                assert(carry <= PyLong_MASK);
 
2541
                        }
 
2542
                        if (carry)
 
2543
                                *pz += (digit)(carry & PyLong_MASK);
 
2544
                        assert((carry >> PyLong_SHIFT) == 0);
 
2545
                }
 
2546
        }
 
2547
        return long_normalize(z);
 
2548
}
 
2549
 
 
2550
/* A helper for Karatsuba multiplication (k_mul).
 
2551
   Takes a long "n" and an integer "size" representing the place to
 
2552
   split, and sets low and high such that abs(n) == (high << size) + low,
 
2553
   viewing the shift as being by digits.  The sign bit is ignored, and
 
2554
   the return values are >= 0.
 
2555
   Returns 0 on success, -1 on failure.
 
2556
*/
 
2557
static int
 
2558
kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
 
2559
{
 
2560
        PyLongObject *hi, *lo;
 
2561
        Py_ssize_t size_lo, size_hi;
 
2562
        const Py_ssize_t size_n = ABS(Py_SIZE(n));
 
2563
 
 
2564
        size_lo = MIN(size_n, size);
 
2565
        size_hi = size_n - size_lo;
 
2566
 
 
2567
        if ((hi = _PyLong_New(size_hi)) == NULL)
 
2568
                return -1;
 
2569
        if ((lo = _PyLong_New(size_lo)) == NULL) {
 
2570
                Py_DECREF(hi);
 
2571
                return -1;
 
2572
        }
 
2573
 
 
2574
        memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
 
2575
        memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
 
2576
 
 
2577
        *high = long_normalize(hi);
 
2578
        *low = long_normalize(lo);
 
2579
        return 0;
 
2580
}
 
2581
 
 
2582
static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
 
2583
 
 
2584
/* Karatsuba multiplication.  Ignores the input signs, and returns the
 
2585
 * absolute value of the product (or NULL if error).
 
2586
 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
 
2587
 */
 
2588
static PyLongObject *
 
2589
k_mul(PyLongObject *a, PyLongObject *b)
 
2590
{
 
2591
        Py_ssize_t asize = ABS(Py_SIZE(a));
 
2592
        Py_ssize_t bsize = ABS(Py_SIZE(b));
 
2593
        PyLongObject *ah = NULL;
 
2594
        PyLongObject *al = NULL;
 
2595
        PyLongObject *bh = NULL;
 
2596
        PyLongObject *bl = NULL;
 
2597
        PyLongObject *ret = NULL;
 
2598
        PyLongObject *t1, *t2, *t3;
 
2599
        Py_ssize_t shift;       /* the number of digits we split off */
 
2600
        Py_ssize_t i;
 
2601
 
 
2602
        /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
 
2603
         * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh  + ah*bh + al*bl
 
2604
         * Then the original product is
 
2605
         *     ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
 
2606
         * By picking X to be a power of 2, "*X" is just shifting, and it's
 
2607
         * been reduced to 3 multiplies on numbers half the size.
 
2608
         */
 
2609
 
 
2610
        /* We want to split based on the larger number; fiddle so that b
 
2611
         * is largest.
 
2612
         */
 
2613
        if (asize > bsize) {
 
2614
                t1 = a;
 
2615
                a = b;
 
2616
                b = t1;
 
2617
 
 
2618
                i = asize;
 
2619
                asize = bsize;
 
2620
                bsize = i;
 
2621
        }
 
2622
 
 
2623
        /* Use gradeschool math when either number is too small. */
 
2624
        i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
 
2625
        if (asize <= i) {
 
2626
                if (asize == 0)
 
2627
                        return (PyLongObject *)PyLong_FromLong(0);
 
2628
                else
 
2629
                        return x_mul(a, b);
 
2630
        }
 
2631
 
 
2632
        /* If a is small compared to b, splitting on b gives a degenerate
 
2633
         * case with ah==0, and Karatsuba may be (even much) less efficient
 
2634
         * than "grade school" then.  However, we can still win, by viewing
 
2635
         * b as a string of "big digits", each of width a->ob_size.  That
 
2636
         * leads to a sequence of balanced calls to k_mul.
 
2637
         */
 
2638
        if (2 * asize <= bsize)
 
2639
                return k_lopsided_mul(a, b);
 
2640
 
 
2641
        /* Split a & b into hi & lo pieces. */
 
2642
        shift = bsize >> 1;
 
2643
        if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
 
2644
        assert(Py_SIZE(ah) > 0);        /* the split isn't degenerate */
 
2645
 
 
2646
        if (a == b) {
 
2647
                bh = ah;
 
2648
                bl = al;
 
2649
                Py_INCREF(bh);
 
2650
                Py_INCREF(bl);
 
2651
        }
 
2652
        else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
 
2653
 
 
2654
        /* The plan:
 
2655
         * 1. Allocate result space (asize + bsize digits:  that's always
 
2656
         *    enough).
 
2657
         * 2. Compute ah*bh, and copy into result at 2*shift.
 
2658
         * 3. Compute al*bl, and copy into result at 0.  Note that this
 
2659
         *    can't overlap with #2.
 
2660
         * 4. Subtract al*bl from the result, starting at shift.  This may
 
2661
         *    underflow (borrow out of the high digit), but we don't care:
 
2662
         *    we're effectively doing unsigned arithmetic mod
 
2663
         *    BASE**(sizea + sizeb), and so long as the *final* result fits,
 
2664
         *    borrows and carries out of the high digit can be ignored.
 
2665
         * 5. Subtract ah*bh from the result, starting at shift.
 
2666
         * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
 
2667
         *    at shift.
 
2668
         */
 
2669
 
 
2670
        /* 1. Allocate result space. */
 
2671
        ret = _PyLong_New(asize + bsize);
 
2672
        if (ret == NULL) goto fail;
 
2673
#ifdef Py_DEBUG
 
2674
        /* Fill with trash, to catch reference to uninitialized digits. */
 
2675
        memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
 
2676
#endif
 
2677
 
 
2678
        /* 2. t1 <- ah*bh, and copy into high digits of result. */
 
2679
        if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
 
2680
        assert(Py_SIZE(t1) >= 0);
 
2681
        assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
 
2682
        memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
 
2683
               Py_SIZE(t1) * sizeof(digit));
 
2684
 
 
2685
        /* Zero-out the digits higher than the ah*bh copy. */
 
2686
        i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
 
2687
        if (i)
 
2688
                memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
 
2689
                       i * sizeof(digit));
 
2690
 
 
2691
        /* 3. t2 <- al*bl, and copy into the low digits. */
 
2692
        if ((t2 = k_mul(al, bl)) == NULL) {
 
2693
                Py_DECREF(t1);
 
2694
                goto fail;
 
2695
        }
 
2696
        assert(Py_SIZE(t2) >= 0);
 
2697
        assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
 
2698
        memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
 
2699
 
 
2700
        /* Zero out remaining digits. */
 
2701
        i = 2*shift - Py_SIZE(t2);      /* number of uninitialized digits */
 
2702
        if (i)
 
2703
                memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
 
2704
 
 
2705
        /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2).  We do al*bl first
 
2706
         * because it's fresher in cache.
 
2707
         */
 
2708
        i = Py_SIZE(ret) - shift;  /* # digits after shift */
 
2709
        (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
 
2710
        Py_DECREF(t2);
 
2711
 
 
2712
        (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
 
2713
        Py_DECREF(t1);
 
2714
 
 
2715
        /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
 
2716
        if ((t1 = x_add(ah, al)) == NULL) goto fail;
 
2717
        Py_DECREF(ah);
 
2718
        Py_DECREF(al);
 
2719
        ah = al = NULL;
 
2720
 
 
2721
        if (a == b) {
 
2722
                t2 = t1;
 
2723
                Py_INCREF(t2);
 
2724
        }
 
2725
        else if ((t2 = x_add(bh, bl)) == NULL) {
 
2726
                Py_DECREF(t1);
 
2727
                goto fail;
 
2728
        }
 
2729
        Py_DECREF(bh);
 
2730
        Py_DECREF(bl);
 
2731
        bh = bl = NULL;
 
2732
 
 
2733
        t3 = k_mul(t1, t2);
 
2734
        Py_DECREF(t1);
 
2735
        Py_DECREF(t2);
 
2736
        if (t3 == NULL) goto fail;
 
2737
        assert(Py_SIZE(t3) >= 0);
 
2738
 
 
2739
        /* Add t3.  It's not obvious why we can't run out of room here.
 
2740
         * See the (*) comment after this function.
 
2741
         */
 
2742
        (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
 
2743
        Py_DECREF(t3);
 
2744
 
 
2745
        return long_normalize(ret);
 
2746
 
 
2747
 fail:
 
2748
        Py_XDECREF(ret);
 
2749
        Py_XDECREF(ah);
 
2750
        Py_XDECREF(al);
 
2751
        Py_XDECREF(bh);
 
2752
        Py_XDECREF(bl);
 
2753
        return NULL;
 
2754
}
 
2755
 
 
2756
/* (*) Why adding t3 can't "run out of room" above.
 
2757
 
 
2758
Let f(x) mean the floor of x and c(x) mean the ceiling of x.  Some facts
 
2759
to start with:
 
2760
 
 
2761
1. For any integer i, i = c(i/2) + f(i/2).  In particular,
 
2762
   bsize = c(bsize/2) + f(bsize/2).
 
2763
2. shift = f(bsize/2)
 
2764
3. asize <= bsize
 
2765
4. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
 
2766
   routine, so asize > bsize/2 >= f(bsize/2) in this routine.
 
2767
 
 
2768
We allocated asize + bsize result digits, and add t3 into them at an offset
 
2769
of shift.  This leaves asize+bsize-shift allocated digit positions for t3
 
2770
to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
 
2771
asize + c(bsize/2) available digit positions.
 
2772
 
 
2773
bh has c(bsize/2) digits, and bl at most f(size/2) digits.  So bh+hl has
 
2774
at most c(bsize/2) digits + 1 bit.
 
2775
 
 
2776
If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
 
2777
digits, and al has at most f(bsize/2) digits in any case.  So ah+al has at
 
2778
most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
 
2779
 
 
2780
The product (ah+al)*(bh+bl) therefore has at most
 
2781
 
 
2782
    c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
 
2783
 
 
2784
and we have asize + c(bsize/2) available digit positions.  We need to show
 
2785
this is always enough.  An instance of c(bsize/2) cancels out in both, so
 
2786
the question reduces to whether asize digits is enough to hold
 
2787
(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits.  If asize < bsize,
 
2788
then we're asking whether asize digits >= f(bsize/2) digits + 2 bits.  By #4,
 
2789
asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
 
2790
digit is enough to hold 2 bits.  This is so since PyLong_SHIFT=15 >= 2.  If
 
2791
asize == bsize, then we're asking whether bsize digits is enough to hold
 
2792
c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
 
2793
is enough to hold 2 bits.  This is so if bsize >= 2, which holds because
 
2794
bsize >= KARATSUBA_CUTOFF >= 2.
 
2795
 
 
2796
Note that since there's always enough room for (ah+al)*(bh+bl), and that's
 
2797
clearly >= each of ah*bh and al*bl, there's always enough room to subtract
 
2798
ah*bh and al*bl too.
 
2799
*/
 
2800
 
 
2801
/* b has at least twice the digits of a, and a is big enough that Karatsuba
 
2802
 * would pay off *if* the inputs had balanced sizes.  View b as a sequence
 
2803
 * of slices, each with a->ob_size digits, and multiply the slices by a,
 
2804
 * one at a time.  This gives k_mul balanced inputs to work with, and is
 
2805
 * also cache-friendly (we compute one double-width slice of the result
 
2806
 * at a time, then move on, never bactracking except for the helpful
 
2807
 * single-width slice overlap between successive partial sums).
 
2808
 */
 
2809
static PyLongObject *
 
2810
k_lopsided_mul(PyLongObject *a, PyLongObject *b)
 
2811
{
 
2812
        const Py_ssize_t asize = ABS(Py_SIZE(a));
 
2813
        Py_ssize_t bsize = ABS(Py_SIZE(b));
 
2814
        Py_ssize_t nbdone;      /* # of b digits already multiplied */
 
2815
        PyLongObject *ret;
 
2816
        PyLongObject *bslice = NULL;
 
2817
 
 
2818
        assert(asize > KARATSUBA_CUTOFF);
 
2819
        assert(2 * asize <= bsize);
 
2820
 
 
2821
        /* Allocate result space, and zero it out. */
 
2822
        ret = _PyLong_New(asize + bsize);
 
2823
        if (ret == NULL)
 
2824
                return NULL;
 
2825
        memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
 
2826
 
 
2827
        /* Successive slices of b are copied into bslice. */
 
2828
        bslice = _PyLong_New(asize);
 
2829
        if (bslice == NULL)
 
2830
                goto fail;
 
2831
 
 
2832
        nbdone = 0;
 
2833
        while (bsize > 0) {
 
2834
                PyLongObject *product;
 
2835
                const Py_ssize_t nbtouse = MIN(bsize, asize);
 
2836
 
 
2837
                /* Multiply the next slice of b by a. */
 
2838
                memcpy(bslice->ob_digit, b->ob_digit + nbdone,
 
2839
                       nbtouse * sizeof(digit));
 
2840
                Py_SIZE(bslice) = nbtouse;
 
2841
                product = k_mul(a, bslice);
 
2842
                if (product == NULL)
 
2843
                        goto fail;
 
2844
 
 
2845
                /* Add into result. */
 
2846
                (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
 
2847
                             product->ob_digit, Py_SIZE(product));
 
2848
                Py_DECREF(product);
 
2849
 
 
2850
                bsize -= nbtouse;
 
2851
                nbdone += nbtouse;
 
2852
        }
 
2853
 
 
2854
        Py_DECREF(bslice);
 
2855
        return long_normalize(ret);
 
2856
 
 
2857
 fail:
 
2858
        Py_DECREF(ret);
 
2859
        Py_XDECREF(bslice);
 
2860
        return NULL;
 
2861
}
 
2862
 
 
2863
static PyObject *
 
2864
long_mul(PyLongObject *a, PyLongObject *b)
 
2865
{
 
2866
        PyLongObject *z;
 
2867
 
 
2868
        CHECK_BINOP(a, b);
 
2869
 
 
2870
        /* fast path for single-digit multiplication */
 
2871
        if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
 
2872
                stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
 
2873
#ifdef HAVE_LONG_LONG
 
2874
                return PyLong_FromLongLong((PY_LONG_LONG)v);
 
2875
#else
 
2876
                /* if we don't have long long then we're almost certainly
 
2877
                   using 15-bit digits, so v will fit in a long.  In the
 
2878
                   unlikely event that we're using 30-bit digits on a platform
 
2879
                   without long long, a large v will just cause us to fall
 
2880
                   through to the general multiplication code below. */
 
2881
                if (v >= LONG_MIN && v <= LONG_MAX)
 
2882
                        return PyLong_FromLong((long)v);
 
2883
#endif
 
2884
        }
 
2885
 
 
2886
        z = k_mul(a, b);
 
2887
        /* Negate if exactly one of the inputs is negative. */
 
2888
        if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
 
2889
                NEGATE(z);
 
2890
        return (PyObject *)z;
 
2891
}
 
2892
 
 
2893
/* The / and % operators are now defined in terms of divmod().
 
2894
   The expression a mod b has the value a - b*floor(a/b).
 
2895
   The long_divrem function gives the remainder after division of
 
2896
   |a| by |b|, with the sign of a.  This is also expressed
 
2897
   as a - b*trunc(a/b), if trunc truncates towards zero.
 
2898
   Some examples:
 
2899
         a       b      a rem b         a mod b
 
2900
         13      10      3               3
 
2901
        -13      10     -3               7
 
2902
         13     -10      3              -7
 
2903
        -13     -10     -3              -3
 
2904
   So, to get from rem to mod, we have to add b if a and b
 
2905
   have different signs.  We then subtract one from the 'div'
 
2906
   part of the outcome to keep the invariant intact. */
 
2907
 
 
2908
/* Compute
 
2909
 *     *pdiv, *pmod = divmod(v, w)
 
2910
 * NULL can be passed for pdiv or pmod, in which case that part of
 
2911
 * the result is simply thrown away.  The caller owns a reference to
 
2912
 * each of these it requests (does not pass NULL for).
 
2913
 */
 
2914
static int
 
2915
l_divmod(PyLongObject *v, PyLongObject *w,
 
2916
         PyLongObject **pdiv, PyLongObject **pmod)
 
2917
{
 
2918
        PyLongObject *div, *mod;
 
2919
 
 
2920
        if (long_divrem(v, w, &div, &mod) < 0)
 
2921
                return -1;
 
2922
        if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
 
2923
            (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
 
2924
                PyLongObject *temp;
 
2925
                PyLongObject *one;
 
2926
                temp = (PyLongObject *) long_add(mod, w);
 
2927
                Py_DECREF(mod);
 
2928
                mod = temp;
 
2929
                if (mod == NULL) {
 
2930
                        Py_DECREF(div);
 
2931
                        return -1;
 
2932
                }
 
2933
                one = (PyLongObject *) PyLong_FromLong(1L);
 
2934
                if (one == NULL ||
 
2935
                    (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
 
2936
                        Py_DECREF(mod);
 
2937
                        Py_DECREF(div);
 
2938
                        Py_XDECREF(one);
 
2939
                        return -1;
 
2940
                }
 
2941
                Py_DECREF(one);
 
2942
                Py_DECREF(div);
 
2943
                div = temp;
 
2944
        }
 
2945
        if (pdiv != NULL)
 
2946
                *pdiv = div;
 
2947
        else
 
2948
                Py_DECREF(div);
 
2949
 
 
2950
        if (pmod != NULL)
 
2951
                *pmod = mod;
 
2952
        else
 
2953
                Py_DECREF(mod);
 
2954
 
 
2955
        return 0;
 
2956
}
 
2957
 
 
2958
static PyObject *
 
2959
long_div(PyObject *a, PyObject *b)
 
2960
{
 
2961
        PyLongObject *div;
 
2962
 
 
2963
        CHECK_BINOP(a, b);
 
2964
        if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
 
2965
                div = NULL;
 
2966
        return (PyObject *)div;
 
2967
}
 
2968
 
 
2969
static PyObject *
 
2970
long_true_divide(PyObject *a, PyObject *b)
 
2971
{
 
2972
        double ad, bd;
 
2973
        int failed, aexp = -1, bexp = -1;
 
2974
 
 
2975
        CHECK_BINOP(a, b);
 
2976
        ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
 
2977
        bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
 
2978
        failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
 
2979
        if (failed)
 
2980
                return NULL;
 
2981
        /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
 
2982
           but should really be set correctly after sucessful calls to
 
2983
           _PyLong_AsScaledDouble() */
 
2984
        assert(aexp >= 0 && bexp >= 0);
 
2985
 
 
2986
        if (bd == 0.0) {
 
2987
                PyErr_SetString(PyExc_ZeroDivisionError,
 
2988
                        "int division or modulo by zero");
 
2989
                return NULL;
 
2990
        }
 
2991
 
 
2992
        /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
 
2993
        ad /= bd;       /* overflow/underflow impossible here */
 
2994
        aexp -= bexp;
 
2995
        if (aexp > INT_MAX / PyLong_SHIFT)
 
2996
                goto overflow;
 
2997
        else if (aexp < -(INT_MAX / PyLong_SHIFT))
 
2998
                return PyFloat_FromDouble(0.0); /* underflow to 0 */
 
2999
        errno = 0;
 
3000
        ad = ldexp(ad, aexp * PyLong_SHIFT);
 
3001
        if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
 
3002
                goto overflow;
 
3003
        return PyFloat_FromDouble(ad);
 
3004
 
 
3005
overflow:
 
3006
        PyErr_SetString(PyExc_OverflowError,
 
3007
                "int/int too large for a float");
 
3008
        return NULL;
 
3009
 
 
3010
}
 
3011
 
 
3012
static PyObject *
 
3013
long_mod(PyObject *a, PyObject *b)
 
3014
{
 
3015
        PyLongObject *mod;
 
3016
        
 
3017
        CHECK_BINOP(a, b);
 
3018
 
 
3019
        if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
 
3020
                mod = NULL;
 
3021
        return (PyObject *)mod;
 
3022
}
 
3023
 
 
3024
static PyObject *
 
3025
long_divmod(PyObject *a, PyObject *b)
 
3026
{
 
3027
        PyLongObject *div, *mod;
 
3028
        PyObject *z;
 
3029
 
 
3030
        CHECK_BINOP(a, b);
 
3031
 
 
3032
        if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
 
3033
                return NULL;
 
3034
        }
 
3035
        z = PyTuple_New(2);
 
3036
        if (z != NULL) {
 
3037
                PyTuple_SetItem(z, 0, (PyObject *) div);
 
3038
                PyTuple_SetItem(z, 1, (PyObject *) mod);
 
3039
        }
 
3040
        else {
 
3041
                Py_DECREF(div);
 
3042
                Py_DECREF(mod);
 
3043
        }
 
3044
        return z;
 
3045
}
 
3046
 
 
3047
/* pow(v, w, x) */
 
3048
static PyObject *
 
3049
long_pow(PyObject *v, PyObject *w, PyObject *x)
 
3050
{
 
3051
        PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
 
3052
        int negativeOutput = 0;  /* if x<0 return negative output */
 
3053
 
 
3054
        PyLongObject *z = NULL;  /* accumulated result */
 
3055
        Py_ssize_t i, j, k;             /* counters */
 
3056
        PyLongObject *temp = NULL;
 
3057
 
 
3058
        /* 5-ary values.  If the exponent is large enough, table is
 
3059
         * precomputed so that table[i] == a**i % c for i in range(32).
 
3060
         */
 
3061
        PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
 
3062
                                   0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
 
3063
 
 
3064
        /* a, b, c = v, w, x */
 
3065
        CHECK_BINOP(v, w);
 
3066
        a = (PyLongObject*)v; Py_INCREF(a);
 
3067
        b = (PyLongObject*)w; Py_INCREF(b);
 
3068
        if (PyLong_Check(x)) {
 
3069
                c = (PyLongObject *)x;
 
3070
                Py_INCREF(x);
 
3071
        }
 
3072
        else if (x == Py_None)
 
3073
                c = NULL;
 
3074
        else {
 
3075
                Py_DECREF(a);
 
3076
                Py_DECREF(b);
 
3077
                Py_INCREF(Py_NotImplemented);
 
3078
                return Py_NotImplemented;
 
3079
        }
 
3080
 
 
3081
        if (Py_SIZE(b) < 0) {  /* if exponent is negative */
 
3082
                if (c) {
 
3083
                        PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
 
3084
                            "cannot be negative when 3rd argument specified");
 
3085
                        goto Error;
 
3086
                }
 
3087
                else {
 
3088
                        /* else return a float.  This works because we know
 
3089
                           that this calls float_pow() which converts its
 
3090
                           arguments to double. */
 
3091
                        Py_DECREF(a);
 
3092
                        Py_DECREF(b);
 
3093
                        return PyFloat_Type.tp_as_number->nb_power(v, w, x);
 
3094
                }
 
3095
        }
 
3096
 
 
3097
        if (c) {
 
3098
                /* if modulus == 0:
 
3099
                       raise ValueError() */
 
3100
                if (Py_SIZE(c) == 0) {
 
3101
                        PyErr_SetString(PyExc_ValueError,
 
3102
                                        "pow() 3rd argument cannot be 0");
 
3103
                        goto Error;
 
3104
                }
 
3105
 
 
3106
                /* if modulus < 0:
 
3107
                       negativeOutput = True
 
3108
                       modulus = -modulus */
 
3109
                if (Py_SIZE(c) < 0) {
 
3110
                        negativeOutput = 1;
 
3111
                        temp = (PyLongObject *)_PyLong_Copy(c);
 
3112
                        if (temp == NULL)
 
3113
                                goto Error;
 
3114
                        Py_DECREF(c);
 
3115
                        c = temp;
 
3116
                        temp = NULL;
 
3117
                        NEGATE(c);
 
3118
                }
 
3119
 
 
3120
                /* if modulus == 1:
 
3121
                       return 0 */
 
3122
                if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
 
3123
                        z = (PyLongObject *)PyLong_FromLong(0L);
 
3124
                        goto Done;
 
3125
                }
 
3126
 
 
3127
                /* if base < 0:
 
3128
                       base = base % modulus
 
3129
                   Having the base positive just makes things easier. */
 
3130
                if (Py_SIZE(a) < 0) {
 
3131
                        if (l_divmod(a, c, NULL, &temp) < 0)
 
3132
                                goto Error;
 
3133
                        Py_DECREF(a);
 
3134
                        a = temp;
 
3135
                        temp = NULL;
 
3136
                }
 
3137
        }
 
3138
 
 
3139
        /* At this point a, b, and c are guaranteed non-negative UNLESS
 
3140
           c is NULL, in which case a may be negative. */
 
3141
 
 
3142
        z = (PyLongObject *)PyLong_FromLong(1L);
 
3143
        if (z == NULL)
 
3144
                goto Error;
 
3145
 
 
3146
        /* Perform a modular reduction, X = X % c, but leave X alone if c
 
3147
         * is NULL.
 
3148
         */
 
3149
#define REDUCE(X)                                       \
 
3150
        if (c != NULL) {                                \
 
3151
                if (l_divmod(X, c, NULL, &temp) < 0)    \
 
3152
                        goto Error;                     \
 
3153
                Py_XDECREF(X);                          \
 
3154
                X = temp;                               \
 
3155
                temp = NULL;                            \
 
3156
        }
 
3157
 
 
3158
        /* Multiply two values, then reduce the result:
 
3159
           result = X*Y % c.  If c is NULL, skip the mod. */
 
3160
#define MULT(X, Y, result)                              \
 
3161
{                                                       \
 
3162
        temp = (PyLongObject *)long_mul(X, Y);          \
 
3163
        if (temp == NULL)                               \
 
3164
                goto Error;                             \
 
3165
        Py_XDECREF(result);                             \
 
3166
        result = temp;                                  \
 
3167
        temp = NULL;                                    \
 
3168
        REDUCE(result)                                  \
 
3169
}
 
3170
 
 
3171
        if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
 
3172
                /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
 
3173
                /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf    */
 
3174
                for (i = Py_SIZE(b) - 1; i >= 0; --i) {
 
3175
                        digit bi = b->ob_digit[i];
 
3176
 
 
3177
                        for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
 
3178
                                MULT(z, z, z)
 
3179
                                if (bi & j)
 
3180
                                        MULT(z, a, z)
 
3181
                        }
 
3182
                }
 
3183
        }
 
3184
        else {
 
3185
                /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
 
3186
                Py_INCREF(z);   /* still holds 1L */
 
3187
                table[0] = z;
 
3188
                for (i = 1; i < 32; ++i)
 
3189
                        MULT(table[i-1], a, table[i])
 
3190
 
 
3191
                for (i = Py_SIZE(b) - 1; i >= 0; --i) {
 
3192
                        const digit bi = b->ob_digit[i];
 
3193
 
 
3194
                        for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
 
3195
                                const int index = (bi >> j) & 0x1f;
 
3196
                                for (k = 0; k < 5; ++k)
 
3197
                                        MULT(z, z, z)
 
3198
                                if (index)
 
3199
                                        MULT(z, table[index], z)
 
3200
                        }
 
3201
                }
 
3202
        }
 
3203
 
 
3204
        if (negativeOutput && (Py_SIZE(z) != 0)) {
 
3205
                temp = (PyLongObject *)long_sub(z, c);
 
3206
                if (temp == NULL)
 
3207
                        goto Error;
 
3208
                Py_DECREF(z);
 
3209
                z = temp;
 
3210
                temp = NULL;
 
3211
        }
 
3212
        goto Done;
 
3213
 
 
3214
 Error:
 
3215
        if (z != NULL) {
 
3216
                Py_DECREF(z);
 
3217
                z = NULL;
 
3218
        }
 
3219
        /* fall through */
 
3220
 Done:
 
3221
        if (Py_SIZE(b) > FIVEARY_CUTOFF) {
 
3222
                for (i = 0; i < 32; ++i)
 
3223
                        Py_XDECREF(table[i]);
 
3224
        }
 
3225
        Py_DECREF(a);
 
3226
        Py_DECREF(b);
 
3227
        Py_XDECREF(c);
 
3228
        Py_XDECREF(temp);
 
3229
        return (PyObject *)z;
 
3230
}
 
3231
 
 
3232
static PyObject *
 
3233
long_invert(PyLongObject *v)
 
3234
{
 
3235
        /* Implement ~x as -(x+1) */
 
3236
        PyLongObject *x;
 
3237
        PyLongObject *w;
 
3238
        if (ABS(Py_SIZE(v)) <=1)
 
3239
                return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
 
3240
        w = (PyLongObject *)PyLong_FromLong(1L);
 
3241
        if (w == NULL)
 
3242
                return NULL;
 
3243
        x = (PyLongObject *) long_add(v, w);
 
3244
        Py_DECREF(w);
 
3245
        if (x == NULL)
 
3246
                return NULL;
 
3247
        Py_SIZE(x) = -(Py_SIZE(x));
 
3248
        return (PyObject *)maybe_small_long(x);
 
3249
}
 
3250
 
 
3251
static PyObject *
 
3252
long_neg(PyLongObject *v)
 
3253
{
 
3254
        PyLongObject *z;
 
3255
        if (ABS(Py_SIZE(v)) <= 1)
 
3256
                return PyLong_FromLong(-MEDIUM_VALUE(v));
 
3257
        z = (PyLongObject *)_PyLong_Copy(v);
 
3258
        if (z != NULL)
 
3259
                Py_SIZE(z) = -(Py_SIZE(v));
 
3260
        return (PyObject *)z;
 
3261
}
 
3262
 
 
3263
static PyObject *
 
3264
long_abs(PyLongObject *v)
 
3265
{
 
3266
        if (Py_SIZE(v) < 0)
 
3267
                return long_neg(v);
 
3268
        else
 
3269
                return long_long((PyObject *)v);
 
3270
}
 
3271
 
 
3272
static int
 
3273
long_bool(PyLongObject *v)
 
3274
{
 
3275
        return ABS(Py_SIZE(v)) != 0;
 
3276
}
 
3277
 
 
3278
static PyObject *
 
3279
long_rshift(PyLongObject *a, PyLongObject *b)
 
3280
{
 
3281
        PyLongObject *z = NULL;
 
3282
        long shiftby;
 
3283
        Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
 
3284
        digit lomask, himask;
 
3285
 
 
3286
        CHECK_BINOP(a, b);
 
3287
 
 
3288
        if (Py_SIZE(a) < 0) {
 
3289
                /* Right shifting negative numbers is harder */
 
3290
                PyLongObject *a1, *a2;
 
3291
                a1 = (PyLongObject *) long_invert(a);
 
3292
                if (a1 == NULL)
 
3293
                        goto rshift_error;
 
3294
                a2 = (PyLongObject *) long_rshift(a1, b);
 
3295
                Py_DECREF(a1);
 
3296
                if (a2 == NULL)
 
3297
                        goto rshift_error;
 
3298
                z = (PyLongObject *) long_invert(a2);
 
3299
                Py_DECREF(a2);
 
3300
        }
 
3301
        else {
 
3302
 
 
3303
                shiftby = PyLong_AsLong((PyObject *)b);
 
3304
                if (shiftby == -1L && PyErr_Occurred())
 
3305
                        goto rshift_error;
 
3306
                if (shiftby < 0) {
 
3307
                        PyErr_SetString(PyExc_ValueError,
 
3308
                                        "negative shift count");
 
3309
                        goto rshift_error;
 
3310
                }
 
3311
                wordshift = shiftby / PyLong_SHIFT;
 
3312
                newsize = ABS(Py_SIZE(a)) - wordshift;
 
3313
                if (newsize <= 0)
 
3314
                        return PyLong_FromLong(0);
 
3315
                loshift = shiftby % PyLong_SHIFT;
 
3316
                hishift = PyLong_SHIFT - loshift;
 
3317
                lomask = ((digit)1 << hishift) - 1;
 
3318
                himask = PyLong_MASK ^ lomask;
 
3319
                z = _PyLong_New(newsize);
 
3320
                if (z == NULL)
 
3321
                        goto rshift_error;
 
3322
                if (Py_SIZE(a) < 0)
 
3323
                        Py_SIZE(z) = -(Py_SIZE(z));
 
3324
                for (i = 0, j = wordshift; i < newsize; i++, j++) {
 
3325
                        z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
 
3326
                        if (i+1 < newsize)
 
3327
                                z->ob_digit[i] |=
 
3328
                                  (a->ob_digit[j+1] << hishift) & himask;
 
3329
                }
 
3330
                z = long_normalize(z);
 
3331
        }
 
3332
rshift_error:
 
3333
        return (PyObject *) maybe_small_long(z);
 
3334
 
 
3335
}
 
3336
 
 
3337
static PyObject *
 
3338
long_lshift(PyObject *v, PyObject *w)
 
3339
{
 
3340
        /* This version due to Tim Peters */
 
3341
        PyLongObject *a = (PyLongObject*)v;
 
3342
        PyLongObject *b = (PyLongObject*)w;
 
3343
        PyLongObject *z = NULL;
 
3344
        long shiftby;
 
3345
        Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
 
3346
        twodigits accum;
 
3347
 
 
3348
        CHECK_BINOP(a, b);
 
3349
 
 
3350
        shiftby = PyLong_AsLong((PyObject *)b);
 
3351
        if (shiftby == -1L && PyErr_Occurred())
 
3352
                goto lshift_error;
 
3353
        if (shiftby < 0) {
 
3354
                PyErr_SetString(PyExc_ValueError, "negative shift count");
 
3355
                goto lshift_error;
 
3356
        }
 
3357
        if ((long)(int)shiftby != shiftby) {
 
3358
                PyErr_SetString(PyExc_ValueError,
 
3359
                                "outrageous left shift count");
 
3360
                goto lshift_error;
 
3361
        }
 
3362
        /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
 
3363
        wordshift = (int)shiftby / PyLong_SHIFT;
 
3364
        remshift  = (int)shiftby - wordshift * PyLong_SHIFT;
 
3365
 
 
3366
        oldsize = ABS(Py_SIZE(a));
 
3367
        newsize = oldsize + wordshift;
 
3368
        if (remshift)
 
3369
                ++newsize;
 
3370
        z = _PyLong_New(newsize);
 
3371
        if (z == NULL)
 
3372
                goto lshift_error;
 
3373
        if (Py_SIZE(a) < 0)
 
3374
                NEGATE(z);
 
3375
        for (i = 0; i < wordshift; i++)
 
3376
                z->ob_digit[i] = 0;
 
3377
        accum = 0;
 
3378
        for (i = wordshift, j = 0; j < oldsize; i++, j++) {
 
3379
                accum |= (twodigits)a->ob_digit[j] << remshift;
 
3380
                z->ob_digit[i] = (digit)(accum & PyLong_MASK);
 
3381
                accum >>= PyLong_SHIFT;
 
3382
        }
 
3383
        if (remshift)
 
3384
                z->ob_digit[newsize-1] = (digit)accum;
 
3385
        else
 
3386
                assert(!accum);
 
3387
        z = long_normalize(z);
 
3388
lshift_error:
 
3389
        return (PyObject *) maybe_small_long(z);
 
3390
}
 
3391
 
 
3392
 
 
3393
/* Bitwise and/xor/or operations */
 
3394
 
 
3395
static PyObject *
 
3396
long_bitwise(PyLongObject *a,
 
3397
             int op,  /* '&', '|', '^' */
 
3398
             PyLongObject *b)
 
3399
{
 
3400
        digit maska, maskb; /* 0 or PyLong_MASK */
 
3401
        int negz;
 
3402
        Py_ssize_t size_a, size_b, size_z, i;
 
3403
        PyLongObject *z;
 
3404
        digit diga, digb;
 
3405
        PyObject *v;
 
3406
 
 
3407
        if (Py_SIZE(a) < 0) {
 
3408
                a = (PyLongObject *) long_invert(a);
 
3409
                if (a == NULL)
 
3410
                        return NULL;
 
3411
                maska = PyLong_MASK;
 
3412
        }
 
3413
        else {
 
3414
                Py_INCREF(a);
 
3415
                maska = 0;
 
3416
        }
 
3417
        if (Py_SIZE(b) < 0) {
 
3418
                b = (PyLongObject *) long_invert(b);
 
3419
                if (b == NULL) {
 
3420
                        Py_DECREF(a);
 
3421
                        return NULL;
 
3422
                }
 
3423
                maskb = PyLong_MASK;
 
3424
        }
 
3425
        else {
 
3426
                Py_INCREF(b);
 
3427
                maskb = 0;
 
3428
        }
 
3429
 
 
3430
        negz = 0;
 
3431
        switch (op) {
 
3432
        case '^':
 
3433
                if (maska != maskb) {
 
3434
                        maska ^= PyLong_MASK;
 
3435
                        negz = -1;
 
3436
                }
 
3437
                break;
 
3438
        case '&':
 
3439
                if (maska && maskb) {
 
3440
                        op = '|';
 
3441
                        maska ^= PyLong_MASK;
 
3442
                        maskb ^= PyLong_MASK;
 
3443
                        negz = -1;
 
3444
                }
 
3445
                break;
 
3446
        case '|':
 
3447
                if (maska || maskb) {
 
3448
                        op = '&';
 
3449
                        maska ^= PyLong_MASK;
 
3450
                        maskb ^= PyLong_MASK;
 
3451
                        negz = -1;
 
3452
                }
 
3453
                break;
 
3454
        }
 
3455
 
 
3456
        /* JRH: The original logic here was to allocate the result value (z)
 
3457
           as the longer of the two operands.  However, there are some cases
 
3458
           where the result is guaranteed to be shorter than that: AND of two
 
3459
           positives, OR of two negatives: use the shorter number.  AND with
 
3460
           mixed signs: use the positive number.  OR with mixed signs: use the
 
3461
           negative number.  After the transformations above, op will be '&'
 
3462
           iff one of these cases applies, and mask will be non-0 for operands
 
3463
           whose length should be ignored.
 
3464
        */
 
3465
 
 
3466
        size_a = Py_SIZE(a);
 
3467
        size_b = Py_SIZE(b);
 
3468
        size_z = op == '&'
 
3469
                ? (maska
 
3470
                   ? size_b
 
3471
                   : (maskb ? size_a : MIN(size_a, size_b)))
 
3472
                : MAX(size_a, size_b);
 
3473
        z = _PyLong_New(size_z);
 
3474
        if (z == NULL) {
 
3475
                Py_DECREF(a);
 
3476
                Py_DECREF(b);
 
3477
                return NULL;
 
3478
        }
 
3479
 
 
3480
        for (i = 0; i < size_z; ++i) {
 
3481
                diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
 
3482
                digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
 
3483
                switch (op) {
 
3484
                case '&': z->ob_digit[i] = diga & digb; break;
 
3485
                case '|': z->ob_digit[i] = diga | digb; break;
 
3486
                case '^': z->ob_digit[i] = diga ^ digb; break;
 
3487
                }
 
3488
        }
 
3489
 
 
3490
        Py_DECREF(a);
 
3491
        Py_DECREF(b);
 
3492
        z = long_normalize(z);
 
3493
        if (negz == 0)
 
3494
                return (PyObject *) maybe_small_long(z);
 
3495
        v = long_invert(z);
 
3496
        Py_DECREF(z);
 
3497
        return v;
 
3498
}
 
3499
 
 
3500
static PyObject *
 
3501
long_and(PyObject *a, PyObject *b)
 
3502
{
 
3503
        PyObject *c;
 
3504
        CHECK_BINOP(a, b);
 
3505
        c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
 
3506
        return c;
 
3507
}
 
3508
 
 
3509
static PyObject *
 
3510
long_xor(PyObject *a, PyObject *b)
 
3511
{
 
3512
        PyObject *c;
 
3513
        CHECK_BINOP(a, b);
 
3514
        c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
 
3515
        return c;
 
3516
}
 
3517
 
 
3518
static PyObject *
 
3519
long_or(PyObject *a, PyObject *b)
 
3520
{
 
3521
        PyObject *c;
 
3522
        CHECK_BINOP(a, b);
 
3523
        c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
 
3524
        return c;
 
3525
}
 
3526
 
 
3527
static PyObject *
 
3528
long_long(PyObject *v)
 
3529
{
 
3530
        if (PyLong_CheckExact(v))
 
3531
                Py_INCREF(v);
 
3532
        else
 
3533
                v = _PyLong_Copy((PyLongObject *)v);
 
3534
        return v;
 
3535
}
 
3536
 
 
3537
static PyObject *
 
3538
long_float(PyObject *v)
 
3539
{
 
3540
        double result;
 
3541
        result = PyLong_AsDouble(v);
 
3542
        if (result == -1.0 && PyErr_Occurred())
 
3543
                return NULL;
 
3544
        return PyFloat_FromDouble(result);
 
3545
}
 
3546
 
 
3547
static PyObject *
 
3548
long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
 
3549
 
 
3550
static PyObject *
 
3551
long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
 
3552
{
 
3553
        PyObject *x = NULL;
 
3554
        int base = -909;                     /* unlikely! */
 
3555
        static char *kwlist[] = {"x", "base", 0};
 
3556
 
 
3557
        if (type != &PyLong_Type)
 
3558
                return long_subtype_new(type, args, kwds); /* Wimp out */
 
3559
        if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
 
3560
                                         &x, &base))
 
3561
                return NULL;
 
3562
        if (x == NULL)
 
3563
                return PyLong_FromLong(0L);
 
3564
        if (base == -909)
 
3565
                return PyNumber_Long(x);
 
3566
        else if (PyUnicode_Check(x))
 
3567
                return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
 
3568
                                          PyUnicode_GET_SIZE(x),
 
3569
                                          base);
 
3570
        else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
 
3571
                /* Since PyLong_FromString doesn't have a length parameter,
 
3572
                 * check here for possible NULs in the string. */
 
3573
                char *string;
 
3574
                Py_ssize_t size = Py_SIZE(x);
 
3575
                if (PyByteArray_Check(x))
 
3576
                        string = PyByteArray_AS_STRING(x);
 
3577
                else
 
3578
                        string = PyBytes_AS_STRING(x);
 
3579
                if (strlen(string) != (size_t)size) {
 
3580
                        /* We only see this if there's a null byte in x,
 
3581
                           x is a bytes or buffer, *and* a base is given. */
 
3582
                        PyErr_Format(PyExc_ValueError,
 
3583
                            "invalid literal for int() with base %d: %R",
 
3584
                            base, x);
 
3585
                        return NULL;
 
3586
                }
 
3587
                return PyLong_FromString(string, NULL, base);
 
3588
        }
 
3589
        else {
 
3590
                PyErr_SetString(PyExc_TypeError,
 
3591
                        "int() can't convert non-string with explicit base");
 
3592
                return NULL;
 
3593
        }
 
3594
}
 
3595
 
 
3596
/* Wimpy, slow approach to tp_new calls for subtypes of long:
 
3597
   first create a regular long from whatever arguments we got,
 
3598
   then allocate a subtype instance and initialize it from
 
3599
   the regular long.  The regular long is then thrown away.
 
3600
*/
 
3601
static PyObject *
 
3602
long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
 
3603
{
 
3604
        PyLongObject *tmp, *newobj;
 
3605
        Py_ssize_t i, n;
 
3606
 
 
3607
        assert(PyType_IsSubtype(type, &PyLong_Type));
 
3608
        tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
 
3609
        if (tmp == NULL)
 
3610
                return NULL;
 
3611
        assert(PyLong_CheckExact(tmp));
 
3612
        n = Py_SIZE(tmp);
 
3613
        if (n < 0)
 
3614
                n = -n;
 
3615
        newobj = (PyLongObject *)type->tp_alloc(type, n);
 
3616
        if (newobj == NULL) {
 
3617
                Py_DECREF(tmp);
 
3618
                return NULL;
 
3619
        }
 
3620
        assert(PyLong_Check(newobj));
 
3621
        Py_SIZE(newobj) = Py_SIZE(tmp);
 
3622
        for (i = 0; i < n; i++)
 
3623
                newobj->ob_digit[i] = tmp->ob_digit[i];
 
3624
        Py_DECREF(tmp);
 
3625
        return (PyObject *)newobj;
 
3626
}
 
3627
 
 
3628
static PyObject *
 
3629
long_getnewargs(PyLongObject *v)
 
3630
{
 
3631
        return Py_BuildValue("(N)", _PyLong_Copy(v));
 
3632
}
 
3633
 
 
3634
static PyObject *
 
3635
long_getN(PyLongObject *v, void *context) {
 
3636
        return PyLong_FromLong((Py_intptr_t)context);
 
3637
}
 
3638
 
 
3639
static PyObject *
 
3640
long__format__(PyObject *self, PyObject *args)
 
3641
{
 
3642
        PyObject *format_spec;
 
3643
 
 
3644
        if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
 
3645
                return NULL;
 
3646
        return _PyLong_FormatAdvanced(self,
 
3647
                                      PyUnicode_AS_UNICODE(format_spec),
 
3648
                                      PyUnicode_GET_SIZE(format_spec));
 
3649
}
 
3650
 
 
3651
static PyObject *
 
3652
long_round(PyObject *self, PyObject *args)
 
3653
{
 
3654
        PyObject *o_ndigits=NULL, *temp;
 
3655
        PyLongObject *pow=NULL, *q=NULL, *r=NULL, *ndigits=NULL, *one;
 
3656
        int errcode;
 
3657
        digit q_mod_4;
 
3658
 
 
3659
        /* Notes on the algorithm: to round to the nearest 10**n (n positive),
 
3660
           the straightforward method is:
 
3661
 
 
3662
              (1) divide by 10**n
 
3663
              (2) round to nearest integer (round to even in case of tie)
 
3664
              (3) multiply result by 10**n.
 
3665
 
 
3666
           But the rounding step involves examining the fractional part of the
 
3667
           quotient to see whether it's greater than 0.5 or not.  Since we
 
3668
           want to do the whole calculation in integer arithmetic, it's
 
3669
           simpler to do:
 
3670
 
 
3671
              (1) divide by (10**n)/2
 
3672
              (2) round to nearest multiple of 2 (multiple of 4 in case of tie)
 
3673
              (3) multiply result by (10**n)/2.
 
3674
 
 
3675
           Then all we need to know about the fractional part of the quotient
 
3676
           arising in step (2) is whether it's zero or not.
 
3677
 
 
3678
           Doing both a multiplication and division is wasteful, and is easily
 
3679
           avoided if we just figure out how much to adjust the original input
 
3680
           by to do the rounding.
 
3681
 
 
3682
           Here's the whole algorithm expressed in Python.
 
3683
 
 
3684
            def round(self, ndigits = None):
 
3685
                """round(int, int) -> int"""
 
3686
                if ndigits is None or ndigits >= 0:
 
3687
                    return self
 
3688
                pow = 10**-ndigits >> 1
 
3689
                q, r = divmod(self, pow)
 
3690
                self -= r
 
3691
                if (q & 1 != 0):
 
3692
                    if (q & 2 == r == 0):
 
3693
                        self -= pow
 
3694
                    else:
 
3695
                        self += pow
 
3696
                return self
 
3697
 
 
3698
        */
 
3699
        if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
 
3700
                return NULL;
 
3701
        if (o_ndigits == NULL)
 
3702
                return long_long(self);
 
3703
 
 
3704
        ndigits = (PyLongObject *)PyNumber_Index(o_ndigits);
 
3705
        if (ndigits == NULL)
 
3706
                return NULL;
 
3707
 
 
3708
        if (Py_SIZE(ndigits) >= 0) {
 
3709
                Py_DECREF(ndigits);
 
3710
                return long_long(self);
 
3711
        }
 
3712
 
 
3713
        Py_INCREF(self); /* to keep refcounting simple */
 
3714
        /* we now own references to self, ndigits */
 
3715
 
 
3716
        /* pow = 10 ** -ndigits >> 1 */
 
3717
        pow = (PyLongObject *)PyLong_FromLong(10L);
 
3718
        if (pow == NULL)
 
3719
                goto error;
 
3720
        temp = long_neg(ndigits);
 
3721
        Py_DECREF(ndigits);
 
3722
        ndigits = (PyLongObject *)temp;
 
3723
        if (ndigits == NULL)
 
3724
                goto error;
 
3725
        temp = long_pow((PyObject *)pow, (PyObject *)ndigits, Py_None);
 
3726
        Py_DECREF(pow);
 
3727
        pow = (PyLongObject *)temp;
 
3728
        if (pow == NULL)
 
3729
                goto error;
 
3730
        assert(PyLong_Check(pow)); /* check long_pow returned a long */
 
3731
        one = (PyLongObject *)PyLong_FromLong(1L);
 
3732
        if (one == NULL)
 
3733
                goto error;
 
3734
        temp = long_rshift(pow, one);
 
3735
        Py_DECREF(one);
 
3736
        Py_DECREF(pow);
 
3737
        pow = (PyLongObject *)temp;
 
3738
        if (pow == NULL)
 
3739
                goto error;
 
3740
 
 
3741
        /* q, r = divmod(self, pow) */
 
3742
        errcode = l_divmod((PyLongObject *)self, pow, &q, &r);
 
3743
        if (errcode == -1)
 
3744
                goto error;
 
3745
 
 
3746
        /* self -= r */
 
3747
        temp = long_sub((PyLongObject *)self, r);
 
3748
        Py_DECREF(self);
 
3749
        self = temp;
 
3750
        if (self == NULL)
 
3751
                goto error;
 
3752
 
 
3753
        /* get value of quotient modulo 4 */
 
3754
        if (Py_SIZE(q) == 0)
 
3755
                q_mod_4 = 0;
 
3756
        else if (Py_SIZE(q) > 0)
 
3757
                q_mod_4 = q->ob_digit[0] & 3;
 
3758
        else
 
3759
                q_mod_4 = (PyLong_BASE-q->ob_digit[0]) & 3;
 
3760
 
 
3761
        if ((q_mod_4 & 1) == 1) {
 
3762
                /* q is odd; round self up or down by adding or subtracting pow */
 
3763
                if (q_mod_4 == 1 && Py_SIZE(r) == 0)
 
3764
                        temp = (PyObject *)long_sub((PyLongObject *)self, pow);
 
3765
                else
 
3766
                        temp = (PyObject *)long_add((PyLongObject *)self, pow);
 
3767
                Py_DECREF(self);
 
3768
                self = temp;
 
3769
                if (self == NULL)
 
3770
                        goto error;
 
3771
        }
 
3772
        Py_DECREF(q);
 
3773
        Py_DECREF(r);
 
3774
        Py_DECREF(pow);
 
3775
        Py_DECREF(ndigits);
 
3776
        return self;
 
3777
 
 
3778
  error:
 
3779
        Py_XDECREF(q);
 
3780
        Py_XDECREF(r);
 
3781
        Py_XDECREF(pow);
 
3782
        Py_XDECREF(self);
 
3783
        Py_XDECREF(ndigits);
 
3784
        return NULL;
 
3785
}
 
3786
 
 
3787
static PyObject *
 
3788
long_sizeof(PyLongObject *v)
 
3789
{
 
3790
        Py_ssize_t res;
 
3791
 
 
3792
        res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
 
3793
        return PyLong_FromSsize_t(res);
 
3794
}
 
3795
 
 
3796
static const unsigned char BitLengthTable[32] = {
 
3797
        0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
 
3798
        5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
 
3799
};
 
3800
 
 
3801
static PyObject *
 
3802
long_bit_length(PyLongObject *v)
 
3803
{
 
3804
        PyLongObject *result, *x, *y;
 
3805
        Py_ssize_t ndigits, msd_bits = 0;
 
3806
        digit msd;
 
3807
 
 
3808
        assert(v != NULL);
 
3809
        assert(PyLong_Check(v));
 
3810
 
 
3811
        ndigits = ABS(Py_SIZE(v));
 
3812
        if (ndigits == 0)
 
3813
                return PyLong_FromLong(0);
 
3814
 
 
3815
        msd = v->ob_digit[ndigits-1];
 
3816
        while (msd >= 32) {
 
3817
                msd_bits += 6;
 
3818
                msd >>= 6;
 
3819
        }
 
3820
        msd_bits += (long)(BitLengthTable[msd]);
 
3821
 
 
3822
        if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
 
3823
                return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
 
3824
 
 
3825
        /* expression above may overflow; use Python integers instead */
 
3826
        result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
 
3827
        if (result == NULL)
 
3828
                return NULL;
 
3829
        x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
 
3830
        if (x == NULL)
 
3831
                goto error;
 
3832
        y = (PyLongObject *)long_mul(result, x);
 
3833
        Py_DECREF(x);
 
3834
        if (y == NULL)
 
3835
                goto error;
 
3836
        Py_DECREF(result);
 
3837
        result = y;
 
3838
 
 
3839
        x = (PyLongObject *)PyLong_FromLong(msd_bits);
 
3840
        if (x == NULL)
 
3841
                goto error;
 
3842
        y = (PyLongObject *)long_add(result, x);
 
3843
        Py_DECREF(x);
 
3844
        if (y == NULL)
 
3845
                goto error;
 
3846
        Py_DECREF(result);
 
3847
        result = y;
 
3848
 
 
3849
        return (PyObject *)result;
 
3850
 
 
3851
error:
 
3852
        Py_DECREF(result);
 
3853
        return NULL;
 
3854
}
 
3855
 
 
3856
PyDoc_STRVAR(long_bit_length_doc,
 
3857
"int.bit_length() -> int\n\
 
3858
\n\
 
3859
Number of bits necessary to represent self in binary.\n\
 
3860
>>> bin(37)\n\
 
3861
'0b100101'\n\
 
3862
>>> (37).bit_length()\n\
 
3863
6");
 
3864
 
 
3865
#if 0
 
3866
static PyObject *
 
3867
long_is_finite(PyObject *v)
 
3868
{
 
3869
        Py_RETURN_TRUE;
 
3870
}
 
3871
#endif
 
3872
 
 
3873
static PyMethodDef long_methods[] = {
 
3874
        {"conjugate",   (PyCFunction)long_long, METH_NOARGS,
 
3875
         "Returns self, the complex conjugate of any int."},
 
3876
        {"bit_length",  (PyCFunction)long_bit_length, METH_NOARGS,
 
3877
         long_bit_length_doc},
 
3878
#if 0
 
3879
        {"is_finite",   (PyCFunction)long_is_finite,    METH_NOARGS,
 
3880
         "Returns always True."},
 
3881
#endif
 
3882
        {"__trunc__",   (PyCFunction)long_long, METH_NOARGS,
 
3883
         "Truncating an Integral returns itself."},
 
3884
        {"__floor__",   (PyCFunction)long_long, METH_NOARGS,
 
3885
         "Flooring an Integral returns itself."},
 
3886
        {"__ceil__",    (PyCFunction)long_long, METH_NOARGS,
 
3887
         "Ceiling of an Integral returns itself."},
 
3888
        {"__round__",   (PyCFunction)long_round, METH_VARARGS,
 
3889
         "Rounding an Integral returns itself.\n"
 
3890
         "Rounding with an ndigits argument also returns an integer."},
 
3891
        {"__getnewargs__",      (PyCFunction)long_getnewargs,   METH_NOARGS},
 
3892
        {"__format__", (PyCFunction)long__format__, METH_VARARGS},
 
3893
        {"__sizeof__",  (PyCFunction)long_sizeof, METH_NOARGS,
 
3894
         "Returns size in memory, in bytes"},
 
3895
        {NULL,          NULL}           /* sentinel */
 
3896
};
 
3897
 
 
3898
static PyGetSetDef long_getset[] = {
 
3899
    {"real", 
 
3900
     (getter)long_long, (setter)NULL,
 
3901
     "the real part of a complex number",
 
3902
     NULL},
 
3903
    {"imag", 
 
3904
     (getter)long_getN, (setter)NULL,
 
3905
     "the imaginary part of a complex number",
 
3906
     (void*)0},
 
3907
    {"numerator", 
 
3908
     (getter)long_long, (setter)NULL,
 
3909
     "the numerator of a rational number in lowest terms",
 
3910
     NULL},
 
3911
    {"denominator", 
 
3912
     (getter)long_getN, (setter)NULL,
 
3913
     "the denominator of a rational number in lowest terms",
 
3914
     (void*)1},
 
3915
    {NULL}  /* Sentinel */
 
3916
};
 
3917
 
 
3918
PyDoc_STRVAR(long_doc,
 
3919
"int(x[, base]) -> integer\n\
 
3920
\n\
 
3921
Convert a string or number to an integer, if possible.  A floating\n\
 
3922
point argument will be truncated towards zero (this does not include a\n\
 
3923
string representation of a floating point number!)  When converting a\n\
 
3924
string, use the optional base.  It is an error to supply a base when\n\
 
3925
converting a non-string.");
 
3926
 
 
3927
static PyNumberMethods long_as_number = {
 
3928
        (binaryfunc)    long_add,       /*nb_add*/
 
3929
        (binaryfunc)    long_sub,       /*nb_subtract*/
 
3930
        (binaryfunc)    long_mul,       /*nb_multiply*/
 
3931
                        long_mod,       /*nb_remainder*/
 
3932
                        long_divmod,    /*nb_divmod*/
 
3933
                        long_pow,       /*nb_power*/
 
3934
        (unaryfunc)     long_neg,       /*nb_negative*/
 
3935
        (unaryfunc)     long_long,      /*tp_positive*/
 
3936
        (unaryfunc)     long_abs,       /*tp_absolute*/
 
3937
        (inquiry)       long_bool,      /*tp_bool*/
 
3938
        (unaryfunc)     long_invert,    /*nb_invert*/
 
3939
                        long_lshift,    /*nb_lshift*/
 
3940
        (binaryfunc)    long_rshift,    /*nb_rshift*/
 
3941
                        long_and,       /*nb_and*/
 
3942
                        long_xor,       /*nb_xor*/
 
3943
                        long_or,        /*nb_or*/
 
3944
                        long_long,      /*nb_int*/
 
3945
        0,                              /*nb_reserved*/
 
3946
                        long_float,     /*nb_float*/
 
3947
        0,                              /* nb_inplace_add */
 
3948
        0,                              /* nb_inplace_subtract */
 
3949
        0,                              /* nb_inplace_multiply */
 
3950
        0,                              /* nb_inplace_remainder */
 
3951
        0,                              /* nb_inplace_power */
 
3952
        0,                              /* nb_inplace_lshift */
 
3953
        0,                              /* nb_inplace_rshift */
 
3954
        0,                              /* nb_inplace_and */
 
3955
        0,                              /* nb_inplace_xor */
 
3956
        0,                              /* nb_inplace_or */
 
3957
        long_div,                       /* nb_floor_divide */
 
3958
        long_true_divide,               /* nb_true_divide */
 
3959
        0,                              /* nb_inplace_floor_divide */
 
3960
        0,                              /* nb_inplace_true_divide */
 
3961
        long_long,                      /* nb_index */
 
3962
};
 
3963
 
 
3964
PyTypeObject PyLong_Type = {
 
3965
        PyVarObject_HEAD_INIT(&PyType_Type, 0)
 
3966
        "int",                                  /* tp_name */
 
3967
        offsetof(PyLongObject, ob_digit),       /* tp_basicsize */
 
3968
        sizeof(digit),                          /* tp_itemsize */
 
3969
        long_dealloc,                           /* tp_dealloc */
 
3970
        0,                                      /* tp_print */
 
3971
        0,                                      /* tp_getattr */
 
3972
        0,                                      /* tp_setattr */
 
3973
        0,                                      /* tp_reserved */
 
3974
        long_repr,                              /* tp_repr */
 
3975
        &long_as_number,                        /* tp_as_number */
 
3976
        0,                                      /* tp_as_sequence */
 
3977
        0,                                      /* tp_as_mapping */
 
3978
        (hashfunc)long_hash,                    /* tp_hash */
 
3979
        0,                                      /* tp_call */
 
3980
        long_repr,                              /* tp_str */
 
3981
        PyObject_GenericGetAttr,                /* tp_getattro */
 
3982
        0,                                      /* tp_setattro */
 
3983
        0,                                      /* tp_as_buffer */
 
3984
        Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
 
3985
                Py_TPFLAGS_LONG_SUBCLASS,       /* tp_flags */
 
3986
        long_doc,                               /* tp_doc */
 
3987
        0,                                      /* tp_traverse */
 
3988
        0,                                      /* tp_clear */
 
3989
        long_richcompare,                       /* tp_richcompare */
 
3990
        0,                                      /* tp_weaklistoffset */
 
3991
        0,                                      /* tp_iter */
 
3992
        0,                                      /* tp_iternext */
 
3993
        long_methods,                           /* tp_methods */
 
3994
        0,                                      /* tp_members */
 
3995
        long_getset,                            /* tp_getset */
 
3996
        0,                                      /* tp_base */
 
3997
        0,                                      /* tp_dict */
 
3998
        0,                                      /* tp_descr_get */
 
3999
        0,                                      /* tp_descr_set */
 
4000
        0,                                      /* tp_dictoffset */
 
4001
        0,                                      /* tp_init */
 
4002
        0,                                      /* tp_alloc */
 
4003
        long_new,                               /* tp_new */
 
4004
        PyObject_Del,                           /* tp_free */
 
4005
};
 
4006
 
 
4007
static PyTypeObject Int_InfoType;
 
4008
 
 
4009
PyDoc_STRVAR(int_info__doc__,
 
4010
"sys.int_info\n\
 
4011
\n\
 
4012
A struct sequence that holds information about Python's\n\
 
4013
internal representation of integers.  The attributes are read only.");
 
4014
 
 
4015
static PyStructSequence_Field int_info_fields[] = {
 
4016
        {"bits_per_digit", "size of a digit in bits"},
 
4017
        {"sizeof_digit", "size in bytes of the C type used to "
 
4018
                         "represent a digit"},
 
4019
        {NULL, NULL}
 
4020
};
 
4021
 
 
4022
static PyStructSequence_Desc int_info_desc = {
 
4023
        "sys.int_info",   /* name */
 
4024
        int_info__doc__,  /* doc */
 
4025
        int_info_fields,  /* fields */
 
4026
        2                 /* number of fields */
 
4027
};
 
4028
 
 
4029
PyObject *
 
4030
PyLong_GetInfo(void)
 
4031
{
 
4032
        PyObject* int_info;
 
4033
        int field = 0;
 
4034
        int_info = PyStructSequence_New(&Int_InfoType);
 
4035
        if (int_info == NULL)
 
4036
                return NULL;
 
4037
        PyStructSequence_SET_ITEM(int_info, field++, PyLong_FromLong(PyLong_SHIFT));
 
4038
        PyStructSequence_SET_ITEM(int_info, field++, PyLong_FromLong(sizeof(digit)));
 
4039
        if (PyErr_Occurred()) {
 
4040
                Py_CLEAR(int_info);
 
4041
                return NULL;
 
4042
        }
 
4043
        return int_info;
 
4044
}
 
4045
 
 
4046
int
 
4047
_PyLong_Init(void)
 
4048
{
 
4049
#if NSMALLNEGINTS + NSMALLPOSINTS > 0
 
4050
        int ival, size;
 
4051
        PyLongObject *v = small_ints;
 
4052
 
 
4053
        for (ival = -NSMALLNEGINTS; ival <  NSMALLPOSINTS; ival++, v++) {
 
4054
                size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
 
4055
                if (Py_TYPE(v) == &PyLong_Type) {
 
4056
                        /* The element is already initialized, most likely
 
4057
                         * the Python interpreter was initialized before.
 
4058
                         */
 
4059
                        Py_ssize_t refcnt;
 
4060
                        PyObject* op = (PyObject*)v;
 
4061
 
 
4062
                        refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
 
4063
                        _Py_NewReference(op);
 
4064
                        /* _Py_NewReference sets the ref count to 1 but
 
4065
                         * the ref count might be larger. Set the refcnt
 
4066
                         * to the original refcnt + 1 */         
 
4067
                        Py_REFCNT(op) = refcnt + 1;
 
4068
                        assert(Py_SIZE(op) == size);
 
4069
                        assert(v->ob_digit[0] == abs(ival));
 
4070
                }
 
4071
                else {
 
4072
                        PyObject_INIT(v, &PyLong_Type);
 
4073
                }
 
4074
                Py_SIZE(v) = size;
 
4075
                v->ob_digit[0] = abs(ival);
 
4076
        }
 
4077
#endif
 
4078
        /* initialize int_info */
 
4079
        if (Int_InfoType.tp_name == 0)
 
4080
                PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
 
4081
 
 
4082
        return 1;
 
4083
}
 
4084
 
 
4085
void
 
4086
PyLong_Fini(void)
 
4087
{
 
4088
        /* Integers are currently statically allocated. Py_DECREF is not
 
4089
           needed, but Python must forget about the reference or multiple
 
4090
           reinitializations will fail. */
 
4091
#if NSMALLNEGINTS + NSMALLPOSINTS > 0
 
4092
        int i;
 
4093
        PyLongObject *v = small_ints;
 
4094
        for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
 
4095
                _Py_DEC_REFTOTAL;
 
4096
                _Py_ForgetReference((PyObject*)v);
 
4097
        }
 
4098
#endif
 
4099
}