blob: 3aa518b91756048190e7f110c4541d7684c92c0e [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001/* Long (arbitrary precision) integer object implementation */
2
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003/* XXX The functional organization of this file is terrible */
4
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005#include "Python.h"
Guido van Rossumedcc38a1991-05-05 20:09:44 +00006#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00008#include <ctype.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +00009
Guido van Rossumddefaf32007-01-14 03:31:43 +000010#ifndef NSMALLPOSINTS
11#define NSMALLPOSINTS 257
12#endif
13#ifndef NSMALLNEGINTS
14#define NSMALLNEGINTS 5
15#endif
Facundo Batista6e6f59b2008-07-24 18:57:11 +000016
17#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(x)->ob_digit[0] : \
18 (Py_SIZE(x) == 0 ? 0 : (x)->ob_digit[0]))
19#define ABS(x) ((x) < 0 ? -(x) : (x))
20
Guido van Rossumddefaf32007-01-14 03:31:43 +000021#if NSMALLNEGINTS + NSMALLPOSINTS > 0
22/* Small integers are preallocated in this array so that they
23 can be shared.
24 The integers that are preallocated are those in the range
25 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
26*/
27static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
28#ifdef COUNT_ALLOCS
29int quick_int_allocs, quick_neg_int_allocs;
30#endif
31
Guido van Rossum7eaf8222007-06-18 17:58:50 +000032static PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +000033get_small_int(int ival)
34{
35 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
36 Py_INCREF(v);
37#ifdef COUNT_ALLOCS
38 if (ival >= 0)
39 quick_int_allocs++;
40 else
41 quick_neg_int_allocs++;
42#endif
43 return v;
44}
45#define CHECK_SMALL_INT(ival) \
46 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
47 return get_small_int(ival); \
48 } while(0)
49
Facundo Batista6e6f59b2008-07-24 18:57:11 +000050static PyLongObject *
51maybe_small_long(PyLongObject *v)
52{
53 if (v && ABS(Py_SIZE(v)) <= 1) {
54 int ival = MEDIUM_VALUE(v);
55 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
56 Py_DECREF(v);
57 return (PyLongObject *)get_small_int(ival);
58 }
59 }
60 return v;
61}
Guido van Rossumddefaf32007-01-14 03:31:43 +000062#else
63#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000064#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000065#endif
66
Guido van Rossumddefaf32007-01-14 03:31:43 +000067/* If a freshly-allocated long is already shared, it must
68 be a small integer, so negating it must go to PyLong_FromLong */
69#define NEGATE(x) \
Christian Heimes90aa7642007-12-19 02:45:37 +000070 do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \
Christian Heimes217cfd12007-12-02 14:31:20 +000071 else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \
Guido van Rossumddefaf32007-01-14 03:31:43 +000072 Py_DECREF(x); (x) = (PyLongObject*)tmp; } \
73 while(0)
Tim Peters5af4e6c2002-08-12 02:31:19 +000074/* For long multiplication, use the O(N**2) school algorithm unless
75 * both operands contain more than KARATSUBA_CUTOFF digits (this
76 * being an internal Python long digit, in base BASE).
77 */
Tim Peters0973b992004-08-29 22:16:50 +000078#define KARATSUBA_CUTOFF 70
79#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000080
Tim Peters47e52ee2004-08-30 02:44:38 +000081/* For exponentiation, use the binary left-to-right algorithm
82 * unless the exponent contains more than FIVEARY_CUTOFF digits.
83 * In that case, do 5 bits at a time. The potential drawback is that
84 * a table of 2**5 intermediate results is computed.
85 */
86#define FIVEARY_CUTOFF 8
87
Tim Peters5af4e6c2002-08-12 02:31:19 +000088#undef MIN
89#undef MAX
90#define MAX(x, y) ((x) < (y) ? (y) : (x))
91#define MIN(x, y) ((x) > (y) ? (y) : (x))
92
Guido van Rossume32e0141992-01-19 16:31:05 +000093/* Forward */
Tim Peters9f688bf2000-07-07 15:53:28 +000094static PyLongObject *long_normalize(PyLongObject *);
95static PyLongObject *mul1(PyLongObject *, wdigit);
96static PyLongObject *muladd1(PyLongObject *, wdigit, wdigit);
Tim Peters212e6142001-07-14 12:23:19 +000097static PyLongObject *divrem1(PyLongObject *, digit, digit *);
Guido van Rossume32e0141992-01-19 16:31:05 +000098
Guido van Rossumc0b618a1997-05-02 03:12:38 +000099#define SIGCHECK(PyTryBlock) \
Skip Montanarod581d772002-09-03 20:10:45 +0000100 if (--_Py_Ticker < 0) { \
101 _Py_Ticker = _Py_CheckInterval; \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000102 if (PyErr_CheckSignals()) PyTryBlock \
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000103 }
104
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000105/* Normalize (remove leading zeros from) a long int object.
106 Doesn't attempt to free the storage--in most cases, due to the nature
107 of the algorithms used, this could save at most be one word anyway. */
108
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000109static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000110long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000111{
Christian Heimes90aa7642007-12-19 02:45:37 +0000112 Py_ssize_t j = ABS(Py_SIZE(v));
Martin v. Löwis18e16552006-02-15 17:27:45 +0000113 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000114
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000115 while (i > 0 && v->ob_digit[i-1] == 0)
116 --i;
117 if (i != j)
Christian Heimes90aa7642007-12-19 02:45:37 +0000118 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000119 return v;
120}
121
122/* Allocate a new long int object with size digits.
123 Return NULL and set exception if we run out of memory. */
124
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000125PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000126_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000127{
Guido van Rossumddefaf32007-01-14 03:31:43 +0000128 PyLongObject *result;
129 /* Can't use sizeof(PyLongObject) here, since the
130 compiler takes padding at the end into account.
131 As the consequence, this would waste 2 bytes on
132 a 32-bit system, and 6 bytes on a 64-bit system.
133 This computation would be incorrect on systems
134 which have padding before the digits; with 16-bit
135 digits this should not happen. */
136 result = PyObject_MALLOC(sizeof(PyVarObject) +
137 size*sizeof(digit));
138 if (!result) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000139 PyErr_NoMemory();
140 return NULL;
141 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000142 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000143}
144
Tim Peters64b5ce32001-09-10 20:52:51 +0000145PyObject *
146_PyLong_Copy(PyLongObject *src)
147{
148 PyLongObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000149 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000150
151 assert(src != NULL);
Christian Heimes90aa7642007-12-19 02:45:37 +0000152 i = Py_SIZE(src);
Tim Peters64b5ce32001-09-10 20:52:51 +0000153 if (i < 0)
154 i = -(i);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000155 if (i < 2) {
156 int ival = src->ob_digit[0];
Christian Heimes90aa7642007-12-19 02:45:37 +0000157 if (Py_SIZE(src) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000158 ival = -ival;
159 CHECK_SMALL_INT(ival);
160 }
Tim Peters64b5ce32001-09-10 20:52:51 +0000161 result = _PyLong_New(i);
162 if (result != NULL) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000163 Py_SIZE(result) = Py_SIZE(src);
Tim Peters64b5ce32001-09-10 20:52:51 +0000164 while (--i >= 0)
165 result->ob_digit[i] = src->ob_digit[i];
166 }
167 return (PyObject *)result;
168}
169
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000170/* Create a new long int object from a C long int */
171
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000172PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000173PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000174{
Tim Petersce9de2f2001-06-14 04:56:19 +0000175 PyLongObject *v;
Christian Heimesdae2a892008-04-19 00:55:37 +0000176 unsigned long abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000177 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
178 int ndigits = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000179 int sign = 1;
180
181 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000182
183 if (ival < 0) {
Christian Heimesdae2a892008-04-19 00:55:37 +0000184 /* if LONG_MIN == -LONG_MAX-1 (true on most platforms) then
185 ANSI C says that the result of -ival is undefined when ival
186 == LONG_MIN. Hence the following workaround. */
187 abs_ival = (unsigned long)(-1-ival) + 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000188 sign = -1;
Tim Petersce9de2f2001-06-14 04:56:19 +0000189 }
Christian Heimesdae2a892008-04-19 00:55:37 +0000190 else {
191 abs_ival = (unsigned long)ival;
192 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000193
Guido van Rossumddefaf32007-01-14 03:31:43 +0000194 /* Fast path for single-digits ints */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000195 if (!(ival>>PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000196 v = _PyLong_New(1);
197 if (v) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000198 Py_SIZE(v) = sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000199 v->ob_digit[0] = ival;
200 }
201 return (PyObject*)v;
202 }
203
204 /* 2 digits */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000205 if (!(ival >> 2*PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000206 v = _PyLong_New(2);
207 if (v) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000208 Py_SIZE(v) = 2*sign;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000209 v->ob_digit[0] = (digit)ival & PyLong_MASK;
210 v->ob_digit[1] = ival >> PyLong_SHIFT;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000211 }
212 return (PyObject*)v;
213 }
214
215 /* Larger numbers: loop to determine number of digits */
Christian Heimesdae2a892008-04-19 00:55:37 +0000216 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000217 while (t) {
218 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000219 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000220 }
221 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000222 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000223 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +0000224 Py_SIZE(v) = ndigits*sign;
Christian Heimesdae2a892008-04-19 00:55:37 +0000225 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000226 while (t) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000227 *p++ = (digit)(t & PyLong_MASK);
228 t >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000229 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000230 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000231 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000232}
233
Guido van Rossum53756b11997-01-03 17:14:46 +0000234/* Create a new long int object from a C unsigned long int */
235
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000236PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000237PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000238{
Tim Petersce9de2f2001-06-14 04:56:19 +0000239 PyLongObject *v;
240 unsigned long t;
241 int ndigits = 0;
242
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000243 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000244 return PyLong_FromLong(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000245 /* Count the number of Python digits. */
246 t = (unsigned long)ival;
247 while (t) {
248 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000249 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000250 }
251 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000252 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000253 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +0000254 Py_SIZE(v) = ndigits;
Tim Petersce9de2f2001-06-14 04:56:19 +0000255 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000256 *p++ = (digit)(ival & PyLong_MASK);
257 ival >>= PyLong_SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000258 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000259 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000260 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000261}
262
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000263/* Create a new long int object from a C double */
264
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000265PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000266PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000267{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000268 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000269 double frac;
270 int i, ndig, expo, neg;
271 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000272 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000273 PyErr_SetString(PyExc_OverflowError,
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000274 "cannot convert float infinity to integer");
Guido van Rossum1a23c241999-09-27 17:11:52 +0000275 return NULL;
276 }
Christian Heimesa34706f2008-01-04 03:06:10 +0000277 if (Py_IS_NAN(dval)) {
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000278 PyErr_SetString(PyExc_ValueError,
279 "cannot convert float NaN to integer");
Christian Heimes386cd1e2008-01-15 02:01:20 +0000280 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +0000281 }
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000282 if (dval < 0.0) {
283 neg = 1;
284 dval = -dval;
285 }
286 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
287 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000288 return PyLong_FromLong(0L);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000289 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000290 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000291 if (v == NULL)
292 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000293 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000294 for (i = ndig; --i >= 0; ) {
295 long bits = (long)frac;
Guido van Rossum2095d241997-04-09 19:41:24 +0000296 v->ob_digit[i] = (digit) bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000297 frac = frac - (double)bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000298 frac = ldexp(frac, PyLong_SHIFT);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000299 }
300 if (neg)
Christian Heimes90aa7642007-12-19 02:45:37 +0000301 Py_SIZE(v) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000302 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000303}
304
Thomas Wouters89f507f2006-12-13 04:49:30 +0000305/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
306 * anything about what happens when a signed integer operation overflows,
307 * and some compilers think they're doing you a favor by being "clever"
308 * then. The bit pattern for the largest postive signed long is
309 * (unsigned long)LONG_MAX, and for the smallest negative signed long
310 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
311 * However, some other compilers warn about applying unary minus to an
312 * unsigned operand. Hence the weird "0-".
313 */
314#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
315#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
316
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000317/* Get a C long int from a long int object.
318 Returns -1 and sets an error condition if overflow occurs. */
319
320long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000321PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000322{
Guido van Rossumf7531811998-05-26 14:33:37 +0000323 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000324 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000325 unsigned long x, prev;
Georg Brandl61c31b02007-02-26 14:46:30 +0000326 long res;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000327 Py_ssize_t i;
328 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000329 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000330
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000331 *overflow = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000332 if (vv == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000333 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000334 return -1;
335 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000336
337 if (!PyLong_Check(vv)) {
338 PyNumberMethods *nb;
339 if ((nb = vv->ob_type->tp_as_number) == NULL ||
340 nb->nb_int == NULL) {
341 PyErr_SetString(PyExc_TypeError, "an integer is required");
342 return -1;
343 }
344 vv = (*nb->nb_int) (vv);
345 if (vv == NULL)
346 return -1;
347 do_decref = 1;
348 if (!PyLong_Check(vv)) {
349 Py_DECREF(vv);
350 PyErr_SetString(PyExc_TypeError,
351 "nb_int should return int object");
352 return -1;
353 }
354 }
355
Georg Brandl61c31b02007-02-26 14:46:30 +0000356 res = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000357 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000358 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000359
Georg Brandl61c31b02007-02-26 14:46:30 +0000360 switch (i) {
361 case -1:
362 res = -v->ob_digit[0];
363 break;
364 case 0:
365 res = 0;
366 break;
367 case 1:
368 res = v->ob_digit[0];
369 break;
370 default:
371 sign = 1;
372 x = 0;
373 if (i < 0) {
374 sign = -1;
375 i = -(i);
376 }
377 while (--i >= 0) {
378 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000379 x = (x << PyLong_SHIFT) + v->ob_digit[i];
380 if ((x >> PyLong_SHIFT) != prev) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000381 *overflow = Py_SIZE(v) > 0 ? 1 : -1;
Georg Brandl61c31b02007-02-26 14:46:30 +0000382 goto exit;
383 }
384 }
385 /* Haven't lost any bits, but casting to long requires extra care
386 * (see comment above).
387 */
388 if (x <= (unsigned long)LONG_MAX) {
389 res = (long)x * sign;
390 }
391 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
392 res = LONG_MIN;
393 }
394 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000395 *overflow = Py_SIZE(v) > 0 ? 1 : -1;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000396 /* res is already set to -1 */
Georg Brandl61c31b02007-02-26 14:46:30 +0000397 }
398 }
399 exit:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000400 if (do_decref) {
401 Py_DECREF(vv);
402 }
Georg Brandl61c31b02007-02-26 14:46:30 +0000403 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000404}
405
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000406long
407PyLong_AsLong(PyObject *obj)
408{
409 int overflow;
410 long result = PyLong_AsLongAndOverflow(obj, &overflow);
411 if (overflow) {
412 /* XXX: could be cute and give a different
413 message for overflow == -1 */
414 PyErr_SetString(PyExc_OverflowError,
415 "Python int too large to convert to C long");
416 }
417 return result;
418}
419
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000420/* Get a Py_ssize_t from a long int object.
421 Returns -1 and sets an error condition if overflow occurs. */
422
423Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000424PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000425 register PyLongObject *v;
426 size_t x, prev;
427 Py_ssize_t i;
428 int sign;
429
430 if (vv == NULL || !PyLong_Check(vv)) {
431 PyErr_BadInternalCall();
432 return -1;
433 }
434 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000435 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000436 switch (i) {
437 case -1: return -v->ob_digit[0];
438 case 0: return 0;
439 case 1: return v->ob_digit[0];
440 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000441 sign = 1;
442 x = 0;
443 if (i < 0) {
444 sign = -1;
445 i = -(i);
446 }
447 while (--i >= 0) {
448 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000449 x = (x << PyLong_SHIFT) + v->ob_digit[i];
450 if ((x >> PyLong_SHIFT) != prev)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000451 goto overflow;
452 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000453 /* Haven't lost any bits, but casting to a signed type requires
454 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000455 */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000456 if (x <= (size_t)PY_SSIZE_T_MAX) {
457 return (Py_ssize_t)x * sign;
458 }
459 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
460 return PY_SSIZE_T_MIN;
461 }
462 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000463
464 overflow:
465 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000466 "Python int too large to convert to C ssize_t");
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000467 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000468}
469
Guido van Rossumd8c80482002-08-13 00:24:58 +0000470/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000471 Returns -1 and sets an error condition if overflow occurs. */
472
473unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000474PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000475{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000476 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000477 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000478 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000479
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000480 if (vv == NULL || !PyLong_Check(vv)) {
481 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000482 return (unsigned long) -1;
483 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000484 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000485 i = Py_SIZE(v);
Guido van Rossum53756b11997-01-03 17:14:46 +0000486 x = 0;
487 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000488 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000489 "can't convert negative value to unsigned int");
Guido van Rossum53756b11997-01-03 17:14:46 +0000490 return (unsigned long) -1;
491 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000492 switch (i) {
493 case 0: return 0;
494 case 1: return v->ob_digit[0];
495 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000496 while (--i >= 0) {
497 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000498 x = (x << PyLong_SHIFT) + v->ob_digit[i];
499 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000500 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000501 "python int too large to convert to C unsigned long");
Guido van Rossumddefaf32007-01-14 03:31:43 +0000502 return (unsigned long) -1;
503 }
504 }
505 return x;
506}
507
508/* Get a C unsigned long int from a long int object.
509 Returns -1 and sets an error condition if overflow occurs. */
510
511size_t
512PyLong_AsSize_t(PyObject *vv)
513{
514 register PyLongObject *v;
515 size_t x, prev;
516 Py_ssize_t i;
517
518 if (vv == NULL || !PyLong_Check(vv)) {
519 PyErr_BadInternalCall();
520 return (unsigned long) -1;
521 }
522 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000523 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000524 x = 0;
525 if (i < 0) {
526 PyErr_SetString(PyExc_OverflowError,
527 "can't convert negative value to size_t");
528 return (size_t) -1;
529 }
530 switch (i) {
531 case 0: return 0;
532 case 1: return v->ob_digit[0];
533 }
534 while (--i >= 0) {
535 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000536 x = (x << PyLong_SHIFT) + v->ob_digit[i];
537 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000538 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000539 "Python int too large to convert to C size_t");
Guido van Rossum53756b11997-01-03 17:14:46 +0000540 return (unsigned long) -1;
541 }
542 }
543 return x;
544}
545
Thomas Hellera4ea6032003-04-17 18:55:45 +0000546/* Get a C unsigned long int from a long int object, ignoring the high bits.
547 Returns -1 and sets an error condition if an error occurs. */
548
Guido van Rossumddefaf32007-01-14 03:31:43 +0000549static unsigned long
550_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000551{
552 register PyLongObject *v;
553 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000554 Py_ssize_t i;
555 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000556
557 if (vv == NULL || !PyLong_Check(vv)) {
558 PyErr_BadInternalCall();
559 return (unsigned long) -1;
560 }
561 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000562 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000563 switch (i) {
564 case 0: return 0;
565 case 1: return v->ob_digit[0];
566 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000567 sign = 1;
568 x = 0;
569 if (i < 0) {
570 sign = -1;
571 i = -i;
572 }
573 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000574 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +0000575 }
576 return x * sign;
577}
578
Guido van Rossumddefaf32007-01-14 03:31:43 +0000579unsigned long
580PyLong_AsUnsignedLongMask(register PyObject *op)
581{
582 PyNumberMethods *nb;
583 PyLongObject *lo;
584 unsigned long val;
585
586 if (op && PyLong_Check(op))
587 return _PyLong_AsUnsignedLongMask(op);
588
589 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
590 nb->nb_int == NULL) {
591 PyErr_SetString(PyExc_TypeError, "an integer is required");
592 return (unsigned long)-1;
593 }
594
595 lo = (PyLongObject*) (*nb->nb_int) (op);
596 if (lo == NULL)
597 return (unsigned long)-1;
598 if (PyLong_Check(lo)) {
599 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
600 Py_DECREF(lo);
601 if (PyErr_Occurred())
602 return (unsigned long)-1;
603 return val;
604 }
605 else
606 {
607 Py_DECREF(lo);
608 PyErr_SetString(PyExc_TypeError,
609 "nb_int should return int object");
610 return (unsigned long)-1;
611 }
612}
613
Tim Peters5b8132f2003-01-31 15:52:05 +0000614int
615_PyLong_Sign(PyObject *vv)
616{
617 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000618
619 assert(v != NULL);
620 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000621
Christian Heimes90aa7642007-12-19 02:45:37 +0000622 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000623}
624
Tim Petersbaefd9e2003-01-28 20:37:45 +0000625size_t
626_PyLong_NumBits(PyObject *vv)
627{
628 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000629 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000630 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000631
632 assert(v != NULL);
633 assert(PyLong_Check(v));
Christian Heimes90aa7642007-12-19 02:45:37 +0000634 ndigits = ABS(Py_SIZE(v));
Tim Petersbaefd9e2003-01-28 20:37:45 +0000635 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
636 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000637 digit msd = v->ob_digit[ndigits - 1];
638
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000639 result = (ndigits - 1) * PyLong_SHIFT;
640 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000641 goto Overflow;
642 do {
643 ++result;
644 if (result == 0)
645 goto Overflow;
646 msd >>= 1;
647 } while (msd);
648 }
649 return result;
650
651Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000652 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
Tim Petersbaefd9e2003-01-28 20:37:45 +0000653 "to express in a platform size_t");
654 return (size_t)-1;
655}
656
Tim Peters2a9b3672001-06-11 21:23:58 +0000657PyObject *
658_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
659 int little_endian, int is_signed)
660{
661 const unsigned char* pstartbyte;/* LSB of bytes */
662 int incr; /* direction to move pstartbyte */
663 const unsigned char* pendbyte; /* MSB of bytes */
664 size_t numsignificantbytes; /* number of bytes that matter */
665 size_t ndigits; /* number of Python long digits */
666 PyLongObject* v; /* result */
667 int idigit = 0; /* next free index in v->ob_digit */
668
669 if (n == 0)
670 return PyLong_FromLong(0L);
671
672 if (little_endian) {
673 pstartbyte = bytes;
674 pendbyte = bytes + n - 1;
675 incr = 1;
676 }
677 else {
678 pstartbyte = bytes + n - 1;
679 pendbyte = bytes;
680 incr = -1;
681 }
682
683 if (is_signed)
684 is_signed = *pendbyte >= 0x80;
685
686 /* Compute numsignificantbytes. This consists of finding the most
687 significant byte. Leading 0 bytes are insignficant if the number
688 is positive, and leading 0xff bytes if negative. */
689 {
690 size_t i;
691 const unsigned char* p = pendbyte;
692 const int pincr = -incr; /* search MSB to LSB */
693 const unsigned char insignficant = is_signed ? 0xff : 0x00;
694
695 for (i = 0; i < n; ++i, p += pincr) {
696 if (*p != insignficant)
697 break;
698 }
699 numsignificantbytes = n - i;
700 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
701 actually has 2 significant bytes. OTOH, 0xff0001 ==
702 -0x00ffff, so we wouldn't *need* to bump it there; but we
703 do for 0xffff = -0x0001. To be safe without bothering to
704 check every case, bump it regardless. */
705 if (is_signed && numsignificantbytes < n)
706 ++numsignificantbytes;
707 }
708
709 /* How many Python long digits do we need? We have
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000710 8*numsignificantbytes bits, and each Python long digit has PyLong_SHIFT
Tim Peters2a9b3672001-06-11 21:23:58 +0000711 bits, so it's the ceiling of the quotient. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000712 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
Tim Peters2a9b3672001-06-11 21:23:58 +0000713 if (ndigits > (size_t)INT_MAX)
714 return PyErr_NoMemory();
715 v = _PyLong_New((int)ndigits);
716 if (v == NULL)
717 return NULL;
718
719 /* Copy the bits over. The tricky parts are computing 2's-comp on
720 the fly for signed numbers, and dealing with the mismatch between
721 8-bit bytes and (probably) 15-bit Python digits.*/
722 {
723 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000724 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000725 twodigits accum = 0; /* sliding register */
726 unsigned int accumbits = 0; /* number of bits in accum */
727 const unsigned char* p = pstartbyte;
728
729 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000730 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000731 /* Compute correction for 2's comp, if needed. */
732 if (is_signed) {
733 thisbyte = (0xff ^ thisbyte) + carry;
734 carry = thisbyte >> 8;
735 thisbyte &= 0xff;
736 }
737 /* Because we're going LSB to MSB, thisbyte is
738 more significant than what's already in accum,
739 so needs to be prepended to accum. */
740 accum |= thisbyte << accumbits;
741 accumbits += 8;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000742 if (accumbits >= PyLong_SHIFT) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000743 /* There's enough to fill a Python digit. */
744 assert(idigit < (int)ndigits);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000745 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Tim Peters2a9b3672001-06-11 21:23:58 +0000746 ++idigit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000747 accum >>= PyLong_SHIFT;
748 accumbits -= PyLong_SHIFT;
749 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000750 }
751 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000752 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000753 if (accumbits) {
754 assert(idigit < (int)ndigits);
755 v->ob_digit[idigit] = (digit)accum;
756 ++idigit;
757 }
758 }
759
Christian Heimes90aa7642007-12-19 02:45:37 +0000760 Py_SIZE(v) = is_signed ? -idigit : idigit;
Tim Peters2a9b3672001-06-11 21:23:58 +0000761 return (PyObject *)long_normalize(v);
762}
763
764int
765_PyLong_AsByteArray(PyLongObject* v,
766 unsigned char* bytes, size_t n,
767 int little_endian, int is_signed)
768{
769 int i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000770 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000771 twodigits accum; /* sliding register */
772 unsigned int accumbits; /* # bits in accum */
773 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
774 twodigits carry; /* for computing 2's-comp */
775 size_t j; /* # bytes filled */
776 unsigned char* p; /* pointer to next byte in bytes */
777 int pincr; /* direction to move p */
778
779 assert(v != NULL && PyLong_Check(v));
780
Christian Heimes90aa7642007-12-19 02:45:37 +0000781 if (Py_SIZE(v) < 0) {
782 ndigits = -(Py_SIZE(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000783 if (!is_signed) {
784 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000785 "can't convert negative int to unsigned");
Tim Peters2a9b3672001-06-11 21:23:58 +0000786 return -1;
787 }
788 do_twos_comp = 1;
789 }
790 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000791 ndigits = Py_SIZE(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000792 do_twos_comp = 0;
793 }
794
795 if (little_endian) {
796 p = bytes;
797 pincr = 1;
798 }
799 else {
800 p = bytes + n - 1;
801 pincr = -1;
802 }
803
Tim Peters898cf852001-06-13 20:50:08 +0000804 /* Copy over all the Python digits.
805 It's crucial that every Python digit except for the MSD contribute
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000806 exactly PyLong_SHIFT bits to the total, so first assert that the long is
Tim Peters898cf852001-06-13 20:50:08 +0000807 normalized. */
808 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000809 j = 0;
810 accum = 0;
811 accumbits = 0;
812 carry = do_twos_comp ? 1 : 0;
813 for (i = 0; i < ndigits; ++i) {
814 twodigits thisdigit = v->ob_digit[i];
815 if (do_twos_comp) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000816 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
817 carry = thisdigit >> PyLong_SHIFT;
818 thisdigit &= PyLong_MASK;
Tim Peters2a9b3672001-06-11 21:23:58 +0000819 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000820 /* Because we're going LSB to MSB, thisdigit is more
821 significant than what's already in accum, so needs to be
822 prepended to accum. */
823 accum |= thisdigit << accumbits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000824 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000825
Tim Petersede05092001-06-14 08:53:38 +0000826 /* The most-significant digit may be (probably is) at least
827 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000828 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000829 /* Count # of sign bits -- they needn't be stored,
830 * although for signed conversion we need later to
831 * make sure at least one sign bit gets stored.
832 * First shift conceptual sign bit to real sign bit.
833 */
834 stwodigits s = (stwodigits)(thisdigit <<
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000835 (8*sizeof(stwodigits) - PyLong_SHIFT));
Tim Peters7a3bfc32001-06-12 01:22:22 +0000836 unsigned int nsignbits = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000837 while ((s < 0) == do_twos_comp && nsignbits < PyLong_SHIFT) {
Tim Peters7a3bfc32001-06-12 01:22:22 +0000838 ++nsignbits;
Tim Petersede05092001-06-14 08:53:38 +0000839 s <<= 1;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000840 }
Tim Petersede05092001-06-14 08:53:38 +0000841 accumbits -= nsignbits;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000842 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000843
Tim Peters2a9b3672001-06-11 21:23:58 +0000844 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000845 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000846 if (j >= n)
847 goto Overflow;
848 ++j;
849 *p = (unsigned char)(accum & 0xff);
850 p += pincr;
851 accumbits -= 8;
852 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000853 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000854 }
855
856 /* Store the straggler (if any). */
857 assert(accumbits < 8);
858 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000859 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000860 if (j >= n)
861 goto Overflow;
862 ++j;
863 if (do_twos_comp) {
864 /* Fill leading bits of the byte with sign bits
865 (appropriately pretending that the long had an
866 infinite supply of sign bits). */
867 accum |= (~(twodigits)0) << accumbits;
868 }
869 *p = (unsigned char)(accum & 0xff);
870 p += pincr;
871 }
Tim Peters05607ad2001-06-13 21:01:27 +0000872 else if (j == n && n > 0 && is_signed) {
873 /* The main loop filled the byte array exactly, so the code
874 just above didn't get to ensure there's a sign bit, and the
875 loop below wouldn't add one either. Make sure a sign bit
876 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000877 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000878 int sign_bit_set = msb >= 0x80;
879 assert(accumbits == 0);
880 if (sign_bit_set == do_twos_comp)
881 return 0;
882 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000883 goto Overflow;
884 }
Tim Peters05607ad2001-06-13 21:01:27 +0000885
886 /* Fill remaining bytes with copies of the sign bit. */
887 {
888 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
889 for ( ; j < n; ++j, p += pincr)
890 *p = signbyte;
891 }
892
Tim Peters2a9b3672001-06-11 21:23:58 +0000893 return 0;
894
895Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000896 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
Tim Peters2a9b3672001-06-11 21:23:58 +0000897 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000898
Tim Peters2a9b3672001-06-11 21:23:58 +0000899}
900
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000901double
902_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
903{
904/* NBITS_WANTED should be > the number of bits in a double's precision,
905 but small enough so that 2**NBITS_WANTED is within the normal double
906 range. nbitsneeded is set to 1 less than that because the most-significant
907 Python digit contains at least 1 significant bit, but we don't want to
908 bother counting them (catering to the worst case cheaply).
909
910 57 is one more than VAX-D double precision; I (Tim) don't know of a double
911 format with more precision than that; it's 1 larger so that we add in at
912 least one round bit to stand in for the ignored least-significant bits.
913*/
914#define NBITS_WANTED 57
915 PyLongObject *v;
916 double x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000917 const double multiplier = (double)(1L << PyLong_SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000918 Py_ssize_t i;
919 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000920 int nbitsneeded;
921
922 if (vv == NULL || !PyLong_Check(vv)) {
923 PyErr_BadInternalCall();
924 return -1;
925 }
926 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000927 i = Py_SIZE(v);
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000928 sign = 1;
929 if (i < 0) {
930 sign = -1;
931 i = -(i);
932 }
933 else if (i == 0) {
934 *exponent = 0;
935 return 0.0;
936 }
937 --i;
938 x = (double)v->ob_digit[i];
939 nbitsneeded = NBITS_WANTED - 1;
940 /* Invariant: i Python digits remain unaccounted for. */
941 while (i > 0 && nbitsneeded > 0) {
942 --i;
943 x = x * multiplier + (double)v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000944 nbitsneeded -= PyLong_SHIFT;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000945 }
946 /* There are i digits we didn't shift in. Pretending they're all
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000947 zeroes, the true value is x * 2**(i*PyLong_SHIFT). */
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000948 *exponent = i;
949 assert(x > 0.0);
950 return x * sign;
951#undef NBITS_WANTED
952}
953
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000954/* Get a C double from a long int object. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000955
956double
Tim Peters9f688bf2000-07-07 15:53:28 +0000957PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000958{
Thomas Wouters553489a2006-02-01 21:32:04 +0000959 int e = -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000960 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000961
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000962 if (vv == NULL || !PyLong_Check(vv)) {
963 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000964 return -1;
965 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000966 x = _PyLong_AsScaledDouble(vv, &e);
967 if (x == -1.0 && PyErr_Occurred())
968 return -1.0;
Thomas Wouters553489a2006-02-01 21:32:04 +0000969 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
970 set correctly after a successful _PyLong_AsScaledDouble() call */
971 assert(e >= 0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000972 if (e > INT_MAX / PyLong_SHIFT)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000973 goto overflow;
974 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000975 x = ldexp(x, e * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +0000976 if (Py_OVERFLOWED(x))
Tim Peters9fffa3e2001-09-04 05:14:19 +0000977 goto overflow;
978 return x;
979
980overflow:
981 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000982 "Python int too large to convert to C double");
Tim Peters9fffa3e2001-09-04 05:14:19 +0000983 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000984}
985
Guido van Rossum78694d91998-09-18 14:14:13 +0000986/* Create a new long (or int) object from a C pointer */
987
988PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000989PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000990{
Tim Peters70128a12001-06-16 08:48:40 +0000991#ifndef HAVE_LONG_LONG
992# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
993#endif
994#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000995# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000996#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000997 /* special-case null pointer */
998 if (!p)
Christian Heimes217cfd12007-12-02 14:31:20 +0000999 return PyLong_FromLong(0);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001000 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +00001001
Guido van Rossum78694d91998-09-18 14:14:13 +00001002}
1003
1004/* Get a C pointer from a long object (or an int object in some cases) */
1005
1006void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001007PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001008{
1009 /* This function will allow int or long objects. If vv is neither,
1010 then the PyLong_AsLong*() functions will raise the exception:
1011 PyExc_SystemError, "bad argument to internal function"
1012 */
Tim Peters70128a12001-06-16 08:48:40 +00001013#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +00001014 long x;
1015
Guido van Rossumddefaf32007-01-14 03:31:43 +00001016 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001017 x = PyLong_AsLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001018 else
1019 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001020#else
Tim Peters70128a12001-06-16 08:48:40 +00001021
1022#ifndef HAVE_LONG_LONG
1023# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1024#endif
1025#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001026# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001027#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001028 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001029
Guido van Rossumddefaf32007-01-14 03:31:43 +00001030 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001031 x = PyLong_AsLongLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001032 else
1033 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001034
1035#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001036
1037 if (x == -1 && PyErr_Occurred())
1038 return NULL;
1039 return (void *)x;
1040}
1041
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001042#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001043
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001044/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001045 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001046 */
1047
Tim Peterscf37dfc2001-06-14 18:42:50 +00001048#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +00001049
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001050/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001051
1052PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001053PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001054{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001055 PyLongObject *v;
Christian Heimesdae2a892008-04-19 00:55:37 +00001056 unsigned PY_LONG_LONG abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001057 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1058 int ndigits = 0;
1059 int negative = 0;
1060
Guido van Rossumddefaf32007-01-14 03:31:43 +00001061 CHECK_SMALL_INT(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001062 if (ival < 0) {
Christian Heimesdae2a892008-04-19 00:55:37 +00001063 /* avoid signed overflow on negation; see comments
1064 in PyLong_FromLong above. */
1065 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001066 negative = 1;
1067 }
Christian Heimesdae2a892008-04-19 00:55:37 +00001068 else {
1069 abs_ival = (unsigned PY_LONG_LONG)ival;
1070 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001071
1072 /* Count the number of Python digits.
1073 We used to pick 5 ("big enough for anything"), but that's a
1074 waste of time and space given that 5*15 = 75 bits are rarely
1075 needed. */
Christian Heimesdae2a892008-04-19 00:55:37 +00001076 t = abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001077 while (t) {
1078 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001079 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001080 }
1081 v = _PyLong_New(ndigits);
1082 if (v != NULL) {
1083 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001084 Py_SIZE(v) = negative ? -ndigits : ndigits;
Christian Heimesdae2a892008-04-19 00:55:37 +00001085 t = abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001086 while (t) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001087 *p++ = (digit)(t & PyLong_MASK);
1088 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001089 }
1090 }
1091 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001092}
1093
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001094/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001095
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001096PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001097PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001098{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001099 PyLongObject *v;
1100 unsigned PY_LONG_LONG t;
1101 int ndigits = 0;
1102
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001103 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001104 return PyLong_FromLong(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001105 /* Count the number of Python digits. */
1106 t = (unsigned PY_LONG_LONG)ival;
1107 while (t) {
1108 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001109 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001110 }
1111 v = _PyLong_New(ndigits);
1112 if (v != NULL) {
1113 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001114 Py_SIZE(v) = ndigits;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001115 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001116 *p++ = (digit)(ival & PyLong_MASK);
1117 ival >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001118 }
1119 }
1120 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001121}
1122
Martin v. Löwis18e16552006-02-15 17:27:45 +00001123/* Create a new long int object from a C Py_ssize_t. */
1124
1125PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001126PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001127{
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001128 PyLongObject *v;
1129 size_t abs_ival;
1130 size_t t; /* unsigned so >> doesn't propagate sign bit */
1131 int ndigits = 0;
1132 int negative = 0;
1133
1134 CHECK_SMALL_INT(ival);
1135 if (ival < 0) {
1136 /* avoid signed overflow when ival = SIZE_T_MIN */
1137 abs_ival = (size_t)(-1-ival)+1;
1138 negative = 1;
1139 }
1140 else {
1141 abs_ival = (size_t)ival;
1142 }
1143
1144 /* Count the number of Python digits. */
1145 t = abs_ival;
1146 while (t) {
1147 ++ndigits;
1148 t >>= PyLong_SHIFT;
1149 }
1150 v = _PyLong_New(ndigits);
1151 if (v != NULL) {
1152 digit *p = v->ob_digit;
1153 Py_SIZE(v) = negative ? -ndigits : ndigits;
1154 t = abs_ival;
1155 while (t) {
1156 *p++ = (digit)(t & PyLong_MASK);
1157 t >>= PyLong_SHIFT;
1158 }
1159 }
1160 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001161}
1162
1163/* Create a new long int object from a C size_t. */
1164
1165PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001166PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001167{
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001168 PyLongObject *v;
1169 size_t t;
1170 int ndigits = 0;
1171
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001172 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001173 return PyLong_FromLong(ival);
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001174 /* Count the number of Python digits. */
1175 t = ival;
1176 while (t) {
1177 ++ndigits;
1178 t >>= PyLong_SHIFT;
1179 }
1180 v = _PyLong_New(ndigits);
1181 if (v != NULL) {
1182 digit *p = v->ob_digit;
1183 Py_SIZE(v) = ndigits;
1184 while (ival) {
1185 *p++ = (digit)(ival & PyLong_MASK);
1186 ival >>= PyLong_SHIFT;
1187 }
1188 }
1189 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001190}
1191
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001192/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001193 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001194
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001195PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001196PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001197{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001198 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001199 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001200 int one = 1;
1201 int res;
1202
Tim Petersd38b1c72001-09-30 05:09:37 +00001203 if (vv == NULL) {
1204 PyErr_BadInternalCall();
1205 return -1;
1206 }
1207 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001208 PyNumberMethods *nb;
1209 PyObject *io;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001210 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1211 nb->nb_int == NULL) {
1212 PyErr_SetString(PyExc_TypeError, "an integer is required");
1213 return -1;
1214 }
1215 io = (*nb->nb_int) (vv);
1216 if (io == NULL)
1217 return -1;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001218 if (PyLong_Check(io)) {
1219 bytes = PyLong_AsLongLong(io);
1220 Py_DECREF(io);
1221 return bytes;
1222 }
1223 Py_DECREF(io);
1224 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001225 return -1;
1226 }
1227
Guido van Rossumddefaf32007-01-14 03:31:43 +00001228 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001229 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001230 case -1: return -v->ob_digit[0];
1231 case 0: return 0;
1232 case 1: return v->ob_digit[0];
1233 }
Tim Petersd1a7da62001-06-13 00:35:57 +00001234 res = _PyLong_AsByteArray(
1235 (PyLongObject *)vv, (unsigned char *)&bytes,
1236 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001237
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001238 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001239 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001240 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001241 else
1242 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001243}
1244
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001245/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001246 Return -1 and set an error if overflow occurs. */
1247
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001248unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001249PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001250{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001251 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001252 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001253 int one = 1;
1254 int res;
1255
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001256 if (vv == NULL || !PyLong_Check(vv)) {
1257 PyErr_BadInternalCall();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001258 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001259 }
1260
Guido van Rossumddefaf32007-01-14 03:31:43 +00001261 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001262 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001263 case 0: return 0;
1264 case 1: return v->ob_digit[0];
1265 }
1266
Tim Petersd1a7da62001-06-13 00:35:57 +00001267 res = _PyLong_AsByteArray(
1268 (PyLongObject *)vv, (unsigned char *)&bytes,
1269 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001270
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001271 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001272 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001273 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001274 else
1275 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001276}
Tim Petersd1a7da62001-06-13 00:35:57 +00001277
Thomas Hellera4ea6032003-04-17 18:55:45 +00001278/* Get a C unsigned long int from a long int object, ignoring the high bits.
1279 Returns -1 and sets an error condition if an error occurs. */
1280
Guido van Rossumddefaf32007-01-14 03:31:43 +00001281static unsigned PY_LONG_LONG
1282_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001283{
1284 register PyLongObject *v;
1285 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001286 Py_ssize_t i;
1287 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001288
1289 if (vv == NULL || !PyLong_Check(vv)) {
1290 PyErr_BadInternalCall();
1291 return (unsigned long) -1;
1292 }
1293 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001294 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001295 case 0: return 0;
1296 case 1: return v->ob_digit[0];
1297 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001298 i = Py_SIZE(v);
Thomas Hellera4ea6032003-04-17 18:55:45 +00001299 sign = 1;
1300 x = 0;
1301 if (i < 0) {
1302 sign = -1;
1303 i = -i;
1304 }
1305 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001306 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +00001307 }
1308 return x * sign;
1309}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001310
1311unsigned PY_LONG_LONG
1312PyLong_AsUnsignedLongLongMask(register PyObject *op)
1313{
1314 PyNumberMethods *nb;
1315 PyLongObject *lo;
1316 unsigned PY_LONG_LONG val;
1317
1318 if (op && PyLong_Check(op))
1319 return _PyLong_AsUnsignedLongLongMask(op);
1320
1321 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1322 nb->nb_int == NULL) {
1323 PyErr_SetString(PyExc_TypeError, "an integer is required");
1324 return (unsigned PY_LONG_LONG)-1;
1325 }
1326
1327 lo = (PyLongObject*) (*nb->nb_int) (op);
1328 if (lo == NULL)
1329 return (unsigned PY_LONG_LONG)-1;
1330 if (PyLong_Check(lo)) {
1331 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1332 Py_DECREF(lo);
1333 if (PyErr_Occurred())
1334 return (unsigned PY_LONG_LONG)-1;
1335 return val;
1336 }
1337 else
1338 {
1339 Py_DECREF(lo);
1340 PyErr_SetString(PyExc_TypeError,
1341 "nb_int should return int object");
1342 return (unsigned PY_LONG_LONG)-1;
1343 }
1344}
Tim Petersd1a7da62001-06-13 00:35:57 +00001345#undef IS_LITTLE_ENDIAN
1346
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001347#endif /* HAVE_LONG_LONG */
1348
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00001349#define CHECK_BINOP(v,w) \
1350 if (!PyLong_Check(v) || !PyLong_Check(w)) { \
Neil Schemenauerba872e22001-01-04 01:46:03 +00001351 Py_INCREF(Py_NotImplemented); \
1352 return Py_NotImplemented; \
1353 }
1354
Tim Peters877a2122002-08-12 05:09:36 +00001355/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1356 * is modified in place, by adding y to it. Carries are propagated as far as
1357 * x[m-1], and the remaining carry (0 or 1) is returned.
1358 */
1359static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001360v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001361{
1362 int i;
1363 digit carry = 0;
1364
1365 assert(m >= n);
1366 for (i = 0; i < n; ++i) {
1367 carry += x[i] + y[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001368 x[i] = carry & PyLong_MASK;
1369 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001370 assert((carry & 1) == carry);
1371 }
1372 for (; carry && i < m; ++i) {
1373 carry += x[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001374 x[i] = carry & PyLong_MASK;
1375 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001376 assert((carry & 1) == carry);
1377 }
1378 return carry;
1379}
1380
1381/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1382 * is modified in place, by subtracting y from it. Borrows are propagated as
1383 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1384 */
1385static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001386v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001387{
1388 int i;
1389 digit borrow = 0;
1390
1391 assert(m >= n);
1392 for (i = 0; i < n; ++i) {
1393 borrow = x[i] - y[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001394 x[i] = borrow & PyLong_MASK;
1395 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001396 borrow &= 1; /* keep only 1 sign bit */
1397 }
1398 for (; borrow && i < m; ++i) {
1399 borrow = x[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001400 x[i] = borrow & PyLong_MASK;
1401 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001402 borrow &= 1;
1403 }
1404 return borrow;
1405}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001406
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001407/* Multiply by a single digit, ignoring the sign. */
1408
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001409static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001410mul1(PyLongObject *a, wdigit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001411{
1412 return muladd1(a, n, (digit)0);
1413}
1414
1415/* Multiply by a single digit and add a single digit, ignoring the sign. */
1416
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001417static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001418muladd1(PyLongObject *a, wdigit n, wdigit extra)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001419{
Christian Heimes90aa7642007-12-19 02:45:37 +00001420 Py_ssize_t size_a = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001421 PyLongObject *z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001422 twodigits carry = extra;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001423 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001424
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001425 if (z == NULL)
1426 return NULL;
1427 for (i = 0; i < size_a; ++i) {
1428 carry += (twodigits)a->ob_digit[i] * n;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001429 z->ob_digit[i] = (digit) (carry & PyLong_MASK);
1430 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001431 }
Guido van Rossum2095d241997-04-09 19:41:24 +00001432 z->ob_digit[i] = (digit) carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001433 return long_normalize(z);
1434}
1435
Tim Peters212e6142001-07-14 12:23:19 +00001436/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1437 in pout, and returning the remainder. pin and pout point at the LSD.
1438 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001439 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001440 immutable. */
1441
1442static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001443inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001444{
1445 twodigits rem = 0;
1446
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001447 assert(n > 0 && n <= PyLong_MASK);
Tim Peters212e6142001-07-14 12:23:19 +00001448 pin += size;
1449 pout += size;
1450 while (--size >= 0) {
1451 digit hi;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001452 rem = (rem << PyLong_SHIFT) + *--pin;
Tim Peters212e6142001-07-14 12:23:19 +00001453 *--pout = hi = (digit)(rem / n);
1454 rem -= hi * n;
1455 }
1456 return (digit)rem;
1457}
1458
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001459/* Divide a long integer by a digit, returning both the quotient
1460 (as function result) and the remainder (through *prem).
1461 The sign of a is ignored; n should not be zero. */
1462
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001463static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001464divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001465{
Christian Heimes90aa7642007-12-19 02:45:37 +00001466 const Py_ssize_t size = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001467 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001468
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001469 assert(n > 0 && n <= PyLong_MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001470 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001471 if (z == NULL)
1472 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001473 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001474 return long_normalize(z);
1475}
1476
1477/* Convert a long int object to a string, using a given conversion base.
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001478 Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001479 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001480
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001481PyObject *
1482_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001483{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001484 register PyLongObject *a = (PyLongObject *)aa;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001485 PyObject *str;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001486 Py_ssize_t i, j, sz;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001487 Py_ssize_t size_a;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001488 Py_UNICODE *p;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001489 int bits;
1490 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001491
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001492 if (a == NULL || !PyLong_Check(a)) {
1493 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001494 return NULL;
1495 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001496 assert(base >= 2 && base <= 36);
Christian Heimes90aa7642007-12-19 02:45:37 +00001497 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001498
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001499 /* Compute a rough upper bound for the length of the string */
1500 i = base;
1501 bits = 0;
1502 while (i > 1) {
1503 ++bits;
1504 i >>= 1;
1505 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001506 i = 5;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001507 j = size_a*PyLong_SHIFT + bits-1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001508 sz = i + j / bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001509 if (j / PyLong_SHIFT < size_a || sz < i) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001510 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001511 "int is too large to format");
Thomas Wouters89f507f2006-12-13 04:49:30 +00001512 return NULL;
1513 }
Walter Dörwald1ab83302007-05-18 17:15:44 +00001514 str = PyUnicode_FromUnicode(NULL, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001515 if (str == NULL)
1516 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001517 p = PyUnicode_AS_UNICODE(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001518 *p = '\0';
Christian Heimes90aa7642007-12-19 02:45:37 +00001519 if (Py_SIZE(a) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001520 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001521
Christian Heimes90aa7642007-12-19 02:45:37 +00001522 if (Py_SIZE(a) == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001523 *--p = '0';
1524 }
1525 else if ((base & (base - 1)) == 0) {
1526 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001527 twodigits accum = 0;
1528 int accumbits = 0; /* # of bits in accum */
1529 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001530 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001531 while ((i >>= 1) > 1)
1532 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001533
1534 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001535 accum |= (twodigits)a->ob_digit[i] << accumbits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001536 accumbits += PyLong_SHIFT;
Tim Peters586b2e32001-07-15 09:11:14 +00001537 assert(accumbits >= basebits);
1538 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001539 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001540 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001541 assert(p > PyUnicode_AS_UNICODE(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001542 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001543 accumbits -= basebits;
1544 accum >>= basebits;
1545 } while (i < size_a-1 ? accumbits >= basebits :
1546 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001547 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001548 }
1549 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001550 /* Not 0, and base not a power of 2. Divide repeatedly by
1551 base, but for speed use the highest power of base that
1552 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001553 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001554 digit *pin = a->ob_digit;
1555 PyLongObject *scratch;
1556 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001557 digit powbase = base; /* powbase == base ** power */
1558 int power = 1;
1559 for (;;) {
1560 unsigned long newpow = powbase * (unsigned long)base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001561 if (newpow >> PyLong_SHIFT) /* doesn't fit in a digit */
Tim Petersfad225f2001-07-13 02:59:26 +00001562 break;
1563 powbase = (digit)newpow;
1564 ++power;
1565 }
Tim Peters212e6142001-07-14 12:23:19 +00001566
1567 /* Get a scratch area for repeated division. */
1568 scratch = _PyLong_New(size);
1569 if (scratch == NULL) {
1570 Py_DECREF(str);
1571 return NULL;
1572 }
1573
1574 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001575 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001576 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001577 digit rem = inplace_divrem1(scratch->ob_digit,
1578 pin, size, powbase);
1579 pin = scratch->ob_digit; /* no need to use a again */
1580 if (pin[size - 1] == 0)
1581 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001582 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001583 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001584 Py_DECREF(str);
1585 return NULL;
1586 })
Tim Peters212e6142001-07-14 12:23:19 +00001587
1588 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001589 assert(ntostore > 0);
1590 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001591 digit nextrem = (digit)(rem / base);
1592 char c = (char)(rem - nextrem * base);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001593 assert(p > PyUnicode_AS_UNICODE(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001594 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001595 *--p = c;
1596 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001597 --ntostore;
1598 /* Termination is a bit delicate: must not
1599 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001600 remaining quotient and rem are both 0. */
1601 } while (ntostore && (size || rem));
1602 } while (size != 0);
1603 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001604 }
1605
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001606 if (base == 16) {
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001607 *--p = 'x';
1608 *--p = '0';
1609 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001610 else if (base == 8) {
1611 *--p = 'o';
1612 *--p = '0';
1613 }
1614 else if (base == 2) {
1615 *--p = 'b';
1616 *--p = '0';
1617 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001618 else if (base != 10) {
1619 *--p = '#';
1620 *--p = '0' + base%10;
1621 if (base > 10)
1622 *--p = '0' + base/10;
1623 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001624 if (sign)
1625 *--p = sign;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001626 if (p != PyUnicode_AS_UNICODE(str)) {
1627 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001628 assert(p > q);
1629 do {
1630 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001631 q--;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001632 if (PyUnicode_Resize(&str, (Py_ssize_t) (q - PyUnicode_AS_UNICODE(str)))) {
1633 Py_DECREF(str);
1634 return NULL;
1635 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001636 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001637 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001638}
1639
Thomas Wouters477c8d52006-05-27 19:21:47 +00001640/* Table of digit values for 8-bit string -> integer conversion.
1641 * '0' maps to 0, ..., '9' maps to 9.
1642 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1643 * All other indices map to 37.
1644 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001645 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001646 */
1647int _PyLong_DigitValue[256] = {
1648 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1649 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1650 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1651 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1652 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1653 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1654 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1655 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1656 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1657 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1658 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 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};
1665
1666/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001667 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1668 * non-digit (which may be *str!). A normalized long is returned.
1669 * The point to this routine is that it takes time linear in the number of
1670 * string characters.
1671 */
1672static PyLongObject *
1673long_from_binary_base(char **str, int base)
1674{
1675 char *p = *str;
1676 char *start = p;
1677 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001678 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001679 PyLongObject *z;
1680 twodigits accum;
1681 int bits_in_accum;
1682 digit *pdigit;
1683
1684 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1685 n = base;
1686 for (bits_per_char = -1; n; ++bits_per_char)
1687 n >>= 1;
1688 /* n <- total # of bits needed, while setting p to end-of-string */
1689 n = 0;
Christian Heimesbbe741d2008-03-28 10:53:29 +00001690 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001691 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001692 *str = p;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001693 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1694 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001695 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001696 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001697 "int string too large to convert");
Tim Peters1a3b19a2003-02-02 17:33:53 +00001698 return NULL;
1699 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001700 n = n / PyLong_SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001701 z = _PyLong_New(n);
1702 if (z == NULL)
1703 return NULL;
1704 /* Read string from right, and fill in long from left; i.e.,
1705 * from least to most significant in both.
1706 */
1707 accum = 0;
1708 bits_in_accum = 0;
1709 pdigit = z->ob_digit;
1710 while (--p >= start) {
Christian Heimesbbe741d2008-03-28 10:53:29 +00001711 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001712 assert(k >= 0 && k < base);
1713 accum |= (twodigits)(k << bits_in_accum);
Tim Petersbf2674b2003-02-02 07:51:32 +00001714 bits_in_accum += bits_per_char;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001715 if (bits_in_accum >= PyLong_SHIFT) {
1716 *pdigit++ = (digit)(accum & PyLong_MASK);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001717 assert(pdigit - z->ob_digit <= (int)n);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001718 accum >>= PyLong_SHIFT;
1719 bits_in_accum -= PyLong_SHIFT;
1720 assert(bits_in_accum < PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001721 }
1722 }
1723 if (bits_in_accum) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001724 assert(bits_in_accum <= PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001725 *pdigit++ = (digit)accum;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001726 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001727 }
1728 while (pdigit - z->ob_digit < n)
1729 *pdigit++ = 0;
1730 return long_normalize(z);
1731}
1732
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001733PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001734PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001735{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001736 int sign = 1, error_if_nonzero = 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001737 char *start, *orig_str = str;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001738 PyLongObject *z = NULL;
Guido van Rossum25236212007-08-22 23:28:23 +00001739 PyObject *strobj;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001740 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001741
Guido van Rossum472c04f1996-12-05 21:57:21 +00001742 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001743 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001744 "int() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001745 return NULL;
1746 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001747 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001748 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001749 if (*str == '+')
1750 ++str;
1751 else if (*str == '-') {
1752 ++str;
1753 sign = -1;
1754 }
1755 if (base == 0) {
1756 if (str[0] != '0')
1757 base = 10;
1758 else if (str[1] == 'x' || str[1] == 'X')
1759 base = 16;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001760 else if (str[1] == 'o' || str[1] == 'O')
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001761 base = 8;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001762 else if (str[1] == 'b' || str[1] == 'B')
1763 base = 2;
1764 else {
1765 /* "old" (C-style) octal literal, now invalid.
1766 it might still be zero though */
1767 error_if_nonzero = 1;
1768 base = 10;
1769 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001770 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001771 if (str[0] == '0' &&
1772 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1773 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1774 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001775 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001776
Guido van Rossume6762971998-06-22 03:54:46 +00001777 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001778 if ((base & (base - 1)) == 0)
1779 z = long_from_binary_base(&str, base);
1780 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001781/***
1782Binary bases can be converted in time linear in the number of digits, because
1783Python's representation base is binary. Other bases (including decimal!) use
1784the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001785
Thomas Wouters477c8d52006-05-27 19:21:47 +00001786First some math: the largest integer that can be expressed in N base-B digits
1787is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1788case number of Python digits needed to hold it is the smallest integer n s.t.
1789
1790 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1791 BASE**n >= B**N [taking logs to base BASE]
1792 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1793
1794The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1795this quickly. A Python long with that much space is reserved near the start,
1796and the result is computed into it.
1797
1798The input string is actually treated as being in base base**i (i.e., i digits
1799are processed at a time), where two more static arrays hold:
1800
1801 convwidth_base[base] = the largest integer i such that base**i <= BASE
1802 convmultmax_base[base] = base ** convwidth_base[base]
1803
1804The first of these is the largest i such that i consecutive input digits
1805must fit in a single Python digit. The second is effectively the input
1806base we're really using.
1807
1808Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1809convmultmax_base[base], the result is "simply"
1810
1811 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1812
1813where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001814
1815Error analysis: as above, the number of Python digits `n` needed is worst-
1816case
1817
1818 n >= N * log(B)/log(BASE)
1819
1820where `N` is the number of input digits in base `B`. This is computed via
1821
1822 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1823
1824below. Two numeric concerns are how much space this can waste, and whether
1825the computed result can be too small. To be concrete, assume BASE = 2**15,
1826which is the default (and it's unlikely anyone changes that).
1827
1828Waste isn't a problem: provided the first input digit isn't 0, the difference
1829between the worst-case input with N digits and the smallest input with N
1830digits is about a factor of B, but B is small compared to BASE so at most
1831one allocated Python digit can remain unused on that count. If
1832N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1833and adding 1 returns a result 1 larger than necessary. However, that can't
1834happen: whenever B is a power of 2, long_from_binary_base() is called
1835instead, and it's impossible for B**i to be an integer power of 2**15 when
1836B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1837an exact integer when B is not a power of 2, since B**i has a prime factor
1838other than 2 in that case, but (2**15)**j's only prime factor is 2).
1839
1840The computed result can be too small if the true value of N*log(B)/log(BASE)
1841is a little bit larger than an exact integer, but due to roundoff errors (in
1842computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1843yields a numeric result a little less than that integer. Unfortunately, "how
1844close can a transcendental function get to an integer over some range?"
1845questions are generally theoretically intractable. Computer analysis via
1846continued fractions is practical: expand log(B)/log(BASE) via continued
1847fractions, giving a sequence i/j of "the best" rational approximations. Then
1848j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1849we can get very close to being in trouble, but very rarely. For example,
185076573 is a denominator in one of the continued-fraction approximations to
1851log(10)/log(2**15), and indeed:
1852
1853 >>> log(10)/log(2**15)*76573
1854 16958.000000654003
1855
1856is very close to an integer. If we were working with IEEE single-precision,
1857rounding errors could kill us. Finding worst cases in IEEE double-precision
1858requires better-than-double-precision log() functions, and Tim didn't bother.
1859Instead the code checks to see whether the allocated space is enough as each
1860new Python digit is added, and copies the whole thing to a larger long if not.
1861This should happen extremely rarely, and in fact I don't have a test case
1862that triggers it(!). Instead the code was tested by artificially allocating
1863just 1 digit at the start, so that the copying code was exercised for every
1864digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001865***/
1866 register twodigits c; /* current input character */
1867 Py_ssize_t size_z;
1868 int i;
1869 int convwidth;
1870 twodigits convmultmax, convmult;
1871 digit *pz, *pzstop;
1872 char* scan;
1873
1874 static double log_base_BASE[37] = {0.0e0,};
1875 static int convwidth_base[37] = {0,};
1876 static twodigits convmultmax_base[37] = {0,};
1877
1878 if (log_base_BASE[base] == 0.0) {
1879 twodigits convmax = base;
1880 int i = 1;
1881
1882 log_base_BASE[base] = log((double)base) /
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001883 log((double)PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001884 for (;;) {
1885 twodigits next = convmax * base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001886 if (next > PyLong_BASE)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001887 break;
1888 convmax = next;
1889 ++i;
1890 }
1891 convmultmax_base[base] = convmax;
1892 assert(i > 0);
1893 convwidth_base[base] = i;
1894 }
1895
1896 /* Find length of the string of numeric characters. */
1897 scan = str;
Christian Heimesbbe741d2008-03-28 10:53:29 +00001898 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001899 ++scan;
1900
1901 /* Create a long object that can contain the largest possible
1902 * integer with this base and length. Note that there's no
1903 * need to initialize z->ob_digit -- no slot is read up before
1904 * being stored into.
1905 */
1906 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001907 /* Uncomment next line to test exceedingly rare copy code */
1908 /* size_z = 1; */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001909 assert(size_z > 0);
1910 z = _PyLong_New(size_z);
1911 if (z == NULL)
1912 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00001913 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001914
1915 /* `convwidth` consecutive input digits are treated as a single
1916 * digit in base `convmultmax`.
1917 */
1918 convwidth = convwidth_base[base];
1919 convmultmax = convmultmax_base[base];
1920
1921 /* Work ;-) */
1922 while (str < scan) {
1923 /* grab up to convwidth digits from the input string */
Christian Heimesbbe741d2008-03-28 10:53:29 +00001924 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Thomas Wouters477c8d52006-05-27 19:21:47 +00001925 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1926 c = (twodigits)(c * base +
Christian Heimesbbe741d2008-03-28 10:53:29 +00001927 _PyLong_DigitValue[Py_CHARMASK(*str)]);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001928 assert(c < PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001929 }
1930
1931 convmult = convmultmax;
1932 /* Calculate the shift only if we couldn't get
1933 * convwidth digits.
1934 */
1935 if (i != convwidth) {
1936 convmult = base;
1937 for ( ; i > 1; --i)
1938 convmult *= base;
1939 }
1940
1941 /* Multiply z by convmult, and add c. */
1942 pz = z->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001943 pzstop = pz + Py_SIZE(z);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001944 for (; pz < pzstop; ++pz) {
1945 c += (twodigits)*pz * convmult;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001946 *pz = (digit)(c & PyLong_MASK);
1947 c >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001948 }
1949 /* carry off the current end? */
1950 if (c) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001951 assert(c < PyLong_BASE);
Christian Heimes90aa7642007-12-19 02:45:37 +00001952 if (Py_SIZE(z) < size_z) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001953 *pz = (digit)c;
Christian Heimes90aa7642007-12-19 02:45:37 +00001954 ++Py_SIZE(z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001955 }
1956 else {
1957 PyLongObject *tmp;
1958 /* Extremely rare. Get more space. */
Christian Heimes90aa7642007-12-19 02:45:37 +00001959 assert(Py_SIZE(z) == size_z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001960 tmp = _PyLong_New(size_z + 1);
1961 if (tmp == NULL) {
1962 Py_DECREF(z);
1963 return NULL;
1964 }
1965 memcpy(tmp->ob_digit,
1966 z->ob_digit,
1967 sizeof(digit) * size_z);
1968 Py_DECREF(z);
1969 z = tmp;
1970 z->ob_digit[size_z] = (digit)c;
1971 ++size_z;
1972 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001973 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001974 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001975 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001976 if (z == NULL)
1977 return NULL;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001978 if (error_if_nonzero) {
1979 /* reset the base to 0, else the exception message
1980 doesn't make too much sense */
1981 base = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +00001982 if (Py_SIZE(z) != 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001983 goto onError;
1984 /* there might still be other problems, therefore base
1985 remains zero here for the same reason */
1986 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00001987 if (str == start)
1988 goto onError;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001989 if (sign < 0)
Christian Heimes90aa7642007-12-19 02:45:37 +00001990 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00001991 if (*str == 'L' || *str == 'l')
1992 str++;
1993 while (*str && isspace(Py_CHARMASK(*str)))
1994 str++;
1995 if (*str != '\0')
1996 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001997 if (pend)
1998 *pend = str;
Martin v. Löwis029656f2008-06-30 04:06:08 +00001999 long_normalize(z);
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002000 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002001
2002 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00002003 Py_XDECREF(z);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002004 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
Guido van Rossum25236212007-08-22 23:28:23 +00002005 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002006 if (strobj == NULL)
2007 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002008 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00002009 "invalid literal for int() with base %d: %R",
2010 base, strobj);
2011 Py_DECREF(strobj);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002012 return NULL;
2013}
2014
2015PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002016PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002017{
Walter Dörwald07e14762002-11-06 16:15:14 +00002018 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002019 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002020
Walter Dörwald07e14762002-11-06 16:15:14 +00002021 if (buffer == NULL)
2022 return NULL;
2023
2024 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
2025 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002026 return NULL;
2027 }
Walter Dörwald07e14762002-11-06 16:15:14 +00002028 result = PyLong_FromString(buffer, NULL, base);
2029 PyMem_FREE(buffer);
2030 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002031}
2032
Tim Peters9f688bf2000-07-07 15:53:28 +00002033/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002034static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00002035 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002036static PyObject *long_long(PyObject *v);
Tim Peters9f688bf2000-07-07 15:53:28 +00002037static int long_divrem(PyLongObject *, PyLongObject *,
2038 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002039
2040/* Long division with remainder, top-level routine */
2041
Guido van Rossume32e0141992-01-19 16:31:05 +00002042static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002043long_divrem(PyLongObject *a, PyLongObject *b,
2044 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002045{
Christian Heimes90aa7642007-12-19 02:45:37 +00002046 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002047 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002048
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002049 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002050 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002051 "integer division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00002052 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002053 }
2054 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00002055 (size_a == size_b &&
2056 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002057 /* |a| < |b|. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00002058 *pdiv = (PyLongObject*)PyLong_FromLong(0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002059 if (*pdiv == NULL)
2060 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002061 Py_INCREF(a);
2062 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00002063 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002064 }
2065 if (size_b == 1) {
2066 digit rem = 0;
2067 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002068 if (z == NULL)
2069 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002070 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002071 if (*prem == NULL) {
2072 Py_DECREF(z);
2073 return -1;
2074 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002075 }
Guido van Rossume32e0141992-01-19 16:31:05 +00002076 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002077 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002078 if (z == NULL)
2079 return -1;
2080 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002081 /* Set the signs.
2082 The quotient z has the sign of a*b;
2083 the remainder r has the sign of a,
2084 so a = b*z + r. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002085 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
Guido van Rossumddefaf32007-01-14 03:31:43 +00002086 NEGATE(z);
Christian Heimes90aa7642007-12-19 02:45:37 +00002087 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002088 NEGATE(*prem);
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002089 *pdiv = maybe_small_long(z);
Guido van Rossume32e0141992-01-19 16:31:05 +00002090 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002091}
2092
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002093/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002094
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002095static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002096x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002097{
Christian Heimes90aa7642007-12-19 02:45:37 +00002098 Py_ssize_t size_v = ABS(Py_SIZE(v1)), size_w = ABS(Py_SIZE(w1));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002099 digit d = (digit) ((twodigits)PyLong_BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002100 PyLongObject *v = mul1(v1, d);
2101 PyLongObject *w = mul1(w1, d);
2102 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002103 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002104
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002105 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002106 Py_XDECREF(v);
2107 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002108 return NULL;
2109 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002110
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002111 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Christian Heimes90aa7642007-12-19 02:45:37 +00002112 assert(Py_REFCNT(v) == 1); /* Since v will be used as accumulator! */
2113 assert(size_w == ABS(Py_SIZE(w))); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002114
Christian Heimes90aa7642007-12-19 02:45:37 +00002115 size_v = ABS(Py_SIZE(v));
Thomas Wouters477c8d52006-05-27 19:21:47 +00002116 k = size_v - size_w;
2117 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002118
Thomas Wouters477c8d52006-05-27 19:21:47 +00002119 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002120 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
2121 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002122 stwodigits carry = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002123 int i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002124
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002125 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002126 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002127 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002128 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002129 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002130 if (vj == w->ob_digit[size_w-1])
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002131 q = PyLong_MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002132 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002133 q = (((twodigits)vj << PyLong_SHIFT) + v->ob_digit[j-1]) /
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002134 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00002135
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002136 while (w->ob_digit[size_w-2]*q >
2137 ((
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002138 ((twodigits)vj << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002139 + v->ob_digit[j-1]
2140 - q*w->ob_digit[size_w-1]
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002141 ) << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002142 + v->ob_digit[j-2])
2143 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002144
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002145 for (i = 0; i < size_w && i+k < size_v; ++i) {
2146 twodigits z = w->ob_digit[i] * q;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002147 digit zz = (digit) (z >> PyLong_SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002148 carry += v->ob_digit[i+k] - z
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002149 + ((twodigits)zz << PyLong_SHIFT);
2150 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002151 carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002152 carry, PyLong_SHIFT);
Tim Peters7d3a5112000-07-08 04:17:21 +00002153 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002154 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002155
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002156 if (i+k < size_v) {
2157 carry += v->ob_digit[i+k];
2158 v->ob_digit[i+k] = 0;
2159 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002160
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002161 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00002162 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002163 else {
2164 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00002165 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002166 carry = 0;
2167 for (i = 0; i < size_w && i+k < size_v; ++i) {
2168 carry += v->ob_digit[i+k] + w->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002169 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002170 carry = Py_ARITHMETIC_RIGHT_SHIFT(
2171 BASE_TWODIGITS_TYPE,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002172 carry, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002173 }
2174 }
2175 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002176
Guido van Rossumc206c761995-01-10 15:23:19 +00002177 if (a == NULL)
2178 *prem = NULL;
2179 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00002180 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002181 *prem = divrem1(v, d, &d);
2182 /* d receives the (unused) remainder */
2183 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002184 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002185 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002186 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002187 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002188 Py_DECREF(v);
2189 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002190 return a;
2191}
2192
2193/* Methods */
2194
2195static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002196long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002197{
Christian Heimes90aa7642007-12-19 02:45:37 +00002198 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002199}
2200
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002201static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002202long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002203{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002204 return _PyLong_Format(v, 10);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002205}
2206
2207static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002208long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002209{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002210 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002211
Christian Heimes90aa7642007-12-19 02:45:37 +00002212 if (Py_SIZE(a) != Py_SIZE(b)) {
2213 if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002214 sign = 0;
2215 else
Christian Heimes90aa7642007-12-19 02:45:37 +00002216 sign = Py_SIZE(a) - Py_SIZE(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002217 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002218 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002219 Py_ssize_t i = ABS(Py_SIZE(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002220 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2221 ;
2222 if (i < 0)
2223 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002224 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002225 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Christian Heimes90aa7642007-12-19 02:45:37 +00002226 if (Py_SIZE(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002227 sign = -sign;
2228 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002229 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002230 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002231}
2232
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002233static PyObject *
2234long_richcompare(PyObject *self, PyObject *other, int op)
2235{
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002236 PyObject *result;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002237 CHECK_BINOP(self, other);
2238 result = Py_CmpToRich(op, long_compare((PyLongObject*)self,
2239 (PyLongObject*)other));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002240 return result;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002241}
2242
Guido van Rossum9bfef441993-03-29 10:43:31 +00002243static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002244long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002245{
2246 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002247 Py_ssize_t i;
2248 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002249
2250 /* This is designed so that Python ints and longs with the
2251 same value hash to the same value, otherwise comparisons
2252 of mapping keys will turn out weird */
Christian Heimes90aa7642007-12-19 02:45:37 +00002253 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +00002254 switch(i) {
2255 case -1: return v->ob_digit[0]==1 ? -2 : -v->ob_digit[0];
2256 case 0: return 0;
2257 case 1: return v->ob_digit[0];
2258 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002259 sign = 1;
2260 x = 0;
2261 if (i < 0) {
2262 sign = -1;
2263 i = -(i);
2264 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002265#define LONG_BIT_PyLong_SHIFT (8*sizeof(long) - PyLong_SHIFT)
Thomas Woutersce272b62007-09-19 21:19:28 +00002266 /* The following loop produces a C long x such that (unsigned long)x
2267 is congruent to the absolute value of v modulo ULONG_MAX. The
2268 resulting x is nonzero if and only if v is. */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002269 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002270 /* Force a native long #-bits (32 or 64) circular shift */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002271 x = ((x << PyLong_SHIFT) & ~PyLong_MASK) | ((x >> LONG_BIT_PyLong_SHIFT) & PyLong_MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002272 x += v->ob_digit[i];
Thomas Woutersce272b62007-09-19 21:19:28 +00002273 /* If the addition above overflowed (thinking of x as
2274 unsigned), we compensate by incrementing. This preserves
2275 the value modulo ULONG_MAX. */
2276 if ((unsigned long)x < v->ob_digit[i])
2277 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002278 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002279#undef LONG_BIT_PyLong_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00002280 x = x * sign;
2281 if (x == -1)
2282 x = -2;
2283 return x;
2284}
2285
2286
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002287/* Add the absolute values of two long integers. */
2288
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002289static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002290x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002291{
Christian Heimes90aa7642007-12-19 02:45:37 +00002292 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002293 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002294 int i;
2295 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002296
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002297 /* Ensure a is the larger of the two: */
2298 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002299 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002300 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002301 size_a = size_b;
2302 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002303 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002304 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002305 if (z == NULL)
2306 return NULL;
2307 for (i = 0; i < size_b; ++i) {
2308 carry += a->ob_digit[i] + b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002309 z->ob_digit[i] = carry & PyLong_MASK;
2310 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002311 }
2312 for (; i < size_a; ++i) {
2313 carry += a->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002314 z->ob_digit[i] = carry & PyLong_MASK;
2315 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002316 }
2317 z->ob_digit[i] = carry;
2318 return long_normalize(z);
2319}
2320
2321/* Subtract the absolute values of two integers. */
2322
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002323static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002324x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002325{
Christian Heimes90aa7642007-12-19 02:45:37 +00002326 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002327 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002328 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002329 int sign = 1;
2330 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002331
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002332 /* Ensure a is the larger of the two: */
2333 if (size_a < size_b) {
2334 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002335 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002336 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002337 size_a = size_b;
2338 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002339 }
2340 else if (size_a == size_b) {
2341 /* Find highest digit where a and b differ: */
2342 i = size_a;
2343 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2344 ;
2345 if (i < 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002346 return (PyLongObject *)PyLong_FromLong(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002347 if (a->ob_digit[i] < b->ob_digit[i]) {
2348 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002349 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002350 }
2351 size_a = size_b = i+1;
2352 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002353 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002354 if (z == NULL)
2355 return NULL;
2356 for (i = 0; i < size_b; ++i) {
2357 /* The following assumes unsigned arithmetic
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002358 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002359 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002360 z->ob_digit[i] = borrow & PyLong_MASK;
2361 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002362 borrow &= 1; /* Keep only one sign bit */
2363 }
2364 for (; i < size_a; ++i) {
2365 borrow = a->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002366 z->ob_digit[i] = borrow & PyLong_MASK;
2367 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002368 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002369 }
2370 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002371 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002372 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002373 return long_normalize(z);
2374}
2375
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002376static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002377long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002378{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002379 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002380
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002381 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002382
Christian Heimes90aa7642007-12-19 02:45:37 +00002383 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Christian Heimes217cfd12007-12-02 14:31:20 +00002384 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002385 MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002386 return result;
2387 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002388 if (Py_SIZE(a) < 0) {
2389 if (Py_SIZE(b) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002390 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002391 if (z != NULL && Py_SIZE(z) != 0)
2392 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002393 }
2394 else
2395 z = x_sub(b, a);
2396 }
2397 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002398 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002399 z = x_sub(a, b);
2400 else
2401 z = x_add(a, b);
2402 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002403 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002404}
2405
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002406static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002407long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002408{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002409 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002410
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002411 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002412
Christian Heimes90aa7642007-12-19 02:45:37 +00002413 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002414 PyObject* r;
2415 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002416 return r;
2417 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002418 if (Py_SIZE(a) < 0) {
2419 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002420 z = x_sub(a, b);
2421 else
2422 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002423 if (z != NULL && Py_SIZE(z) != 0)
2424 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002425 }
2426 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002427 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002428 z = x_add(a, b);
2429 else
2430 z = x_sub(a, b);
2431 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002432 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002433}
2434
Tim Peters5af4e6c2002-08-12 02:31:19 +00002435/* Grade school multiplication, ignoring the signs.
2436 * Returns the absolute value of the product, or NULL if error.
2437 */
2438static PyLongObject *
2439x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002440{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002441 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00002442 Py_ssize_t size_a = ABS(Py_SIZE(a));
2443 Py_ssize_t size_b = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002444 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002445
Tim Peters5af4e6c2002-08-12 02:31:19 +00002446 z = _PyLong_New(size_a + size_b);
2447 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002448 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002449
Christian Heimes90aa7642007-12-19 02:45:37 +00002450 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002451 if (a == b) {
2452 /* Efficient squaring per HAC, Algorithm 14.16:
2453 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2454 * Gives slightly less than a 2x speedup when a == b,
2455 * via exploiting that each entry in the multiplication
2456 * pyramid appears twice (except for the size_a squares).
2457 */
2458 for (i = 0; i < size_a; ++i) {
2459 twodigits carry;
2460 twodigits f = a->ob_digit[i];
2461 digit *pz = z->ob_digit + (i << 1);
2462 digit *pa = a->ob_digit + i + 1;
2463 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002464
Tim Peters0973b992004-08-29 22:16:50 +00002465 SIGCHECK({
2466 Py_DECREF(z);
2467 return NULL;
2468 })
2469
2470 carry = *pz + f * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002471 *pz++ = (digit)(carry & PyLong_MASK);
2472 carry >>= PyLong_SHIFT;
2473 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002474
2475 /* Now f is added in twice in each column of the
2476 * pyramid it appears. Same as adding f<<1 once.
2477 */
2478 f <<= 1;
2479 while (pa < paend) {
2480 carry += *pz + *pa++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002481 *pz++ = (digit)(carry & PyLong_MASK);
2482 carry >>= PyLong_SHIFT;
2483 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002484 }
2485 if (carry) {
2486 carry += *pz;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002487 *pz++ = (digit)(carry & PyLong_MASK);
2488 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002489 }
2490 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002491 *pz += (digit)(carry & PyLong_MASK);
2492 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002493 }
Tim Peters0973b992004-08-29 22:16:50 +00002494 }
2495 else { /* a is not the same as b -- gradeschool long mult */
2496 for (i = 0; i < size_a; ++i) {
2497 twodigits carry = 0;
2498 twodigits f = a->ob_digit[i];
2499 digit *pz = z->ob_digit + i;
2500 digit *pb = b->ob_digit;
2501 digit *pbend = b->ob_digit + size_b;
2502
2503 SIGCHECK({
2504 Py_DECREF(z);
2505 return NULL;
2506 })
2507
2508 while (pb < pbend) {
2509 carry += *pz + *pb++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002510 *pz++ = (digit)(carry & PyLong_MASK);
2511 carry >>= PyLong_SHIFT;
2512 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002513 }
2514 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002515 *pz += (digit)(carry & PyLong_MASK);
2516 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002517 }
2518 }
Tim Peters44121a62002-08-12 06:17:58 +00002519 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002520}
2521
2522/* A helper for Karatsuba multiplication (k_mul).
2523 Takes a long "n" and an integer "size" representing the place to
2524 split, and sets low and high such that abs(n) == (high << size) + low,
2525 viewing the shift as being by digits. The sign bit is ignored, and
2526 the return values are >= 0.
2527 Returns 0 on success, -1 on failure.
2528*/
2529static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002530kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002531{
2532 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002533 Py_ssize_t size_lo, size_hi;
Christian Heimes90aa7642007-12-19 02:45:37 +00002534 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002535
2536 size_lo = MIN(size_n, size);
2537 size_hi = size_n - size_lo;
2538
2539 if ((hi = _PyLong_New(size_hi)) == NULL)
2540 return -1;
2541 if ((lo = _PyLong_New(size_lo)) == NULL) {
2542 Py_DECREF(hi);
2543 return -1;
2544 }
2545
2546 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2547 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2548
2549 *high = long_normalize(hi);
2550 *low = long_normalize(lo);
2551 return 0;
2552}
2553
Tim Peters60004642002-08-12 22:01:34 +00002554static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2555
Tim Peters5af4e6c2002-08-12 02:31:19 +00002556/* Karatsuba multiplication. Ignores the input signs, and returns the
2557 * absolute value of the product (or NULL if error).
2558 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2559 */
2560static PyLongObject *
2561k_mul(PyLongObject *a, PyLongObject *b)
2562{
Christian Heimes90aa7642007-12-19 02:45:37 +00002563 Py_ssize_t asize = ABS(Py_SIZE(a));
2564 Py_ssize_t bsize = ABS(Py_SIZE(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002565 PyLongObject *ah = NULL;
2566 PyLongObject *al = NULL;
2567 PyLongObject *bh = NULL;
2568 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002569 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002570 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002571 Py_ssize_t shift; /* the number of digits we split off */
2572 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002573
Tim Peters5af4e6c2002-08-12 02:31:19 +00002574 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2575 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2576 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002577 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002578 * By picking X to be a power of 2, "*X" is just shifting, and it's
2579 * been reduced to 3 multiplies on numbers half the size.
2580 */
2581
Tim Petersfc07e562002-08-12 02:54:10 +00002582 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002583 * is largest.
2584 */
Tim Peters738eda72002-08-12 15:08:20 +00002585 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002586 t1 = a;
2587 a = b;
2588 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002589
2590 i = asize;
2591 asize = bsize;
2592 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002593 }
2594
2595 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002596 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2597 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002598 if (asize == 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002599 return (PyLongObject *)PyLong_FromLong(0);
Tim Peters44121a62002-08-12 06:17:58 +00002600 else
2601 return x_mul(a, b);
2602 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002603
Tim Peters60004642002-08-12 22:01:34 +00002604 /* If a is small compared to b, splitting on b gives a degenerate
2605 * case with ah==0, and Karatsuba may be (even much) less efficient
2606 * than "grade school" then. However, we can still win, by viewing
2607 * b as a string of "big digits", each of width a->ob_size. That
2608 * leads to a sequence of balanced calls to k_mul.
2609 */
2610 if (2 * asize <= bsize)
2611 return k_lopsided_mul(a, b);
2612
Tim Petersd6974a52002-08-13 20:37:51 +00002613 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002614 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002615 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002616 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002617
Tim Peters0973b992004-08-29 22:16:50 +00002618 if (a == b) {
2619 bh = ah;
2620 bl = al;
2621 Py_INCREF(bh);
2622 Py_INCREF(bl);
2623 }
2624 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002625
Tim Petersd64c1de2002-08-12 17:36:03 +00002626 /* The plan:
2627 * 1. Allocate result space (asize + bsize digits: that's always
2628 * enough).
2629 * 2. Compute ah*bh, and copy into result at 2*shift.
2630 * 3. Compute al*bl, and copy into result at 0. Note that this
2631 * can't overlap with #2.
2632 * 4. Subtract al*bl from the result, starting at shift. This may
2633 * underflow (borrow out of the high digit), but we don't care:
2634 * we're effectively doing unsigned arithmetic mod
2635 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2636 * borrows and carries out of the high digit can be ignored.
2637 * 5. Subtract ah*bh from the result, starting at shift.
2638 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2639 * at shift.
2640 */
2641
2642 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002643 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002644 if (ret == NULL) goto fail;
2645#ifdef Py_DEBUG
2646 /* Fill with trash, to catch reference to uninitialized digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002647 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002648#endif
Tim Peters44121a62002-08-12 06:17:58 +00002649
Tim Petersd64c1de2002-08-12 17:36:03 +00002650 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002651 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002652 assert(Py_SIZE(t1) >= 0);
2653 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002654 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Christian Heimes90aa7642007-12-19 02:45:37 +00002655 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002656
2657 /* Zero-out the digits higher than the ah*bh copy. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002658 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002659 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002660 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002661 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002662
Tim Petersd64c1de2002-08-12 17:36:03 +00002663 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002664 if ((t2 = k_mul(al, bl)) == NULL) {
2665 Py_DECREF(t1);
2666 goto fail;
2667 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002668 assert(Py_SIZE(t2) >= 0);
2669 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2670 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002671
2672 /* Zero out remaining digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002673 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002674 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002675 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002676
Tim Petersd64c1de2002-08-12 17:36:03 +00002677 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2678 * because it's fresher in cache.
2679 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002680 i = Py_SIZE(ret) - shift; /* # digits after shift */
2681 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002682 Py_DECREF(t2);
2683
Christian Heimes90aa7642007-12-19 02:45:37 +00002684 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002685 Py_DECREF(t1);
2686
Tim Petersd64c1de2002-08-12 17:36:03 +00002687 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002688 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2689 Py_DECREF(ah);
2690 Py_DECREF(al);
2691 ah = al = NULL;
2692
Tim Peters0973b992004-08-29 22:16:50 +00002693 if (a == b) {
2694 t2 = t1;
2695 Py_INCREF(t2);
2696 }
2697 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002698 Py_DECREF(t1);
2699 goto fail;
2700 }
2701 Py_DECREF(bh);
2702 Py_DECREF(bl);
2703 bh = bl = NULL;
2704
Tim Peters738eda72002-08-12 15:08:20 +00002705 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002706 Py_DECREF(t1);
2707 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002708 if (t3 == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002709 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002710
Tim Petersd6974a52002-08-13 20:37:51 +00002711 /* Add t3. It's not obvious why we can't run out of room here.
2712 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002713 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002714 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002715 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002716
Tim Peters5af4e6c2002-08-12 02:31:19 +00002717 return long_normalize(ret);
2718
2719 fail:
2720 Py_XDECREF(ret);
2721 Py_XDECREF(ah);
2722 Py_XDECREF(al);
2723 Py_XDECREF(bh);
2724 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002725 return NULL;
2726}
2727
Tim Petersd6974a52002-08-13 20:37:51 +00002728/* (*) Why adding t3 can't "run out of room" above.
2729
Tim Petersab86c2b2002-08-15 20:06:00 +00002730Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2731to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002732
Tim Petersab86c2b2002-08-15 20:06:00 +000027331. For any integer i, i = c(i/2) + f(i/2). In particular,
2734 bsize = c(bsize/2) + f(bsize/2).
27352. shift = f(bsize/2)
27363. asize <= bsize
27374. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2738 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002739
Tim Petersab86c2b2002-08-15 20:06:00 +00002740We allocated asize + bsize result digits, and add t3 into them at an offset
2741of shift. This leaves asize+bsize-shift allocated digit positions for t3
2742to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2743asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002744
Tim Petersab86c2b2002-08-15 20:06:00 +00002745bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2746at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002747
Tim Petersab86c2b2002-08-15 20:06:00 +00002748If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2749digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2750most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002751
Tim Petersab86c2b2002-08-15 20:06:00 +00002752The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002753
Tim Petersab86c2b2002-08-15 20:06:00 +00002754 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002755
Tim Petersab86c2b2002-08-15 20:06:00 +00002756and we have asize + c(bsize/2) available digit positions. We need to show
2757this is always enough. An instance of c(bsize/2) cancels out in both, so
2758the question reduces to whether asize digits is enough to hold
2759(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2760then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2761asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002762digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002763asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002764c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2765is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2766bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002767
Tim Peters48d52c02002-08-14 17:07:32 +00002768Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2769clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2770ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002771*/
2772
Tim Peters60004642002-08-12 22:01:34 +00002773/* b has at least twice the digits of a, and a is big enough that Karatsuba
2774 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2775 * of slices, each with a->ob_size digits, and multiply the slices by a,
2776 * one at a time. This gives k_mul balanced inputs to work with, and is
2777 * also cache-friendly (we compute one double-width slice of the result
2778 * at a time, then move on, never bactracking except for the helpful
2779 * single-width slice overlap between successive partial sums).
2780 */
2781static PyLongObject *
2782k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2783{
Christian Heimes90aa7642007-12-19 02:45:37 +00002784 const Py_ssize_t asize = ABS(Py_SIZE(a));
2785 Py_ssize_t bsize = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002786 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002787 PyLongObject *ret;
2788 PyLongObject *bslice = NULL;
2789
2790 assert(asize > KARATSUBA_CUTOFF);
2791 assert(2 * asize <= bsize);
2792
2793 /* Allocate result space, and zero it out. */
2794 ret = _PyLong_New(asize + bsize);
2795 if (ret == NULL)
2796 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00002797 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002798
2799 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002800 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002801 if (bslice == NULL)
2802 goto fail;
2803
2804 nbdone = 0;
2805 while (bsize > 0) {
2806 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002807 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002808
2809 /* Multiply the next slice of b by a. */
2810 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2811 nbtouse * sizeof(digit));
Christian Heimes90aa7642007-12-19 02:45:37 +00002812 Py_SIZE(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00002813 product = k_mul(a, bslice);
2814 if (product == NULL)
2815 goto fail;
2816
2817 /* Add into result. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002818 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
2819 product->ob_digit, Py_SIZE(product));
Tim Peters60004642002-08-12 22:01:34 +00002820 Py_DECREF(product);
2821
2822 bsize -= nbtouse;
2823 nbdone += nbtouse;
2824 }
2825
2826 Py_DECREF(bslice);
2827 return long_normalize(ret);
2828
2829 fail:
2830 Py_DECREF(ret);
2831 Py_XDECREF(bslice);
2832 return NULL;
2833}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002834
2835static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002836long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002837{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002838 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002839
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002840 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002841
Christian Heimes90aa7642007-12-19 02:45:37 +00002842 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002843 PyObject *r;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002844 r = PyLong_FromLong(MEDIUM_VALUE(a)*MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002845 return r;
2846 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00002847
Tim Petersd64c1de2002-08-12 17:36:03 +00002848 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002849 /* Negate if exactly one of the inputs is negative. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002850 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002851 NEGATE(z);
Tim Peters9973d742002-08-15 19:41:06 +00002852 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002853}
2854
Guido van Rossume32e0141992-01-19 16:31:05 +00002855/* The / and % operators are now defined in terms of divmod().
2856 The expression a mod b has the value a - b*floor(a/b).
2857 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002858 |a| by |b|, with the sign of a. This is also expressed
2859 as a - b*trunc(a/b), if trunc truncates towards zero.
2860 Some examples:
2861 a b a rem b a mod b
2862 13 10 3 3
2863 -13 10 -3 7
2864 13 -10 3 -7
2865 -13 -10 -3 -3
2866 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002867 have different signs. We then subtract one from the 'div'
2868 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002869
Tim Peters47e52ee2004-08-30 02:44:38 +00002870/* Compute
2871 * *pdiv, *pmod = divmod(v, w)
2872 * NULL can be passed for pdiv or pmod, in which case that part of
2873 * the result is simply thrown away. The caller owns a reference to
2874 * each of these it requests (does not pass NULL for).
2875 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002876static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002877l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002878 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002879{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002880 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002881
Guido van Rossume32e0141992-01-19 16:31:05 +00002882 if (long_divrem(v, w, &div, &mod) < 0)
2883 return -1;
Christian Heimes90aa7642007-12-19 02:45:37 +00002884 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
2885 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002886 PyLongObject *temp;
2887 PyLongObject *one;
2888 temp = (PyLongObject *) long_add(mod, w);
2889 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002890 mod = temp;
2891 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002892 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002893 return -1;
2894 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002895 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002896 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002897 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2898 Py_DECREF(mod);
2899 Py_DECREF(div);
2900 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002901 return -1;
2902 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002903 Py_DECREF(one);
2904 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002905 div = temp;
2906 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002907 if (pdiv != NULL)
2908 *pdiv = div;
2909 else
2910 Py_DECREF(div);
2911
2912 if (pmod != NULL)
2913 *pmod = mod;
2914 else
2915 Py_DECREF(mod);
2916
Guido van Rossume32e0141992-01-19 16:31:05 +00002917 return 0;
2918}
2919
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002920static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002921long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00002922{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002923 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002924
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002925 CHECK_BINOP(a, b);
2926 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00002927 div = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002928 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002929}
2930
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002931static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002932long_true_divide(PyObject *a, PyObject *b)
Tim Peters20dab9f2001-09-04 05:31:47 +00002933{
Tim Peterse2a60002001-09-04 06:17:36 +00002934 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002935 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002936
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002937 CHECK_BINOP(a, b);
Tim Peterse2a60002001-09-04 06:17:36 +00002938 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2939 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002940 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
Tim Peters6f97e492001-11-04 23:09:40 +00002941 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002942 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002943 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2944 but should really be set correctly after sucessful calls to
2945 _PyLong_AsScaledDouble() */
2946 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002947
2948 if (bd == 0.0) {
2949 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002950 "int division or modulo by zero");
Tim Peterse2a60002001-09-04 06:17:36 +00002951 return NULL;
2952 }
2953
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002954 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
Tim Peterse2a60002001-09-04 06:17:36 +00002955 ad /= bd; /* overflow/underflow impossible here */
2956 aexp -= bexp;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002957 if (aexp > INT_MAX / PyLong_SHIFT)
Tim Peterse2a60002001-09-04 06:17:36 +00002958 goto overflow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002959 else if (aexp < -(INT_MAX / PyLong_SHIFT))
Tim Peterse56ed9b2001-09-06 21:59:14 +00002960 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002961 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002962 ad = ldexp(ad, aexp * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002963 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002964 goto overflow;
2965 return PyFloat_FromDouble(ad);
2966
2967overflow:
2968 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002969 "int/int too large for a float");
Tim Peterse2a60002001-09-04 06:17:36 +00002970 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002971
Tim Peters20dab9f2001-09-04 05:31:47 +00002972}
2973
2974static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002975long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00002976{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002977 PyLongObject *mod;
2978
2979 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002980
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002981 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00002982 mod = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002983 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002984}
2985
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002986static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002987long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002988{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002989 PyLongObject *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002990 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002991
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002992 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002993
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002994 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002995 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002996 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002997 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002998 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002999 PyTuple_SetItem(z, 0, (PyObject *) div);
3000 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003001 }
3002 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003003 Py_DECREF(div);
3004 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003005 }
3006 return z;
3007}
3008
Tim Peters47e52ee2004-08-30 02:44:38 +00003009/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003010static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003011long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003012{
Tim Peters47e52ee2004-08-30 02:44:38 +00003013 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3014 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003015
Tim Peters47e52ee2004-08-30 02:44:38 +00003016 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00003017 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00003018 PyLongObject *temp = NULL;
3019
3020 /* 5-ary values. If the exponent is large enough, table is
3021 * precomputed so that table[i] == a**i % c for i in range(32).
3022 */
3023 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3024 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
3025
3026 /* a, b, c = v, w, x */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003027 CHECK_BINOP(v, w);
3028 a = (PyLongObject*)v; Py_INCREF(a);
3029 b = (PyLongObject*)w; Py_INCREF(b);
Tim Peters47e52ee2004-08-30 02:44:38 +00003030 if (PyLong_Check(x)) {
3031 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003032 Py_INCREF(x);
3033 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003034 else if (x == Py_None)
3035 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003036 else {
3037 Py_DECREF(a);
3038 Py_DECREF(b);
3039 Py_INCREF(Py_NotImplemented);
3040 return Py_NotImplemented;
3041 }
Tim Peters4c483c42001-09-05 06:24:58 +00003042
Christian Heimes90aa7642007-12-19 02:45:37 +00003043 if (Py_SIZE(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00003044 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00003045 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00003046 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00003047 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00003048 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003049 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00003050 /* else return a float. This works because we know
3051 that this calls float_pow() which converts its
3052 arguments to double. */
3053 Py_DECREF(a);
3054 Py_DECREF(b);
3055 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003056 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003057 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003058
3059 if (c) {
3060 /* if modulus == 0:
3061 raise ValueError() */
Christian Heimes90aa7642007-12-19 02:45:37 +00003062 if (Py_SIZE(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003063 PyErr_SetString(PyExc_ValueError,
3064 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003065 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003066 }
3067
3068 /* if modulus < 0:
3069 negativeOutput = True
3070 modulus = -modulus */
Christian Heimes90aa7642007-12-19 02:45:37 +00003071 if (Py_SIZE(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003072 negativeOutput = 1;
3073 temp = (PyLongObject *)_PyLong_Copy(c);
3074 if (temp == NULL)
3075 goto Error;
3076 Py_DECREF(c);
3077 c = temp;
3078 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003079 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003080 }
3081
3082 /* if modulus == 1:
3083 return 0 */
Christian Heimes90aa7642007-12-19 02:45:37 +00003084 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003085 z = (PyLongObject *)PyLong_FromLong(0L);
3086 goto Done;
3087 }
3088
3089 /* if base < 0:
3090 base = base % modulus
3091 Having the base positive just makes things easier. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003092 if (Py_SIZE(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003093 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003094 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003095 Py_DECREF(a);
3096 a = temp;
3097 temp = NULL;
3098 }
3099 }
3100
3101 /* At this point a, b, and c are guaranteed non-negative UNLESS
3102 c is NULL, in which case a may be negative. */
3103
3104 z = (PyLongObject *)PyLong_FromLong(1L);
3105 if (z == NULL)
3106 goto Error;
3107
3108 /* Perform a modular reduction, X = X % c, but leave X alone if c
3109 * is NULL.
3110 */
3111#define REDUCE(X) \
3112 if (c != NULL) { \
3113 if (l_divmod(X, c, NULL, &temp) < 0) \
3114 goto Error; \
3115 Py_XDECREF(X); \
3116 X = temp; \
3117 temp = NULL; \
3118 }
3119
3120 /* Multiply two values, then reduce the result:
3121 result = X*Y % c. If c is NULL, skip the mod. */
3122#define MULT(X, Y, result) \
3123{ \
3124 temp = (PyLongObject *)long_mul(X, Y); \
3125 if (temp == NULL) \
3126 goto Error; \
3127 Py_XDECREF(result); \
3128 result = temp; \
3129 temp = NULL; \
3130 REDUCE(result) \
3131}
3132
Christian Heimes90aa7642007-12-19 02:45:37 +00003133 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003134 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3135 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Christian Heimes90aa7642007-12-19 02:45:37 +00003136 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003137 digit bi = b->ob_digit[i];
3138
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003139 for (j = 1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003140 MULT(z, z, z)
3141 if (bi & j)
3142 MULT(z, a, z)
3143 }
3144 }
3145 }
3146 else {
3147 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3148 Py_INCREF(z); /* still holds 1L */
3149 table[0] = z;
3150 for (i = 1; i < 32; ++i)
3151 MULT(table[i-1], a, table[i])
3152
Christian Heimes90aa7642007-12-19 02:45:37 +00003153 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003154 const digit bi = b->ob_digit[i];
3155
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003156 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003157 const int index = (bi >> j) & 0x1f;
3158 for (k = 0; k < 5; ++k)
3159 MULT(z, z, z)
3160 if (index)
3161 MULT(z, table[index], z)
3162 }
3163 }
3164 }
3165
Christian Heimes90aa7642007-12-19 02:45:37 +00003166 if (negativeOutput && (Py_SIZE(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003167 temp = (PyLongObject *)long_sub(z, c);
3168 if (temp == NULL)
3169 goto Error;
3170 Py_DECREF(z);
3171 z = temp;
3172 temp = NULL;
3173 }
3174 goto Done;
3175
3176 Error:
3177 if (z != NULL) {
3178 Py_DECREF(z);
3179 z = NULL;
3180 }
3181 /* fall through */
3182 Done:
Christian Heimes90aa7642007-12-19 02:45:37 +00003183 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003184 for (i = 0; i < 32; ++i)
3185 Py_XDECREF(table[i]);
3186 }
Tim Petersde7990b2005-07-17 23:45:23 +00003187 Py_DECREF(a);
3188 Py_DECREF(b);
3189 Py_XDECREF(c);
3190 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003191 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003192}
3193
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003194static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003195long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003196{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003197 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003198 PyLongObject *x;
3199 PyLongObject *w;
Christian Heimes90aa7642007-12-19 02:45:37 +00003200 if (ABS(Py_SIZE(v)) <=1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003201 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003202 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003203 if (w == NULL)
3204 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003205 x = (PyLongObject *) long_add(v, w);
3206 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003207 if (x == NULL)
3208 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00003209 Py_SIZE(x) = -(Py_SIZE(x));
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003210 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003211}
3212
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003213static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003214long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003215{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003216 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00003217 if (ABS(Py_SIZE(v)) <= 1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003218 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003219 z = (PyLongObject *)_PyLong_Copy(v);
3220 if (z != NULL)
Christian Heimes90aa7642007-12-19 02:45:37 +00003221 Py_SIZE(z) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003222 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003223}
3224
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003225static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003226long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003227{
Christian Heimes90aa7642007-12-19 02:45:37 +00003228 if (Py_SIZE(v) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003229 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003230 else
Guido van Rossumb43daf72007-08-01 18:08:08 +00003231 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003232}
3233
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003234static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003235long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003236{
Christian Heimes90aa7642007-12-19 02:45:37 +00003237 return ABS(Py_SIZE(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003238}
3239
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003240static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003241long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003242{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003243 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003244 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003245 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003246 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003247
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003248 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003249
Christian Heimes90aa7642007-12-19 02:45:37 +00003250 if (Py_SIZE(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003251 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003252 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003253 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003254 if (a1 == NULL)
3255 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003256 a2 = (PyLongObject *) long_rshift(a1, b);
3257 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003258 if (a2 == NULL)
3259 goto rshift_error;
3260 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003261 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003262 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003263 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003264
Neil Schemenauerba872e22001-01-04 01:46:03 +00003265 shiftby = PyLong_AsLong((PyObject *)b);
3266 if (shiftby == -1L && PyErr_Occurred())
3267 goto rshift_error;
3268 if (shiftby < 0) {
3269 PyErr_SetString(PyExc_ValueError,
3270 "negative shift count");
3271 goto rshift_error;
3272 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003273 wordshift = shiftby / PyLong_SHIFT;
Christian Heimes90aa7642007-12-19 02:45:37 +00003274 newsize = ABS(Py_SIZE(a)) - wordshift;
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003275 if (newsize <= 0)
3276 return PyLong_FromLong(0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003277 loshift = shiftby % PyLong_SHIFT;
3278 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003279 lomask = ((digit)1 << hishift) - 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003280 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003281 z = _PyLong_New(newsize);
3282 if (z == NULL)
3283 goto rshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003284 if (Py_SIZE(a) < 0)
3285 Py_SIZE(z) = -(Py_SIZE(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003286 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3287 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3288 if (i+1 < newsize)
3289 z->ob_digit[i] |=
3290 (a->ob_digit[j+1] << hishift) & himask;
3291 }
3292 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003293 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003294rshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003295 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003296
Guido van Rossumc6913e71991-11-19 20:26:46 +00003297}
3298
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003299static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003300long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003301{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003302 /* This version due to Tim Peters */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003303 PyLongObject *a = (PyLongObject*)v;
3304 PyLongObject *b = (PyLongObject*)w;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003305 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003306 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003307 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003308 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003309
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003310 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003311
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003312 shiftby = PyLong_AsLong((PyObject *)b);
3313 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003314 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003315 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003316 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003317 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003318 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003319 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003320 PyErr_SetString(PyExc_ValueError,
3321 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003322 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003323 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003324 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3325 wordshift = (int)shiftby / PyLong_SHIFT;
3326 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003327
Christian Heimes90aa7642007-12-19 02:45:37 +00003328 oldsize = ABS(Py_SIZE(a));
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003329 newsize = oldsize + wordshift;
3330 if (remshift)
3331 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003332 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003333 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003334 goto lshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003335 if (Py_SIZE(a) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003336 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003337 for (i = 0; i < wordshift; i++)
3338 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003339 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003340 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003341 accum |= (twodigits)a->ob_digit[j] << remshift;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003342 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3343 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003344 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003345 if (remshift)
3346 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003347 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003348 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003349 z = long_normalize(z);
3350lshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003351 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003352}
3353
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003354
3355/* Bitwise and/xor/or operations */
3356
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003357static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003358long_bitwise(PyLongObject *a,
3359 int op, /* '&', '|', '^' */
3360 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003361{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003362 digit maska, maskb; /* 0 or PyLong_MASK */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003363 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003364 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003365 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003366 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003367 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003368 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003369
Christian Heimes90aa7642007-12-19 02:45:37 +00003370 if (Py_SIZE(a) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003371 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003372 if (a == NULL)
3373 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003374 maska = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003375 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003376 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003377 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003378 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003379 }
Christian Heimes90aa7642007-12-19 02:45:37 +00003380 if (Py_SIZE(b) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003381 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003382 if (b == NULL) {
3383 Py_DECREF(a);
3384 return NULL;
3385 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003386 maskb = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003387 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003388 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003389 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003390 maskb = 0;
3391 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003392
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003393 negz = 0;
3394 switch (op) {
3395 case '^':
3396 if (maska != maskb) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003397 maska ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003398 negz = -1;
3399 }
3400 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003401 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003402 if (maska && maskb) {
3403 op = '|';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003404 maska ^= PyLong_MASK;
3405 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003406 negz = -1;
3407 }
3408 break;
3409 case '|':
3410 if (maska || maskb) {
3411 op = '&';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003412 maska ^= PyLong_MASK;
3413 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003414 negz = -1;
3415 }
3416 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003417 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003418
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003419 /* JRH: The original logic here was to allocate the result value (z)
3420 as the longer of the two operands. However, there are some cases
3421 where the result is guaranteed to be shorter than that: AND of two
3422 positives, OR of two negatives: use the shorter number. AND with
3423 mixed signs: use the positive number. OR with mixed signs: use the
3424 negative number. After the transformations above, op will be '&'
3425 iff one of these cases applies, and mask will be non-0 for operands
3426 whose length should be ignored.
3427 */
3428
Christian Heimes90aa7642007-12-19 02:45:37 +00003429 size_a = Py_SIZE(a);
3430 size_b = Py_SIZE(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003431 size_z = op == '&'
3432 ? (maska
3433 ? size_b
3434 : (maskb ? size_a : MIN(size_a, size_b)))
3435 : MAX(size_a, size_b);
3436 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003437 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003438 Py_DECREF(a);
3439 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003440 return NULL;
3441 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003442
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003443 for (i = 0; i < size_z; ++i) {
3444 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3445 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3446 switch (op) {
3447 case '&': z->ob_digit[i] = diga & digb; break;
3448 case '|': z->ob_digit[i] = diga | digb; break;
3449 case '^': z->ob_digit[i] = diga ^ digb; break;
3450 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003451 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003452
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003453 Py_DECREF(a);
3454 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003455 z = long_normalize(z);
3456 if (negz == 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003457 return (PyObject *) maybe_small_long(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003458 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003459 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003460 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003461}
3462
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003463static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003464long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003465{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003466 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003467 CHECK_BINOP(a, b);
3468 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003469 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003470}
3471
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003472static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003473long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003474{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003475 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003476 CHECK_BINOP(a, b);
3477 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003478 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003479}
3480
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003481static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003482long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003483{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003484 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003485 CHECK_BINOP(a, b);
3486 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003487 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003488}
3489
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003490static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003491long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003492{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003493 if (PyLong_CheckExact(v))
3494 Py_INCREF(v);
3495 else
3496 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003497 return v;
3498}
3499
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003500static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003501long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003502{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003503 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003504 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003505 if (result == -1.0 && PyErr_Occurred())
3506 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003507 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003508}
3509
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003510static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003511long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003512
Tim Peters6d6c1a32001-08-02 04:15:00 +00003513static PyObject *
3514long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3515{
3516 PyObject *x = NULL;
3517 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003518 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003519
Guido van Rossumbef14172001-08-29 15:47:46 +00003520 if (type != &PyLong_Type)
3521 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003522 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003523 &x, &base))
3524 return NULL;
3525 if (x == NULL)
3526 return PyLong_FromLong(0L);
3527 if (base == -909)
3528 return PyNumber_Long(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003529 else if (PyUnicode_Check(x))
3530 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3531 PyUnicode_GET_SIZE(x),
3532 base);
Christian Heimes72b710a2008-05-26 13:28:38 +00003533 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003534 /* Since PyLong_FromString doesn't have a length parameter,
3535 * check here for possible NULs in the string. */
Guido van Rossum98297ee2007-11-06 21:34:58 +00003536 char *string;
Christian Heimes90aa7642007-12-19 02:45:37 +00003537 int size = Py_SIZE(x);
Christian Heimes9c4756e2008-05-26 13:22:05 +00003538 if (PyByteArray_Check(x))
3539 string = PyByteArray_AS_STRING(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003540 else
Christian Heimes72b710a2008-05-26 13:28:38 +00003541 string = PyBytes_AS_STRING(x);
Guido van Rossum4581ae52007-05-22 21:56:47 +00003542 if (strlen(string) != size) {
Guido van Rossum25236212007-08-22 23:28:23 +00003543 /* We only see this if there's a null byte in x,
Guido van Rossum98297ee2007-11-06 21:34:58 +00003544 x is a bytes or buffer, *and* a base is given. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003545 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00003546 "invalid literal for int() with base %d: %R",
3547 base, x);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003548 return NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003549 }
Guido van Rossum4581ae52007-05-22 21:56:47 +00003550 return PyLong_FromString(string, NULL, base);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003551 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003552 else {
3553 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003554 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003555 return NULL;
3556 }
3557}
3558
Guido van Rossumbef14172001-08-29 15:47:46 +00003559/* Wimpy, slow approach to tp_new calls for subtypes of long:
3560 first create a regular long from whatever arguments we got,
3561 then allocate a subtype instance and initialize it from
3562 the regular long. The regular long is then thrown away.
3563*/
3564static PyObject *
3565long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3566{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003567 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003568 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003569
3570 assert(PyType_IsSubtype(type, &PyLong_Type));
3571 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3572 if (tmp == NULL)
3573 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003574 assert(PyLong_CheckExact(tmp));
Christian Heimes90aa7642007-12-19 02:45:37 +00003575 n = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003576 if (n < 0)
3577 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003578 newobj = (PyLongObject *)type->tp_alloc(type, n);
3579 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003580 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003581 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003582 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003583 assert(PyLong_Check(newobj));
Christian Heimes90aa7642007-12-19 02:45:37 +00003584 Py_SIZE(newobj) = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003585 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003586 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003587 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003588 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003589}
3590
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003591static PyObject *
3592long_getnewargs(PyLongObject *v)
3593{
3594 return Py_BuildValue("(N)", _PyLong_Copy(v));
3595}
3596
Guido van Rossumb43daf72007-08-01 18:08:08 +00003597static PyObject *
3598long_getN(PyLongObject *v, void *context) {
Christian Heimesc36625b2008-01-04 13:33:00 +00003599 return PyLong_FromLong((Py_intptr_t)context);
Guido van Rossumb43daf72007-08-01 18:08:08 +00003600}
3601
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003602static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00003603long__format__(PyObject *self, PyObject *args)
3604{
Eric Smith4a7d76d2008-05-30 18:10:19 +00003605 PyObject *format_spec;
3606
3607 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3608 return NULL;
3609 return _PyLong_FormatAdvanced(self,
3610 PyUnicode_AS_UNICODE(format_spec),
3611 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00003612}
3613
3614
3615static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003616long_round(PyObject *self, PyObject *args)
3617{
3618#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
3619 int ndigits = UNDEF_NDIGITS;
3620 double x;
3621 PyObject *res;
3622
3623 if (!PyArg_ParseTuple(args, "|i", &ndigits))
3624 return NULL;
3625
3626 if (ndigits == UNDEF_NDIGITS)
3627 return long_long(self);
3628
3629 /* If called with two args, defer to float.__round__(). */
3630 x = PyLong_AsDouble(self);
3631 if (x == -1.0 && PyErr_Occurred())
3632 return NULL;
3633 self = PyFloat_FromDouble(x);
3634 if (self == NULL)
3635 return NULL;
3636 res = PyObject_CallMethod(self, "__round__", "i", ndigits);
3637 Py_DECREF(self);
3638 return res;
3639#undef UNDEF_NDIGITS
3640}
3641
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003642static PyObject *
3643long_sizeof(PyLongObject *v)
3644{
3645 Py_ssize_t res;
3646
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003647 res = sizeof(PyVarObject) + abs(Py_SIZE(v))*sizeof(digit);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003648 return PyLong_FromSsize_t(res);
3649}
3650
Christian Heimes53876d92008-04-19 00:31:39 +00003651#if 0
3652static PyObject *
3653long_is_finite(PyObject *v)
3654{
3655 Py_RETURN_TRUE;
3656}
3657#endif
3658
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003659static PyMethodDef long_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00003660 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
3661 "Returns self, the complex conjugate of any int."},
Christian Heimes53876d92008-04-19 00:31:39 +00003662#if 0
3663 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
3664 "Returns always True."},
3665#endif
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003666 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
3667 "Truncating an Integral returns itself."},
3668 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
3669 "Flooring an Integral returns itself."},
3670 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
3671 "Ceiling of an Integral returns itself."},
3672 {"__round__", (PyCFunction)long_round, METH_VARARGS,
3673 "Rounding an Integral returns itself.\n"
3674 "Rounding with an ndigits arguments defers to float.__round__."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003675 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smith8c663262007-08-25 02:26:07 +00003676 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003677 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
3678 "Returns size in memory, in bytes"},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003679 {NULL, NULL} /* sentinel */
3680};
3681
Guido van Rossumb43daf72007-08-01 18:08:08 +00003682static PyGetSetDef long_getset[] = {
3683 {"real",
3684 (getter)long_long, (setter)NULL,
3685 "the real part of a complex number",
3686 NULL},
3687 {"imag",
3688 (getter)long_getN, (setter)NULL,
3689 "the imaginary part of a complex number",
3690 (void*)0},
3691 {"numerator",
3692 (getter)long_long, (setter)NULL,
3693 "the numerator of a rational number in lowest terms",
3694 NULL},
3695 {"denominator",
3696 (getter)long_getN, (setter)NULL,
3697 "the denominator of a rational number in lowest terms",
3698 (void*)1},
3699 {NULL} /* Sentinel */
3700};
3701
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003702PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003703"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003704\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00003705Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003706point argument will be truncated towards zero (this does not include a\n\
3707string representation of a floating point number!) When converting a\n\
3708string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003709converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003710
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003711static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003712 (binaryfunc) long_add, /*nb_add*/
3713 (binaryfunc) long_sub, /*nb_subtract*/
3714 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003715 long_mod, /*nb_remainder*/
3716 long_divmod, /*nb_divmod*/
3717 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003718 (unaryfunc) long_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003719 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003720 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00003721 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003722 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003723 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003724 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003725 long_and, /*nb_and*/
3726 long_xor, /*nb_xor*/
3727 long_or, /*nb_or*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003728 long_long, /*nb_int*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003729 long_long, /*nb_long*/
3730 long_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00003731 0, /* nb_inplace_add */
3732 0, /* nb_inplace_subtract */
3733 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00003734 0, /* nb_inplace_remainder */
3735 0, /* nb_inplace_power */
3736 0, /* nb_inplace_lshift */
3737 0, /* nb_inplace_rshift */
3738 0, /* nb_inplace_and */
3739 0, /* nb_inplace_xor */
3740 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003741 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003742 long_true_divide, /* nb_true_divide */
3743 0, /* nb_inplace_floor_divide */
3744 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003745 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003746};
3747
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003748PyTypeObject PyLong_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003749 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003750 "int", /* tp_name */
3751 /* See _PyLong_New for why this isn't
3752 sizeof(PyLongObject) - sizeof(digit) */
3753 sizeof(PyVarObject), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003754 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003755 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003756 0, /* tp_print */
3757 0, /* tp_getattr */
3758 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003759 0, /* tp_compare */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003760 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003761 &long_as_number, /* tp_as_number */
3762 0, /* tp_as_sequence */
3763 0, /* tp_as_mapping */
3764 (hashfunc)long_hash, /* tp_hash */
3765 0, /* tp_call */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003766 long_repr, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003767 PyObject_GenericGetAttr, /* tp_getattro */
3768 0, /* tp_setattro */
3769 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00003770 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
3771 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003772 long_doc, /* tp_doc */
3773 0, /* tp_traverse */
3774 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003775 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003776 0, /* tp_weaklistoffset */
3777 0, /* tp_iter */
3778 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003779 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003780 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00003781 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003782 0, /* tp_base */
3783 0, /* tp_dict */
3784 0, /* tp_descr_get */
3785 0, /* tp_descr_set */
3786 0, /* tp_dictoffset */
3787 0, /* tp_init */
3788 0, /* tp_alloc */
3789 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003790 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003791};
Guido van Rossumddefaf32007-01-14 03:31:43 +00003792
3793int
3794_PyLong_Init(void)
3795{
3796#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003797 int ival, size;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003798 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003799
3800 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
3801 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
3802 if (Py_TYPE(v) == &PyLong_Type) {
3803 /* The element is already initialized, most likely
3804 * the Python interpreter was initialized before.
3805 */
Christian Heimes48aa4b12008-02-01 16:56:30 +00003806 Py_ssize_t refcnt;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003807 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003808
Christian Heimes48aa4b12008-02-01 16:56:30 +00003809 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
3810 _Py_NewReference(op);
3811 /* _Py_NewReference sets the ref count to 1 but
3812 * the ref count might be larger. Set the refcnt
3813 * to the original refcnt + 1 */
3814 Py_REFCNT(op) = refcnt + 1;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003815 assert(Py_SIZE(op) == size);
3816 assert(v->ob_digit[0] == abs(ival));
3817 }
3818 else {
3819 PyObject_INIT(v, &PyLong_Type);
3820 }
3821 Py_SIZE(v) = size;
3822 v->ob_digit[0] = abs(ival);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003823 }
3824#endif
3825 return 1;
3826}
3827
3828void
3829PyLong_Fini(void)
3830{
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003831 /* Integers are currently statically allocated. Py_DECREF is not
3832 needed, but Python must forget about the reference or multiple
3833 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003834#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003835 int i;
3836 PyLongObject *v = small_ints;
3837 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
3838 _Py_DEC_REFTOTAL;
3839 _Py_ForgetReference((PyObject*)v);
3840 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003841#endif
3842}