blob: 44b040cf9e3521b69851fe6ba8263bd6d183e833 [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
Eric Smith8c663262007-08-25 02:26:07 +00008#include "formatter_unicode.h"
9
Guido van Rossumeb1fafc1994-08-29 12:47:19 +000010#include <ctype.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000011
Guido van Rossumddefaf32007-01-14 03:31:43 +000012#ifndef NSMALLPOSINTS
13#define NSMALLPOSINTS 257
14#endif
15#ifndef NSMALLNEGINTS
16#define NSMALLNEGINTS 5
17#endif
18#if NSMALLNEGINTS + NSMALLPOSINTS > 0
19/* Small integers are preallocated in this array so that they
20 can be shared.
21 The integers that are preallocated are those in the range
22 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
23*/
24static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
25#ifdef COUNT_ALLOCS
26int quick_int_allocs, quick_neg_int_allocs;
27#endif
28
Guido van Rossum7eaf8222007-06-18 17:58:50 +000029static PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +000030get_small_int(int ival)
31{
32 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
33 Py_INCREF(v);
34#ifdef COUNT_ALLOCS
35 if (ival >= 0)
36 quick_int_allocs++;
37 else
38 quick_neg_int_allocs++;
39#endif
40 return v;
41}
42#define CHECK_SMALL_INT(ival) \
43 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
44 return get_small_int(ival); \
45 } while(0)
46
47#else
48#define CHECK_SMALL_INT(ival)
49#endif
50
Christian Heimes90aa7642007-12-19 02:45:37 +000051#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(x)->ob_digit[0] : (Py_SIZE(x) == 0 ? 0 : (x)->ob_digit[0]))
Guido van Rossumddefaf32007-01-14 03:31:43 +000052/* If a freshly-allocated long is already shared, it must
53 be a small integer, so negating it must go to PyLong_FromLong */
54#define NEGATE(x) \
Christian Heimes90aa7642007-12-19 02:45:37 +000055 do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \
Christian Heimes217cfd12007-12-02 14:31:20 +000056 else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \
Guido van Rossumddefaf32007-01-14 03:31:43 +000057 Py_DECREF(x); (x) = (PyLongObject*)tmp; } \
58 while(0)
Tim Peters5af4e6c2002-08-12 02:31:19 +000059/* For long multiplication, use the O(N**2) school algorithm unless
60 * both operands contain more than KARATSUBA_CUTOFF digits (this
61 * being an internal Python long digit, in base BASE).
62 */
Tim Peters0973b992004-08-29 22:16:50 +000063#define KARATSUBA_CUTOFF 70
64#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000065
Tim Peters47e52ee2004-08-30 02:44:38 +000066/* For exponentiation, use the binary left-to-right algorithm
67 * unless the exponent contains more than FIVEARY_CUTOFF digits.
68 * In that case, do 5 bits at a time. The potential drawback is that
69 * a table of 2**5 intermediate results is computed.
70 */
71#define FIVEARY_CUTOFF 8
72
Guido van Rossume32e0141992-01-19 16:31:05 +000073#define ABS(x) ((x) < 0 ? -(x) : (x))
74
Tim Peters5af4e6c2002-08-12 02:31:19 +000075#undef MIN
76#undef MAX
77#define MAX(x, y) ((x) < (y) ? (y) : (x))
78#define MIN(x, y) ((x) > (y) ? (y) : (x))
79
Guido van Rossume32e0141992-01-19 16:31:05 +000080/* Forward */
Tim Peters9f688bf2000-07-07 15:53:28 +000081static PyLongObject *long_normalize(PyLongObject *);
82static PyLongObject *mul1(PyLongObject *, wdigit);
83static PyLongObject *muladd1(PyLongObject *, wdigit, wdigit);
Tim Peters212e6142001-07-14 12:23:19 +000084static PyLongObject *divrem1(PyLongObject *, digit, digit *);
Guido van Rossume32e0141992-01-19 16:31:05 +000085
Guido van Rossumc0b618a1997-05-02 03:12:38 +000086#define SIGCHECK(PyTryBlock) \
Skip Montanarod581d772002-09-03 20:10:45 +000087 if (--_Py_Ticker < 0) { \
88 _Py_Ticker = _Py_CheckInterval; \
Thomas Wouters477c8d52006-05-27 19:21:47 +000089 if (PyErr_CheckSignals()) PyTryBlock \
Guido van Rossum23d6f0e1991-05-14 12:06:49 +000090 }
91
Guido van Rossumedcc38a1991-05-05 20:09:44 +000092/* Normalize (remove leading zeros from) a long int object.
93 Doesn't attempt to free the storage--in most cases, due to the nature
94 of the algorithms used, this could save at most be one word anyway. */
95
Guido van Rossumc0b618a1997-05-02 03:12:38 +000096static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +000097long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +000098{
Christian Heimes90aa7642007-12-19 02:45:37 +000099 Py_ssize_t j = ABS(Py_SIZE(v));
Martin v. Löwis18e16552006-02-15 17:27:45 +0000100 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000101
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000102 while (i > 0 && v->ob_digit[i-1] == 0)
103 --i;
104 if (i != j)
Christian Heimes90aa7642007-12-19 02:45:37 +0000105 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000106 return v;
107}
108
109/* Allocate a new long int object with size digits.
110 Return NULL and set exception if we run out of memory. */
111
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000112PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000113_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000114{
Guido van Rossumddefaf32007-01-14 03:31:43 +0000115 PyLongObject *result;
116 /* Can't use sizeof(PyLongObject) here, since the
117 compiler takes padding at the end into account.
118 As the consequence, this would waste 2 bytes on
119 a 32-bit system, and 6 bytes on a 64-bit system.
120 This computation would be incorrect on systems
121 which have padding before the digits; with 16-bit
122 digits this should not happen. */
123 result = PyObject_MALLOC(sizeof(PyVarObject) +
124 size*sizeof(digit));
125 if (!result) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000126 PyErr_NoMemory();
127 return NULL;
128 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000129 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000130}
131
Tim Peters64b5ce32001-09-10 20:52:51 +0000132PyObject *
133_PyLong_Copy(PyLongObject *src)
134{
135 PyLongObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000136 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000137
138 assert(src != NULL);
Christian Heimes90aa7642007-12-19 02:45:37 +0000139 i = Py_SIZE(src);
Tim Peters64b5ce32001-09-10 20:52:51 +0000140 if (i < 0)
141 i = -(i);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000142 if (i < 2) {
143 int ival = src->ob_digit[0];
Christian Heimes90aa7642007-12-19 02:45:37 +0000144 if (Py_SIZE(src) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000145 ival = -ival;
146 CHECK_SMALL_INT(ival);
147 }
Tim Peters64b5ce32001-09-10 20:52:51 +0000148 result = _PyLong_New(i);
149 if (result != NULL) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000150 Py_SIZE(result) = Py_SIZE(src);
Tim Peters64b5ce32001-09-10 20:52:51 +0000151 while (--i >= 0)
152 result->ob_digit[i] = src->ob_digit[i];
153 }
154 return (PyObject *)result;
155}
156
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000157/* Create a new long int object from a C long int */
158
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000159PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000160PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000161{
Tim Petersce9de2f2001-06-14 04:56:19 +0000162 PyLongObject *v;
163 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
164 int ndigits = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000165 int sign = 1;
166
167 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000168
169 if (ival < 0) {
170 ival = -ival;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000171 sign = -1;
Tim Petersce9de2f2001-06-14 04:56:19 +0000172 }
173
Guido van Rossumddefaf32007-01-14 03:31:43 +0000174 /* Fast path for single-digits ints */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000175 if (!(ival>>PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000176 v = _PyLong_New(1);
177 if (v) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000178 Py_SIZE(v) = sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000179 v->ob_digit[0] = ival;
180 }
181 return (PyObject*)v;
182 }
183
184 /* 2 digits */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000185 if (!(ival >> 2*PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000186 v = _PyLong_New(2);
187 if (v) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000188 Py_SIZE(v) = 2*sign;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000189 v->ob_digit[0] = (digit)ival & PyLong_MASK;
190 v->ob_digit[1] = ival >> PyLong_SHIFT;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000191 }
192 return (PyObject*)v;
193 }
194
195 /* Larger numbers: loop to determine number of digits */
Tim Petersce9de2f2001-06-14 04:56:19 +0000196 t = (unsigned long)ival;
197 while (t) {
198 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000199 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000200 }
201 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000202 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000203 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +0000204 Py_SIZE(v) = ndigits*sign;
Tim Petersce9de2f2001-06-14 04:56:19 +0000205 t = (unsigned long)ival;
206 while (t) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000207 *p++ = (digit)(t & PyLong_MASK);
208 t >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000209 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000210 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000211 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000212}
213
Guido van Rossum53756b11997-01-03 17:14:46 +0000214/* Create a new long int object from a C unsigned long int */
215
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000216PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000217PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000218{
Tim Petersce9de2f2001-06-14 04:56:19 +0000219 PyLongObject *v;
220 unsigned long t;
221 int ndigits = 0;
222
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000223 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000224 return PyLong_FromLong(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000225 /* Count the number of Python digits. */
226 t = (unsigned long)ival;
227 while (t) {
228 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000229 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000230 }
231 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000232 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000233 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +0000234 Py_SIZE(v) = ndigits;
Tim Petersce9de2f2001-06-14 04:56:19 +0000235 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000236 *p++ = (digit)(ival & PyLong_MASK);
237 ival >>= PyLong_SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000238 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000239 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000240 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000241}
242
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000243/* Create a new long int object from a C double */
244
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000245PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000246PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000247{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000248 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000249 double frac;
250 int i, ndig, expo, neg;
251 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000252 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000253 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000254 "cannot convert float infinity to int");
Guido van Rossum1a23c241999-09-27 17:11:52 +0000255 return NULL;
256 }
Christian Heimesa34706f2008-01-04 03:06:10 +0000257 if (Py_IS_NAN(dval)) {
Christian Heimes386cd1e2008-01-15 02:01:20 +0000258 PyErr_SetString(PyExc_OverflowError,
259 "cannot convert float NaN to int");
260 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +0000261 }
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000262 if (dval < 0.0) {
263 neg = 1;
264 dval = -dval;
265 }
266 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
267 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000268 return PyLong_FromLong(0L);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000269 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000270 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000271 if (v == NULL)
272 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000273 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000274 for (i = ndig; --i >= 0; ) {
275 long bits = (long)frac;
Guido van Rossum2095d241997-04-09 19:41:24 +0000276 v->ob_digit[i] = (digit) bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000277 frac = frac - (double)bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000278 frac = ldexp(frac, PyLong_SHIFT);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000279 }
280 if (neg)
Christian Heimes90aa7642007-12-19 02:45:37 +0000281 Py_SIZE(v) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000282 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000283}
284
Thomas Wouters89f507f2006-12-13 04:49:30 +0000285/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
286 * anything about what happens when a signed integer operation overflows,
287 * and some compilers think they're doing you a favor by being "clever"
288 * then. The bit pattern for the largest postive signed long is
289 * (unsigned long)LONG_MAX, and for the smallest negative signed long
290 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
291 * However, some other compilers warn about applying unary minus to an
292 * unsigned operand. Hence the weird "0-".
293 */
294#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
295#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
296
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000297/* Get a C long int from a long int object.
298 Returns -1 and sets an error condition if overflow occurs. */
299
300long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000301PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000302{
Guido van Rossumf7531811998-05-26 14:33:37 +0000303 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000304 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000305 unsigned long x, prev;
Georg Brandl61c31b02007-02-26 14:46:30 +0000306 long res;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000307 Py_ssize_t i;
308 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000309 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000310
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000311 *overflow = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000312 if (vv == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000313 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000314 return -1;
315 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000316
317 if (!PyLong_Check(vv)) {
318 PyNumberMethods *nb;
319 if ((nb = vv->ob_type->tp_as_number) == NULL ||
320 nb->nb_int == NULL) {
321 PyErr_SetString(PyExc_TypeError, "an integer is required");
322 return -1;
323 }
324 vv = (*nb->nb_int) (vv);
325 if (vv == NULL)
326 return -1;
327 do_decref = 1;
328 if (!PyLong_Check(vv)) {
329 Py_DECREF(vv);
330 PyErr_SetString(PyExc_TypeError,
331 "nb_int should return int object");
332 return -1;
333 }
334 }
335
Georg Brandl61c31b02007-02-26 14:46:30 +0000336 res = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000337 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000338 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000339
Georg Brandl61c31b02007-02-26 14:46:30 +0000340 switch (i) {
341 case -1:
342 res = -v->ob_digit[0];
343 break;
344 case 0:
345 res = 0;
346 break;
347 case 1:
348 res = v->ob_digit[0];
349 break;
350 default:
351 sign = 1;
352 x = 0;
353 if (i < 0) {
354 sign = -1;
355 i = -(i);
356 }
357 while (--i >= 0) {
358 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000359 x = (x << PyLong_SHIFT) + v->ob_digit[i];
360 if ((x >> PyLong_SHIFT) != prev) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000361 *overflow = Py_SIZE(v) > 0 ? 1 : -1;
Georg Brandl61c31b02007-02-26 14:46:30 +0000362 goto exit;
363 }
364 }
365 /* Haven't lost any bits, but casting to long requires extra care
366 * (see comment above).
367 */
368 if (x <= (unsigned long)LONG_MAX) {
369 res = (long)x * sign;
370 }
371 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
372 res = LONG_MIN;
373 }
374 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000375 *overflow = Py_SIZE(v) > 0 ? 1 : -1;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000376 /* res is already set to -1 */
Georg Brandl61c31b02007-02-26 14:46:30 +0000377 }
378 }
379 exit:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000380 if (do_decref) {
381 Py_DECREF(vv);
382 }
Georg Brandl61c31b02007-02-26 14:46:30 +0000383 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000384}
385
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000386long
387PyLong_AsLong(PyObject *obj)
388{
389 int overflow;
390 long result = PyLong_AsLongAndOverflow(obj, &overflow);
391 if (overflow) {
392 /* XXX: could be cute and give a different
393 message for overflow == -1 */
394 PyErr_SetString(PyExc_OverflowError,
395 "Python int too large to convert to C long");
396 }
397 return result;
398}
399
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000400/* Get a Py_ssize_t from a long int object.
401 Returns -1 and sets an error condition if overflow occurs. */
402
403Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000404PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000405 register PyLongObject *v;
406 size_t x, prev;
407 Py_ssize_t i;
408 int sign;
409
410 if (vv == NULL || !PyLong_Check(vv)) {
411 PyErr_BadInternalCall();
412 return -1;
413 }
414 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000415 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000416 switch (i) {
417 case -1: return -v->ob_digit[0];
418 case 0: return 0;
419 case 1: return v->ob_digit[0];
420 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000421 sign = 1;
422 x = 0;
423 if (i < 0) {
424 sign = -1;
425 i = -(i);
426 }
427 while (--i >= 0) {
428 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000429 x = (x << PyLong_SHIFT) + v->ob_digit[i];
430 if ((x >> PyLong_SHIFT) != prev)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000431 goto overflow;
432 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000433 /* Haven't lost any bits, but casting to a signed type requires
434 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000435 */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000436 if (x <= (size_t)PY_SSIZE_T_MAX) {
437 return (Py_ssize_t)x * sign;
438 }
439 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
440 return PY_SSIZE_T_MIN;
441 }
442 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000443
444 overflow:
445 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000446 "Python int too large to convert to C ssize_t");
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000447 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000448}
449
Guido van Rossumd8c80482002-08-13 00:24:58 +0000450/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000451 Returns -1 and sets an error condition if overflow occurs. */
452
453unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000454PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000455{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000456 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000457 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000458 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000459
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000460 if (vv == NULL || !PyLong_Check(vv)) {
461 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000462 return (unsigned long) -1;
463 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000464 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000465 i = Py_SIZE(v);
Guido van Rossum53756b11997-01-03 17:14:46 +0000466 x = 0;
467 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000468 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000469 "can't convert negative value to unsigned int");
Guido van Rossum53756b11997-01-03 17:14:46 +0000470 return (unsigned long) -1;
471 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000472 switch (i) {
473 case 0: return 0;
474 case 1: return v->ob_digit[0];
475 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000476 while (--i >= 0) {
477 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000478 x = (x << PyLong_SHIFT) + v->ob_digit[i];
479 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000480 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000481 "python int too large to convert to C unsigned long");
Guido van Rossumddefaf32007-01-14 03:31:43 +0000482 return (unsigned long) -1;
483 }
484 }
485 return x;
486}
487
488/* Get a C unsigned long int from a long int object.
489 Returns -1 and sets an error condition if overflow occurs. */
490
491size_t
492PyLong_AsSize_t(PyObject *vv)
493{
494 register PyLongObject *v;
495 size_t x, prev;
496 Py_ssize_t i;
497
498 if (vv == NULL || !PyLong_Check(vv)) {
499 PyErr_BadInternalCall();
500 return (unsigned long) -1;
501 }
502 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000503 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000504 x = 0;
505 if (i < 0) {
506 PyErr_SetString(PyExc_OverflowError,
507 "can't convert negative value to size_t");
508 return (size_t) -1;
509 }
510 switch (i) {
511 case 0: return 0;
512 case 1: return v->ob_digit[0];
513 }
514 while (--i >= 0) {
515 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000516 x = (x << PyLong_SHIFT) + v->ob_digit[i];
517 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000518 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000519 "Python int too large to convert to C size_t");
Guido van Rossum53756b11997-01-03 17:14:46 +0000520 return (unsigned long) -1;
521 }
522 }
523 return x;
524}
525
Thomas Hellera4ea6032003-04-17 18:55:45 +0000526/* Get a C unsigned long int from a long int object, ignoring the high bits.
527 Returns -1 and sets an error condition if an error occurs. */
528
Guido van Rossumddefaf32007-01-14 03:31:43 +0000529static unsigned long
530_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000531{
532 register PyLongObject *v;
533 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000534 Py_ssize_t i;
535 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000536
537 if (vv == NULL || !PyLong_Check(vv)) {
538 PyErr_BadInternalCall();
539 return (unsigned long) -1;
540 }
541 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000542 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000543 switch (i) {
544 case 0: return 0;
545 case 1: return v->ob_digit[0];
546 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000547 sign = 1;
548 x = 0;
549 if (i < 0) {
550 sign = -1;
551 i = -i;
552 }
553 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000554 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +0000555 }
556 return x * sign;
557}
558
Guido van Rossumddefaf32007-01-14 03:31:43 +0000559unsigned long
560PyLong_AsUnsignedLongMask(register PyObject *op)
561{
562 PyNumberMethods *nb;
563 PyLongObject *lo;
564 unsigned long val;
565
566 if (op && PyLong_Check(op))
567 return _PyLong_AsUnsignedLongMask(op);
568
569 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
570 nb->nb_int == NULL) {
571 PyErr_SetString(PyExc_TypeError, "an integer is required");
572 return (unsigned long)-1;
573 }
574
575 lo = (PyLongObject*) (*nb->nb_int) (op);
576 if (lo == NULL)
577 return (unsigned long)-1;
578 if (PyLong_Check(lo)) {
579 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
580 Py_DECREF(lo);
581 if (PyErr_Occurred())
582 return (unsigned long)-1;
583 return val;
584 }
585 else
586 {
587 Py_DECREF(lo);
588 PyErr_SetString(PyExc_TypeError,
589 "nb_int should return int object");
590 return (unsigned long)-1;
591 }
592}
593
Tim Peters5b8132f2003-01-31 15:52:05 +0000594int
595_PyLong_Sign(PyObject *vv)
596{
597 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000598
599 assert(v != NULL);
600 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000601
Christian Heimes90aa7642007-12-19 02:45:37 +0000602 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000603}
604
Tim Petersbaefd9e2003-01-28 20:37:45 +0000605size_t
606_PyLong_NumBits(PyObject *vv)
607{
608 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000609 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000610 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000611
612 assert(v != NULL);
613 assert(PyLong_Check(v));
Christian Heimes90aa7642007-12-19 02:45:37 +0000614 ndigits = ABS(Py_SIZE(v));
Tim Petersbaefd9e2003-01-28 20:37:45 +0000615 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
616 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000617 digit msd = v->ob_digit[ndigits - 1];
618
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000619 result = (ndigits - 1) * PyLong_SHIFT;
620 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000621 goto Overflow;
622 do {
623 ++result;
624 if (result == 0)
625 goto Overflow;
626 msd >>= 1;
627 } while (msd);
628 }
629 return result;
630
631Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000632 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
Tim Petersbaefd9e2003-01-28 20:37:45 +0000633 "to express in a platform size_t");
634 return (size_t)-1;
635}
636
Tim Peters2a9b3672001-06-11 21:23:58 +0000637PyObject *
638_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
639 int little_endian, int is_signed)
640{
641 const unsigned char* pstartbyte;/* LSB of bytes */
642 int incr; /* direction to move pstartbyte */
643 const unsigned char* pendbyte; /* MSB of bytes */
644 size_t numsignificantbytes; /* number of bytes that matter */
645 size_t ndigits; /* number of Python long digits */
646 PyLongObject* v; /* result */
647 int idigit = 0; /* next free index in v->ob_digit */
648
649 if (n == 0)
650 return PyLong_FromLong(0L);
651
652 if (little_endian) {
653 pstartbyte = bytes;
654 pendbyte = bytes + n - 1;
655 incr = 1;
656 }
657 else {
658 pstartbyte = bytes + n - 1;
659 pendbyte = bytes;
660 incr = -1;
661 }
662
663 if (is_signed)
664 is_signed = *pendbyte >= 0x80;
665
666 /* Compute numsignificantbytes. This consists of finding the most
667 significant byte. Leading 0 bytes are insignficant if the number
668 is positive, and leading 0xff bytes if negative. */
669 {
670 size_t i;
671 const unsigned char* p = pendbyte;
672 const int pincr = -incr; /* search MSB to LSB */
673 const unsigned char insignficant = is_signed ? 0xff : 0x00;
674
675 for (i = 0; i < n; ++i, p += pincr) {
676 if (*p != insignficant)
677 break;
678 }
679 numsignificantbytes = n - i;
680 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
681 actually has 2 significant bytes. OTOH, 0xff0001 ==
682 -0x00ffff, so we wouldn't *need* to bump it there; but we
683 do for 0xffff = -0x0001. To be safe without bothering to
684 check every case, bump it regardless. */
685 if (is_signed && numsignificantbytes < n)
686 ++numsignificantbytes;
687 }
688
689 /* How many Python long digits do we need? We have
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000690 8*numsignificantbytes bits, and each Python long digit has PyLong_SHIFT
Tim Peters2a9b3672001-06-11 21:23:58 +0000691 bits, so it's the ceiling of the quotient. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000692 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
Tim Peters2a9b3672001-06-11 21:23:58 +0000693 if (ndigits > (size_t)INT_MAX)
694 return PyErr_NoMemory();
695 v = _PyLong_New((int)ndigits);
696 if (v == NULL)
697 return NULL;
698
699 /* Copy the bits over. The tricky parts are computing 2's-comp on
700 the fly for signed numbers, and dealing with the mismatch between
701 8-bit bytes and (probably) 15-bit Python digits.*/
702 {
703 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000704 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000705 twodigits accum = 0; /* sliding register */
706 unsigned int accumbits = 0; /* number of bits in accum */
707 const unsigned char* p = pstartbyte;
708
709 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000710 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000711 /* Compute correction for 2's comp, if needed. */
712 if (is_signed) {
713 thisbyte = (0xff ^ thisbyte) + carry;
714 carry = thisbyte >> 8;
715 thisbyte &= 0xff;
716 }
717 /* Because we're going LSB to MSB, thisbyte is
718 more significant than what's already in accum,
719 so needs to be prepended to accum. */
720 accum |= thisbyte << accumbits;
721 accumbits += 8;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000722 if (accumbits >= PyLong_SHIFT) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000723 /* There's enough to fill a Python digit. */
724 assert(idigit < (int)ndigits);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000725 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Tim Peters2a9b3672001-06-11 21:23:58 +0000726 ++idigit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000727 accum >>= PyLong_SHIFT;
728 accumbits -= PyLong_SHIFT;
729 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000730 }
731 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000732 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000733 if (accumbits) {
734 assert(idigit < (int)ndigits);
735 v->ob_digit[idigit] = (digit)accum;
736 ++idigit;
737 }
738 }
739
Christian Heimes90aa7642007-12-19 02:45:37 +0000740 Py_SIZE(v) = is_signed ? -idigit : idigit;
Tim Peters2a9b3672001-06-11 21:23:58 +0000741 return (PyObject *)long_normalize(v);
742}
743
744int
745_PyLong_AsByteArray(PyLongObject* v,
746 unsigned char* bytes, size_t n,
747 int little_endian, int is_signed)
748{
749 int i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000750 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000751 twodigits accum; /* sliding register */
752 unsigned int accumbits; /* # bits in accum */
753 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
754 twodigits carry; /* for computing 2's-comp */
755 size_t j; /* # bytes filled */
756 unsigned char* p; /* pointer to next byte in bytes */
757 int pincr; /* direction to move p */
758
759 assert(v != NULL && PyLong_Check(v));
760
Christian Heimes90aa7642007-12-19 02:45:37 +0000761 if (Py_SIZE(v) < 0) {
762 ndigits = -(Py_SIZE(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000763 if (!is_signed) {
764 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000765 "can't convert negative int to unsigned");
Tim Peters2a9b3672001-06-11 21:23:58 +0000766 return -1;
767 }
768 do_twos_comp = 1;
769 }
770 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000771 ndigits = Py_SIZE(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000772 do_twos_comp = 0;
773 }
774
775 if (little_endian) {
776 p = bytes;
777 pincr = 1;
778 }
779 else {
780 p = bytes + n - 1;
781 pincr = -1;
782 }
783
Tim Peters898cf852001-06-13 20:50:08 +0000784 /* Copy over all the Python digits.
785 It's crucial that every Python digit except for the MSD contribute
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000786 exactly PyLong_SHIFT bits to the total, so first assert that the long is
Tim Peters898cf852001-06-13 20:50:08 +0000787 normalized. */
788 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000789 j = 0;
790 accum = 0;
791 accumbits = 0;
792 carry = do_twos_comp ? 1 : 0;
793 for (i = 0; i < ndigits; ++i) {
794 twodigits thisdigit = v->ob_digit[i];
795 if (do_twos_comp) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000796 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
797 carry = thisdigit >> PyLong_SHIFT;
798 thisdigit &= PyLong_MASK;
Tim Peters2a9b3672001-06-11 21:23:58 +0000799 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000800 /* Because we're going LSB to MSB, thisdigit is more
801 significant than what's already in accum, so needs to be
802 prepended to accum. */
803 accum |= thisdigit << accumbits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000804 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000805
Tim Petersede05092001-06-14 08:53:38 +0000806 /* The most-significant digit may be (probably is) at least
807 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000808 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000809 /* Count # of sign bits -- they needn't be stored,
810 * although for signed conversion we need later to
811 * make sure at least one sign bit gets stored.
812 * First shift conceptual sign bit to real sign bit.
813 */
814 stwodigits s = (stwodigits)(thisdigit <<
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000815 (8*sizeof(stwodigits) - PyLong_SHIFT));
Tim Peters7a3bfc32001-06-12 01:22:22 +0000816 unsigned int nsignbits = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000817 while ((s < 0) == do_twos_comp && nsignbits < PyLong_SHIFT) {
Tim Peters7a3bfc32001-06-12 01:22:22 +0000818 ++nsignbits;
Tim Petersede05092001-06-14 08:53:38 +0000819 s <<= 1;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000820 }
Tim Petersede05092001-06-14 08:53:38 +0000821 accumbits -= nsignbits;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000822 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000823
Tim Peters2a9b3672001-06-11 21:23:58 +0000824 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000825 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000826 if (j >= n)
827 goto Overflow;
828 ++j;
829 *p = (unsigned char)(accum & 0xff);
830 p += pincr;
831 accumbits -= 8;
832 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000833 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000834 }
835
836 /* Store the straggler (if any). */
837 assert(accumbits < 8);
838 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000839 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000840 if (j >= n)
841 goto Overflow;
842 ++j;
843 if (do_twos_comp) {
844 /* Fill leading bits of the byte with sign bits
845 (appropriately pretending that the long had an
846 infinite supply of sign bits). */
847 accum |= (~(twodigits)0) << accumbits;
848 }
849 *p = (unsigned char)(accum & 0xff);
850 p += pincr;
851 }
Tim Peters05607ad2001-06-13 21:01:27 +0000852 else if (j == n && n > 0 && is_signed) {
853 /* The main loop filled the byte array exactly, so the code
854 just above didn't get to ensure there's a sign bit, and the
855 loop below wouldn't add one either. Make sure a sign bit
856 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000857 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000858 int sign_bit_set = msb >= 0x80;
859 assert(accumbits == 0);
860 if (sign_bit_set == do_twos_comp)
861 return 0;
862 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000863 goto Overflow;
864 }
Tim Peters05607ad2001-06-13 21:01:27 +0000865
866 /* Fill remaining bytes with copies of the sign bit. */
867 {
868 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
869 for ( ; j < n; ++j, p += pincr)
870 *p = signbyte;
871 }
872
Tim Peters2a9b3672001-06-11 21:23:58 +0000873 return 0;
874
875Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000876 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
Tim Peters2a9b3672001-06-11 21:23:58 +0000877 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000878
Tim Peters2a9b3672001-06-11 21:23:58 +0000879}
880
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000881double
882_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
883{
884/* NBITS_WANTED should be > the number of bits in a double's precision,
885 but small enough so that 2**NBITS_WANTED is within the normal double
886 range. nbitsneeded is set to 1 less than that because the most-significant
887 Python digit contains at least 1 significant bit, but we don't want to
888 bother counting them (catering to the worst case cheaply).
889
890 57 is one more than VAX-D double precision; I (Tim) don't know of a double
891 format with more precision than that; it's 1 larger so that we add in at
892 least one round bit to stand in for the ignored least-significant bits.
893*/
894#define NBITS_WANTED 57
895 PyLongObject *v;
896 double x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000897 const double multiplier = (double)(1L << PyLong_SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000898 Py_ssize_t i;
899 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000900 int nbitsneeded;
901
902 if (vv == NULL || !PyLong_Check(vv)) {
903 PyErr_BadInternalCall();
904 return -1;
905 }
906 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000907 i = Py_SIZE(v);
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000908 sign = 1;
909 if (i < 0) {
910 sign = -1;
911 i = -(i);
912 }
913 else if (i == 0) {
914 *exponent = 0;
915 return 0.0;
916 }
917 --i;
918 x = (double)v->ob_digit[i];
919 nbitsneeded = NBITS_WANTED - 1;
920 /* Invariant: i Python digits remain unaccounted for. */
921 while (i > 0 && nbitsneeded > 0) {
922 --i;
923 x = x * multiplier + (double)v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000924 nbitsneeded -= PyLong_SHIFT;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000925 }
926 /* There are i digits we didn't shift in. Pretending they're all
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000927 zeroes, the true value is x * 2**(i*PyLong_SHIFT). */
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000928 *exponent = i;
929 assert(x > 0.0);
930 return x * sign;
931#undef NBITS_WANTED
932}
933
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000934/* Get a C double from a long int object. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000935
936double
Tim Peters9f688bf2000-07-07 15:53:28 +0000937PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000938{
Thomas Wouters553489a2006-02-01 21:32:04 +0000939 int e = -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000940 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000941
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000942 if (vv == NULL || !PyLong_Check(vv)) {
943 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000944 return -1;
945 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000946 x = _PyLong_AsScaledDouble(vv, &e);
947 if (x == -1.0 && PyErr_Occurred())
948 return -1.0;
Thomas Wouters553489a2006-02-01 21:32:04 +0000949 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
950 set correctly after a successful _PyLong_AsScaledDouble() call */
951 assert(e >= 0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000952 if (e > INT_MAX / PyLong_SHIFT)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000953 goto overflow;
954 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000955 x = ldexp(x, e * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +0000956 if (Py_OVERFLOWED(x))
Tim Peters9fffa3e2001-09-04 05:14:19 +0000957 goto overflow;
958 return x;
959
960overflow:
961 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000962 "Python int too large to convert to C double");
Tim Peters9fffa3e2001-09-04 05:14:19 +0000963 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000964}
965
Guido van Rossum78694d91998-09-18 14:14:13 +0000966/* Create a new long (or int) object from a C pointer */
967
968PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000969PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000970{
Tim Peters70128a12001-06-16 08:48:40 +0000971#ifndef HAVE_LONG_LONG
972# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
973#endif
974#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000975# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000976#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000977 /* special-case null pointer */
978 if (!p)
Christian Heimes217cfd12007-12-02 14:31:20 +0000979 return PyLong_FromLong(0);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000980 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +0000981
Guido van Rossum78694d91998-09-18 14:14:13 +0000982}
983
984/* Get a C pointer from a long object (or an int object in some cases) */
985
986void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000987PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000988{
989 /* This function will allow int or long objects. If vv is neither,
990 then the PyLong_AsLong*() functions will raise the exception:
991 PyExc_SystemError, "bad argument to internal function"
992 */
Tim Peters70128a12001-06-16 08:48:40 +0000993#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +0000994 long x;
995
Guido van Rossumddefaf32007-01-14 03:31:43 +0000996 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000997 x = PyLong_AsLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000998 else
999 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001000#else
Tim Peters70128a12001-06-16 08:48:40 +00001001
1002#ifndef HAVE_LONG_LONG
1003# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1004#endif
1005#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001006# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001007#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001008 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001009
Guido van Rossumddefaf32007-01-14 03:31:43 +00001010 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001011 x = PyLong_AsLongLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001012 else
1013 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001014
1015#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001016
1017 if (x == -1 && PyErr_Occurred())
1018 return NULL;
1019 return (void *)x;
1020}
1021
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001022#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001023
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001024/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001025 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001026 */
1027
Tim Peterscf37dfc2001-06-14 18:42:50 +00001028#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +00001029
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001030/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001031
1032PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001033PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001034{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001035 PyLongObject *v;
1036 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1037 int ndigits = 0;
1038 int negative = 0;
1039
Guido van Rossumddefaf32007-01-14 03:31:43 +00001040 CHECK_SMALL_INT(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001041 if (ival < 0) {
1042 ival = -ival;
1043 negative = 1;
1044 }
1045
1046 /* Count the number of Python digits.
1047 We used to pick 5 ("big enough for anything"), but that's a
1048 waste of time and space given that 5*15 = 75 bits are rarely
1049 needed. */
1050 t = (unsigned PY_LONG_LONG)ival;
1051 while (t) {
1052 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001053 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001054 }
1055 v = _PyLong_New(ndigits);
1056 if (v != NULL) {
1057 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001058 Py_SIZE(v) = negative ? -ndigits : ndigits;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001059 t = (unsigned PY_LONG_LONG)ival;
1060 while (t) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001061 *p++ = (digit)(t & PyLong_MASK);
1062 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001063 }
1064 }
1065 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001066}
1067
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001068/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001069
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001070PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001071PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001072{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001073 PyLongObject *v;
1074 unsigned PY_LONG_LONG t;
1075 int ndigits = 0;
1076
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001077 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001078 return PyLong_FromLong(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001079 /* Count the number of Python digits. */
1080 t = (unsigned PY_LONG_LONG)ival;
1081 while (t) {
1082 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001083 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001084 }
1085 v = _PyLong_New(ndigits);
1086 if (v != NULL) {
1087 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001088 Py_SIZE(v) = ndigits;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001089 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001090 *p++ = (digit)(ival & PyLong_MASK);
1091 ival >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001092 }
1093 }
1094 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001095}
1096
Martin v. Löwis18e16552006-02-15 17:27:45 +00001097/* Create a new long int object from a C Py_ssize_t. */
1098
1099PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001100PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001101{
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001102 PyLongObject *v;
1103 size_t abs_ival;
1104 size_t t; /* unsigned so >> doesn't propagate sign bit */
1105 int ndigits = 0;
1106 int negative = 0;
1107
1108 CHECK_SMALL_INT(ival);
1109 if (ival < 0) {
1110 /* avoid signed overflow when ival = SIZE_T_MIN */
1111 abs_ival = (size_t)(-1-ival)+1;
1112 negative = 1;
1113 }
1114 else {
1115 abs_ival = (size_t)ival;
1116 }
1117
1118 /* Count the number of Python digits. */
1119 t = abs_ival;
1120 while (t) {
1121 ++ndigits;
1122 t >>= PyLong_SHIFT;
1123 }
1124 v = _PyLong_New(ndigits);
1125 if (v != NULL) {
1126 digit *p = v->ob_digit;
1127 Py_SIZE(v) = negative ? -ndigits : ndigits;
1128 t = abs_ival;
1129 while (t) {
1130 *p++ = (digit)(t & PyLong_MASK);
1131 t >>= PyLong_SHIFT;
1132 }
1133 }
1134 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001135}
1136
1137/* Create a new long int object from a C size_t. */
1138
1139PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001140PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001141{
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001142 PyLongObject *v;
1143 size_t t;
1144 int ndigits = 0;
1145
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001146 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001147 return PyLong_FromLong(ival);
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001148 /* Count the number of Python digits. */
1149 t = ival;
1150 while (t) {
1151 ++ndigits;
1152 t >>= PyLong_SHIFT;
1153 }
1154 v = _PyLong_New(ndigits);
1155 if (v != NULL) {
1156 digit *p = v->ob_digit;
1157 Py_SIZE(v) = ndigits;
1158 while (ival) {
1159 *p++ = (digit)(ival & PyLong_MASK);
1160 ival >>= PyLong_SHIFT;
1161 }
1162 }
1163 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001164}
1165
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001166/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001167 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001168
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001169PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001170PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001171{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001172 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001173 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001174 int one = 1;
1175 int res;
1176
Tim Petersd38b1c72001-09-30 05:09:37 +00001177 if (vv == NULL) {
1178 PyErr_BadInternalCall();
1179 return -1;
1180 }
1181 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001182 PyNumberMethods *nb;
1183 PyObject *io;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001184 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1185 nb->nb_int == NULL) {
1186 PyErr_SetString(PyExc_TypeError, "an integer is required");
1187 return -1;
1188 }
1189 io = (*nb->nb_int) (vv);
1190 if (io == NULL)
1191 return -1;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001192 if (PyLong_Check(io)) {
1193 bytes = PyLong_AsLongLong(io);
1194 Py_DECREF(io);
1195 return bytes;
1196 }
1197 Py_DECREF(io);
1198 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001199 return -1;
1200 }
1201
Guido van Rossumddefaf32007-01-14 03:31:43 +00001202 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001203 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001204 case -1: return -v->ob_digit[0];
1205 case 0: return 0;
1206 case 1: return v->ob_digit[0];
1207 }
Tim Petersd1a7da62001-06-13 00:35:57 +00001208 res = _PyLong_AsByteArray(
1209 (PyLongObject *)vv, (unsigned char *)&bytes,
1210 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001211
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001212 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001213 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001214 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001215 else
1216 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001217}
1218
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001219/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001220 Return -1 and set an error if overflow occurs. */
1221
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001222unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001223PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001224{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001225 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001226 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001227 int one = 1;
1228 int res;
1229
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001230 if (vv == NULL || !PyLong_Check(vv)) {
1231 PyErr_BadInternalCall();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001232 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001233 }
1234
Guido van Rossumddefaf32007-01-14 03:31:43 +00001235 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001236 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001237 case 0: return 0;
1238 case 1: return v->ob_digit[0];
1239 }
1240
Tim Petersd1a7da62001-06-13 00:35:57 +00001241 res = _PyLong_AsByteArray(
1242 (PyLongObject *)vv, (unsigned char *)&bytes,
1243 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001244
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001245 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001246 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001247 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001248 else
1249 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001250}
Tim Petersd1a7da62001-06-13 00:35:57 +00001251
Thomas Hellera4ea6032003-04-17 18:55:45 +00001252/* Get a C unsigned long int from a long int object, ignoring the high bits.
1253 Returns -1 and sets an error condition if an error occurs. */
1254
Guido van Rossumddefaf32007-01-14 03:31:43 +00001255static unsigned PY_LONG_LONG
1256_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001257{
1258 register PyLongObject *v;
1259 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001260 Py_ssize_t i;
1261 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001262
1263 if (vv == NULL || !PyLong_Check(vv)) {
1264 PyErr_BadInternalCall();
1265 return (unsigned long) -1;
1266 }
1267 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001268 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001269 case 0: return 0;
1270 case 1: return v->ob_digit[0];
1271 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001272 i = Py_SIZE(v);
Thomas Hellera4ea6032003-04-17 18:55:45 +00001273 sign = 1;
1274 x = 0;
1275 if (i < 0) {
1276 sign = -1;
1277 i = -i;
1278 }
1279 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001280 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +00001281 }
1282 return x * sign;
1283}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001284
1285unsigned PY_LONG_LONG
1286PyLong_AsUnsignedLongLongMask(register PyObject *op)
1287{
1288 PyNumberMethods *nb;
1289 PyLongObject *lo;
1290 unsigned PY_LONG_LONG val;
1291
1292 if (op && PyLong_Check(op))
1293 return _PyLong_AsUnsignedLongLongMask(op);
1294
1295 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1296 nb->nb_int == NULL) {
1297 PyErr_SetString(PyExc_TypeError, "an integer is required");
1298 return (unsigned PY_LONG_LONG)-1;
1299 }
1300
1301 lo = (PyLongObject*) (*nb->nb_int) (op);
1302 if (lo == NULL)
1303 return (unsigned PY_LONG_LONG)-1;
1304 if (PyLong_Check(lo)) {
1305 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1306 Py_DECREF(lo);
1307 if (PyErr_Occurred())
1308 return (unsigned PY_LONG_LONG)-1;
1309 return val;
1310 }
1311 else
1312 {
1313 Py_DECREF(lo);
1314 PyErr_SetString(PyExc_TypeError,
1315 "nb_int should return int object");
1316 return (unsigned PY_LONG_LONG)-1;
1317 }
1318}
Tim Petersd1a7da62001-06-13 00:35:57 +00001319#undef IS_LITTLE_ENDIAN
1320
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001321#endif /* HAVE_LONG_LONG */
1322
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00001323#define CHECK_BINOP(v,w) \
1324 if (!PyLong_Check(v) || !PyLong_Check(w)) { \
Neil Schemenauerba872e22001-01-04 01:46:03 +00001325 Py_INCREF(Py_NotImplemented); \
1326 return Py_NotImplemented; \
1327 }
1328
Tim Peters877a2122002-08-12 05:09:36 +00001329/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1330 * is modified in place, by adding y to it. Carries are propagated as far as
1331 * x[m-1], and the remaining carry (0 or 1) is returned.
1332 */
1333static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001334v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001335{
1336 int i;
1337 digit carry = 0;
1338
1339 assert(m >= n);
1340 for (i = 0; i < n; ++i) {
1341 carry += x[i] + y[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001342 x[i] = carry & PyLong_MASK;
1343 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001344 assert((carry & 1) == carry);
1345 }
1346 for (; carry && i < m; ++i) {
1347 carry += x[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001348 x[i] = carry & PyLong_MASK;
1349 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001350 assert((carry & 1) == carry);
1351 }
1352 return carry;
1353}
1354
1355/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1356 * is modified in place, by subtracting y from it. Borrows are propagated as
1357 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1358 */
1359static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001360v_isub(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 borrow = 0;
1364
1365 assert(m >= n);
1366 for (i = 0; i < n; ++i) {
1367 borrow = x[i] - y[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001368 x[i] = borrow & PyLong_MASK;
1369 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001370 borrow &= 1; /* keep only 1 sign bit */
1371 }
1372 for (; borrow && i < m; ++i) {
1373 borrow = x[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001374 x[i] = borrow & PyLong_MASK;
1375 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001376 borrow &= 1;
1377 }
1378 return borrow;
1379}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001380
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001381/* Multiply by a single digit, ignoring the sign. */
1382
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001383static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001384mul1(PyLongObject *a, wdigit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001385{
1386 return muladd1(a, n, (digit)0);
1387}
1388
1389/* Multiply by a single digit and add a single digit, ignoring the sign. */
1390
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001391static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001392muladd1(PyLongObject *a, wdigit n, wdigit extra)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001393{
Christian Heimes90aa7642007-12-19 02:45:37 +00001394 Py_ssize_t size_a = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001395 PyLongObject *z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001396 twodigits carry = extra;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001397 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001398
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001399 if (z == NULL)
1400 return NULL;
1401 for (i = 0; i < size_a; ++i) {
1402 carry += (twodigits)a->ob_digit[i] * n;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001403 z->ob_digit[i] = (digit) (carry & PyLong_MASK);
1404 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001405 }
Guido van Rossum2095d241997-04-09 19:41:24 +00001406 z->ob_digit[i] = (digit) carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001407 return long_normalize(z);
1408}
1409
Tim Peters212e6142001-07-14 12:23:19 +00001410/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1411 in pout, and returning the remainder. pin and pout point at the LSD.
1412 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001413 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001414 immutable. */
1415
1416static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001417inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001418{
1419 twodigits rem = 0;
1420
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001421 assert(n > 0 && n <= PyLong_MASK);
Tim Peters212e6142001-07-14 12:23:19 +00001422 pin += size;
1423 pout += size;
1424 while (--size >= 0) {
1425 digit hi;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001426 rem = (rem << PyLong_SHIFT) + *--pin;
Tim Peters212e6142001-07-14 12:23:19 +00001427 *--pout = hi = (digit)(rem / n);
1428 rem -= hi * n;
1429 }
1430 return (digit)rem;
1431}
1432
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001433/* Divide a long integer by a digit, returning both the quotient
1434 (as function result) and the remainder (through *prem).
1435 The sign of a is ignored; n should not be zero. */
1436
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001437static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001438divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001439{
Christian Heimes90aa7642007-12-19 02:45:37 +00001440 const Py_ssize_t size = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001441 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001442
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001443 assert(n > 0 && n <= PyLong_MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001444 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001445 if (z == NULL)
1446 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001447 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001448 return long_normalize(z);
1449}
1450
1451/* Convert a long int object to a string, using a given conversion base.
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001452 Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001453 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001454
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001455PyObject *
1456_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001457{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001458 register PyLongObject *a = (PyLongObject *)aa;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001459 PyObject *str;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001460 Py_ssize_t i, j, sz;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001461 Py_ssize_t size_a;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001462 Py_UNICODE *p;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001463 int bits;
1464 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001465
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001466 if (a == NULL || !PyLong_Check(a)) {
1467 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001468 return NULL;
1469 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001470 assert(base >= 2 && base <= 36);
Christian Heimes90aa7642007-12-19 02:45:37 +00001471 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001472
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001473 /* Compute a rough upper bound for the length of the string */
1474 i = base;
1475 bits = 0;
1476 while (i > 1) {
1477 ++bits;
1478 i >>= 1;
1479 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001480 i = 5;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001481 j = size_a*PyLong_SHIFT + bits-1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001482 sz = i + j / bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001483 if (j / PyLong_SHIFT < size_a || sz < i) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001484 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001485 "int is too large to format");
Thomas Wouters89f507f2006-12-13 04:49:30 +00001486 return NULL;
1487 }
Walter Dörwald1ab83302007-05-18 17:15:44 +00001488 str = PyUnicode_FromUnicode(NULL, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001489 if (str == NULL)
1490 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001491 p = PyUnicode_AS_UNICODE(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001492 *p = '\0';
Christian Heimes90aa7642007-12-19 02:45:37 +00001493 if (Py_SIZE(a) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001494 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001495
Christian Heimes90aa7642007-12-19 02:45:37 +00001496 if (Py_SIZE(a) == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001497 *--p = '0';
1498 }
1499 else if ((base & (base - 1)) == 0) {
1500 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001501 twodigits accum = 0;
1502 int accumbits = 0; /* # of bits in accum */
1503 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001504 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001505 while ((i >>= 1) > 1)
1506 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001507
1508 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001509 accum |= (twodigits)a->ob_digit[i] << accumbits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001510 accumbits += PyLong_SHIFT;
Tim Peters586b2e32001-07-15 09:11:14 +00001511 assert(accumbits >= basebits);
1512 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001513 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001514 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001515 assert(p > PyUnicode_AS_UNICODE(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001516 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001517 accumbits -= basebits;
1518 accum >>= basebits;
1519 } while (i < size_a-1 ? accumbits >= basebits :
1520 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001521 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001522 }
1523 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001524 /* Not 0, and base not a power of 2. Divide repeatedly by
1525 base, but for speed use the highest power of base that
1526 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001527 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001528 digit *pin = a->ob_digit;
1529 PyLongObject *scratch;
1530 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001531 digit powbase = base; /* powbase == base ** power */
1532 int power = 1;
1533 for (;;) {
1534 unsigned long newpow = powbase * (unsigned long)base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001535 if (newpow >> PyLong_SHIFT) /* doesn't fit in a digit */
Tim Petersfad225f2001-07-13 02:59:26 +00001536 break;
1537 powbase = (digit)newpow;
1538 ++power;
1539 }
Tim Peters212e6142001-07-14 12:23:19 +00001540
1541 /* Get a scratch area for repeated division. */
1542 scratch = _PyLong_New(size);
1543 if (scratch == NULL) {
1544 Py_DECREF(str);
1545 return NULL;
1546 }
1547
1548 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001549 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001550 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001551 digit rem = inplace_divrem1(scratch->ob_digit,
1552 pin, size, powbase);
1553 pin = scratch->ob_digit; /* no need to use a again */
1554 if (pin[size - 1] == 0)
1555 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001556 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001557 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001558 Py_DECREF(str);
1559 return NULL;
1560 })
Tim Peters212e6142001-07-14 12:23:19 +00001561
1562 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001563 assert(ntostore > 0);
1564 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001565 digit nextrem = (digit)(rem / base);
1566 char c = (char)(rem - nextrem * base);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001567 assert(p > PyUnicode_AS_UNICODE(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001568 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001569 *--p = c;
1570 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001571 --ntostore;
1572 /* Termination is a bit delicate: must not
1573 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001574 remaining quotient and rem are both 0. */
1575 } while (ntostore && (size || rem));
1576 } while (size != 0);
1577 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001578 }
1579
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001580 if (base == 16) {
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001581 *--p = 'x';
1582 *--p = '0';
1583 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001584 else if (base == 8) {
1585 *--p = 'o';
1586 *--p = '0';
1587 }
1588 else if (base == 2) {
1589 *--p = 'b';
1590 *--p = '0';
1591 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001592 else if (base != 10) {
1593 *--p = '#';
1594 *--p = '0' + base%10;
1595 if (base > 10)
1596 *--p = '0' + base/10;
1597 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001598 if (sign)
1599 *--p = sign;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001600 if (p != PyUnicode_AS_UNICODE(str)) {
1601 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001602 assert(p > q);
1603 do {
1604 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001605 q--;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001606 if (PyUnicode_Resize(&str, (Py_ssize_t) (q - PyUnicode_AS_UNICODE(str)))) {
1607 Py_DECREF(str);
1608 return NULL;
1609 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001610 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001611 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001612}
1613
Thomas Wouters477c8d52006-05-27 19:21:47 +00001614/* Table of digit values for 8-bit string -> integer conversion.
1615 * '0' maps to 0, ..., '9' maps to 9.
1616 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1617 * All other indices map to 37.
1618 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001619 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001620 */
1621int _PyLong_DigitValue[256] = {
1622 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1623 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1624 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1625 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1626 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1627 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1628 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1629 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1630 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1631 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1632 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1633 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1634 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1635 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1636 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1637 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1638};
1639
1640/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001641 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1642 * non-digit (which may be *str!). A normalized long is returned.
1643 * The point to this routine is that it takes time linear in the number of
1644 * string characters.
1645 */
1646static PyLongObject *
1647long_from_binary_base(char **str, int base)
1648{
1649 char *p = *str;
1650 char *start = p;
1651 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001652 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001653 PyLongObject *z;
1654 twodigits accum;
1655 int bits_in_accum;
1656 digit *pdigit;
1657
1658 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1659 n = base;
1660 for (bits_per_char = -1; n; ++bits_per_char)
1661 n >>= 1;
1662 /* n <- total # of bits needed, while setting p to end-of-string */
1663 n = 0;
Christian Heimesbbe741d2008-03-28 10:53:29 +00001664 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001665 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001666 *str = p;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001667 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1668 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001669 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001670 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001671 "int string too large to convert");
Tim Peters1a3b19a2003-02-02 17:33:53 +00001672 return NULL;
1673 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001674 n = n / PyLong_SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001675 z = _PyLong_New(n);
1676 if (z == NULL)
1677 return NULL;
1678 /* Read string from right, and fill in long from left; i.e.,
1679 * from least to most significant in both.
1680 */
1681 accum = 0;
1682 bits_in_accum = 0;
1683 pdigit = z->ob_digit;
1684 while (--p >= start) {
Christian Heimesbbe741d2008-03-28 10:53:29 +00001685 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001686 assert(k >= 0 && k < base);
1687 accum |= (twodigits)(k << bits_in_accum);
Tim Petersbf2674b2003-02-02 07:51:32 +00001688 bits_in_accum += bits_per_char;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001689 if (bits_in_accum >= PyLong_SHIFT) {
1690 *pdigit++ = (digit)(accum & PyLong_MASK);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001691 assert(pdigit - z->ob_digit <= (int)n);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001692 accum >>= PyLong_SHIFT;
1693 bits_in_accum -= PyLong_SHIFT;
1694 assert(bits_in_accum < PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001695 }
1696 }
1697 if (bits_in_accum) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001698 assert(bits_in_accum <= PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001699 *pdigit++ = (digit)accum;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001700 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001701 }
1702 while (pdigit - z->ob_digit < n)
1703 *pdigit++ = 0;
1704 return long_normalize(z);
1705}
1706
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001707PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001708PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001709{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001710 int sign = 1, error_if_nonzero = 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001711 char *start, *orig_str = str;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001712 PyLongObject *z = NULL;
Guido van Rossum25236212007-08-22 23:28:23 +00001713 PyObject *strobj;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001714 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001715
Guido van Rossum472c04f1996-12-05 21:57:21 +00001716 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001717 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001718 "int() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001719 return NULL;
1720 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001721 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001722 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001723 if (*str == '+')
1724 ++str;
1725 else if (*str == '-') {
1726 ++str;
1727 sign = -1;
1728 }
1729 if (base == 0) {
1730 if (str[0] != '0')
1731 base = 10;
1732 else if (str[1] == 'x' || str[1] == 'X')
1733 base = 16;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001734 else if (str[1] == 'o' || str[1] == 'O')
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001735 base = 8;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001736 else if (str[1] == 'b' || str[1] == 'B')
1737 base = 2;
1738 else {
1739 /* "old" (C-style) octal literal, now invalid.
1740 it might still be zero though */
1741 error_if_nonzero = 1;
1742 base = 10;
1743 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001744 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001745 if (str[0] == '0' &&
1746 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1747 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1748 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001749 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001750
Guido van Rossume6762971998-06-22 03:54:46 +00001751 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001752 if ((base & (base - 1)) == 0)
1753 z = long_from_binary_base(&str, base);
1754 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001755/***
1756Binary bases can be converted in time linear in the number of digits, because
1757Python's representation base is binary. Other bases (including decimal!) use
1758the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001759
Thomas Wouters477c8d52006-05-27 19:21:47 +00001760First some math: the largest integer that can be expressed in N base-B digits
1761is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1762case number of Python digits needed to hold it is the smallest integer n s.t.
1763
1764 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1765 BASE**n >= B**N [taking logs to base BASE]
1766 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1767
1768The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1769this quickly. A Python long with that much space is reserved near the start,
1770and the result is computed into it.
1771
1772The input string is actually treated as being in base base**i (i.e., i digits
1773are processed at a time), where two more static arrays hold:
1774
1775 convwidth_base[base] = the largest integer i such that base**i <= BASE
1776 convmultmax_base[base] = base ** convwidth_base[base]
1777
1778The first of these is the largest i such that i consecutive input digits
1779must fit in a single Python digit. The second is effectively the input
1780base we're really using.
1781
1782Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1783convmultmax_base[base], the result is "simply"
1784
1785 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1786
1787where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001788
1789Error analysis: as above, the number of Python digits `n` needed is worst-
1790case
1791
1792 n >= N * log(B)/log(BASE)
1793
1794where `N` is the number of input digits in base `B`. This is computed via
1795
1796 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1797
1798below. Two numeric concerns are how much space this can waste, and whether
1799the computed result can be too small. To be concrete, assume BASE = 2**15,
1800which is the default (and it's unlikely anyone changes that).
1801
1802Waste isn't a problem: provided the first input digit isn't 0, the difference
1803between the worst-case input with N digits and the smallest input with N
1804digits is about a factor of B, but B is small compared to BASE so at most
1805one allocated Python digit can remain unused on that count. If
1806N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1807and adding 1 returns a result 1 larger than necessary. However, that can't
1808happen: whenever B is a power of 2, long_from_binary_base() is called
1809instead, and it's impossible for B**i to be an integer power of 2**15 when
1810B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1811an exact integer when B is not a power of 2, since B**i has a prime factor
1812other than 2 in that case, but (2**15)**j's only prime factor is 2).
1813
1814The computed result can be too small if the true value of N*log(B)/log(BASE)
1815is a little bit larger than an exact integer, but due to roundoff errors (in
1816computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1817yields a numeric result a little less than that integer. Unfortunately, "how
1818close can a transcendental function get to an integer over some range?"
1819questions are generally theoretically intractable. Computer analysis via
1820continued fractions is practical: expand log(B)/log(BASE) via continued
1821fractions, giving a sequence i/j of "the best" rational approximations. Then
1822j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1823we can get very close to being in trouble, but very rarely. For example,
182476573 is a denominator in one of the continued-fraction approximations to
1825log(10)/log(2**15), and indeed:
1826
1827 >>> log(10)/log(2**15)*76573
1828 16958.000000654003
1829
1830is very close to an integer. If we were working with IEEE single-precision,
1831rounding errors could kill us. Finding worst cases in IEEE double-precision
1832requires better-than-double-precision log() functions, and Tim didn't bother.
1833Instead the code checks to see whether the allocated space is enough as each
1834new Python digit is added, and copies the whole thing to a larger long if not.
1835This should happen extremely rarely, and in fact I don't have a test case
1836that triggers it(!). Instead the code was tested by artificially allocating
1837just 1 digit at the start, so that the copying code was exercised for every
1838digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001839***/
1840 register twodigits c; /* current input character */
1841 Py_ssize_t size_z;
1842 int i;
1843 int convwidth;
1844 twodigits convmultmax, convmult;
1845 digit *pz, *pzstop;
1846 char* scan;
1847
1848 static double log_base_BASE[37] = {0.0e0,};
1849 static int convwidth_base[37] = {0,};
1850 static twodigits convmultmax_base[37] = {0,};
1851
1852 if (log_base_BASE[base] == 0.0) {
1853 twodigits convmax = base;
1854 int i = 1;
1855
1856 log_base_BASE[base] = log((double)base) /
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001857 log((double)PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001858 for (;;) {
1859 twodigits next = convmax * base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001860 if (next > PyLong_BASE)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001861 break;
1862 convmax = next;
1863 ++i;
1864 }
1865 convmultmax_base[base] = convmax;
1866 assert(i > 0);
1867 convwidth_base[base] = i;
1868 }
1869
1870 /* Find length of the string of numeric characters. */
1871 scan = str;
Christian Heimesbbe741d2008-03-28 10:53:29 +00001872 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001873 ++scan;
1874
1875 /* Create a long object that can contain the largest possible
1876 * integer with this base and length. Note that there's no
1877 * need to initialize z->ob_digit -- no slot is read up before
1878 * being stored into.
1879 */
1880 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001881 /* Uncomment next line to test exceedingly rare copy code */
1882 /* size_z = 1; */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001883 assert(size_z > 0);
1884 z = _PyLong_New(size_z);
1885 if (z == NULL)
1886 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00001887 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001888
1889 /* `convwidth` consecutive input digits are treated as a single
1890 * digit in base `convmultmax`.
1891 */
1892 convwidth = convwidth_base[base];
1893 convmultmax = convmultmax_base[base];
1894
1895 /* Work ;-) */
1896 while (str < scan) {
1897 /* grab up to convwidth digits from the input string */
Christian Heimesbbe741d2008-03-28 10:53:29 +00001898 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Thomas Wouters477c8d52006-05-27 19:21:47 +00001899 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1900 c = (twodigits)(c * base +
Christian Heimesbbe741d2008-03-28 10:53:29 +00001901 _PyLong_DigitValue[Py_CHARMASK(*str)]);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001902 assert(c < PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001903 }
1904
1905 convmult = convmultmax;
1906 /* Calculate the shift only if we couldn't get
1907 * convwidth digits.
1908 */
1909 if (i != convwidth) {
1910 convmult = base;
1911 for ( ; i > 1; --i)
1912 convmult *= base;
1913 }
1914
1915 /* Multiply z by convmult, and add c. */
1916 pz = z->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001917 pzstop = pz + Py_SIZE(z);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001918 for (; pz < pzstop; ++pz) {
1919 c += (twodigits)*pz * convmult;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001920 *pz = (digit)(c & PyLong_MASK);
1921 c >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001922 }
1923 /* carry off the current end? */
1924 if (c) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001925 assert(c < PyLong_BASE);
Christian Heimes90aa7642007-12-19 02:45:37 +00001926 if (Py_SIZE(z) < size_z) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001927 *pz = (digit)c;
Christian Heimes90aa7642007-12-19 02:45:37 +00001928 ++Py_SIZE(z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001929 }
1930 else {
1931 PyLongObject *tmp;
1932 /* Extremely rare. Get more space. */
Christian Heimes90aa7642007-12-19 02:45:37 +00001933 assert(Py_SIZE(z) == size_z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001934 tmp = _PyLong_New(size_z + 1);
1935 if (tmp == NULL) {
1936 Py_DECREF(z);
1937 return NULL;
1938 }
1939 memcpy(tmp->ob_digit,
1940 z->ob_digit,
1941 sizeof(digit) * size_z);
1942 Py_DECREF(z);
1943 z = tmp;
1944 z->ob_digit[size_z] = (digit)c;
1945 ++size_z;
1946 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001947 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001948 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001949 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001950 if (z == NULL)
1951 return NULL;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001952 if (error_if_nonzero) {
1953 /* reset the base to 0, else the exception message
1954 doesn't make too much sense */
1955 base = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +00001956 if (Py_SIZE(z) != 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001957 goto onError;
1958 /* there might still be other problems, therefore base
1959 remains zero here for the same reason */
1960 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00001961 if (str == start)
1962 goto onError;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001963 if (sign < 0)
Christian Heimes90aa7642007-12-19 02:45:37 +00001964 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00001965 if (*str == 'L' || *str == 'l')
1966 str++;
1967 while (*str && isspace(Py_CHARMASK(*str)))
1968 str++;
1969 if (*str != '\0')
1970 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001971 if (pend)
1972 *pend = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001973 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001974
1975 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00001976 Py_XDECREF(z);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001977 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
Guido van Rossum25236212007-08-22 23:28:23 +00001978 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001979 if (strobj == NULL)
1980 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001981 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00001982 "invalid literal for int() with base %d: %R",
1983 base, strobj);
1984 Py_DECREF(strobj);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001985 return NULL;
1986}
1987
1988PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001989PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001990{
Walter Dörwald07e14762002-11-06 16:15:14 +00001991 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001992 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001993
Walter Dörwald07e14762002-11-06 16:15:14 +00001994 if (buffer == NULL)
1995 return NULL;
1996
1997 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1998 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001999 return NULL;
2000 }
Walter Dörwald07e14762002-11-06 16:15:14 +00002001 result = PyLong_FromString(buffer, NULL, base);
2002 PyMem_FREE(buffer);
2003 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002004}
2005
Tim Peters9f688bf2000-07-07 15:53:28 +00002006/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002007static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00002008 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002009static PyObject *long_long(PyObject *v);
Tim Peters9f688bf2000-07-07 15:53:28 +00002010static int long_divrem(PyLongObject *, PyLongObject *,
2011 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002012
2013/* Long division with remainder, top-level routine */
2014
Guido van Rossume32e0141992-01-19 16:31:05 +00002015static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002016long_divrem(PyLongObject *a, PyLongObject *b,
2017 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002018{
Christian Heimes90aa7642007-12-19 02:45:37 +00002019 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002020 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002021
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002022 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002023 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002024 "integer division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00002025 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002026 }
2027 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00002028 (size_a == size_b &&
2029 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002030 /* |a| < |b|. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00002031 *pdiv = (PyLongObject*)PyLong_FromLong(0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002032 if (*pdiv == NULL)
2033 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002034 Py_INCREF(a);
2035 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00002036 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002037 }
2038 if (size_b == 1) {
2039 digit rem = 0;
2040 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002041 if (z == NULL)
2042 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002043 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002044 if (*prem == NULL) {
2045 Py_DECREF(z);
2046 return -1;
2047 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002048 }
Guido van Rossume32e0141992-01-19 16:31:05 +00002049 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002050 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002051 if (z == NULL)
2052 return -1;
2053 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002054 /* Set the signs.
2055 The quotient z has the sign of a*b;
2056 the remainder r has the sign of a,
2057 so a = b*z + r. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002058 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
Guido van Rossumddefaf32007-01-14 03:31:43 +00002059 NEGATE(z);
Christian Heimes90aa7642007-12-19 02:45:37 +00002060 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002061 NEGATE(*prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002062 *pdiv = z;
2063 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002064}
2065
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002066/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002067
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002068static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002069x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002070{
Christian Heimes90aa7642007-12-19 02:45:37 +00002071 Py_ssize_t size_v = ABS(Py_SIZE(v1)), size_w = ABS(Py_SIZE(w1));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002072 digit d = (digit) ((twodigits)PyLong_BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002073 PyLongObject *v = mul1(v1, d);
2074 PyLongObject *w = mul1(w1, d);
2075 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002076 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002077
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002078 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002079 Py_XDECREF(v);
2080 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002081 return NULL;
2082 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002083
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002084 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Christian Heimes90aa7642007-12-19 02:45:37 +00002085 assert(Py_REFCNT(v) == 1); /* Since v will be used as accumulator! */
2086 assert(size_w == ABS(Py_SIZE(w))); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002087
Christian Heimes90aa7642007-12-19 02:45:37 +00002088 size_v = ABS(Py_SIZE(v));
Thomas Wouters477c8d52006-05-27 19:21:47 +00002089 k = size_v - size_w;
2090 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002091
Thomas Wouters477c8d52006-05-27 19:21:47 +00002092 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002093 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
2094 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002095 stwodigits carry = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002096 int i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002097
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002098 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002099 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002100 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002101 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002102 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002103 if (vj == w->ob_digit[size_w-1])
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002104 q = PyLong_MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002105 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002106 q = (((twodigits)vj << PyLong_SHIFT) + v->ob_digit[j-1]) /
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002107 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00002108
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002109 while (w->ob_digit[size_w-2]*q >
2110 ((
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002111 ((twodigits)vj << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002112 + v->ob_digit[j-1]
2113 - q*w->ob_digit[size_w-1]
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002114 ) << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002115 + v->ob_digit[j-2])
2116 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002117
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002118 for (i = 0; i < size_w && i+k < size_v; ++i) {
2119 twodigits z = w->ob_digit[i] * q;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002120 digit zz = (digit) (z >> PyLong_SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002121 carry += v->ob_digit[i+k] - z
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002122 + ((twodigits)zz << PyLong_SHIFT);
2123 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002124 carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002125 carry, PyLong_SHIFT);
Tim Peters7d3a5112000-07-08 04:17:21 +00002126 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002127 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002128
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002129 if (i+k < size_v) {
2130 carry += v->ob_digit[i+k];
2131 v->ob_digit[i+k] = 0;
2132 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002133
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002134 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00002135 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002136 else {
2137 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00002138 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002139 carry = 0;
2140 for (i = 0; i < size_w && i+k < size_v; ++i) {
2141 carry += v->ob_digit[i+k] + w->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002142 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002143 carry = Py_ARITHMETIC_RIGHT_SHIFT(
2144 BASE_TWODIGITS_TYPE,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002145 carry, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002146 }
2147 }
2148 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002149
Guido van Rossumc206c761995-01-10 15:23:19 +00002150 if (a == NULL)
2151 *prem = NULL;
2152 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00002153 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002154 *prem = divrem1(v, d, &d);
2155 /* d receives the (unused) remainder */
2156 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002157 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002158 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002159 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002160 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002161 Py_DECREF(v);
2162 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002163 return a;
2164}
2165
2166/* Methods */
2167
2168static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002169long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002170{
Christian Heimes90aa7642007-12-19 02:45:37 +00002171 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002172}
2173
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002174static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002175long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002176{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002177 return _PyLong_Format(v, 10);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002178}
2179
2180static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002181long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002182{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002183 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002184
Christian Heimes90aa7642007-12-19 02:45:37 +00002185 if (Py_SIZE(a) != Py_SIZE(b)) {
2186 if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002187 sign = 0;
2188 else
Christian Heimes90aa7642007-12-19 02:45:37 +00002189 sign = Py_SIZE(a) - Py_SIZE(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002190 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002191 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002192 Py_ssize_t i = ABS(Py_SIZE(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002193 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2194 ;
2195 if (i < 0)
2196 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002197 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002198 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Christian Heimes90aa7642007-12-19 02:45:37 +00002199 if (Py_SIZE(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002200 sign = -sign;
2201 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002202 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002203 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002204}
2205
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002206static PyObject *
2207long_richcompare(PyObject *self, PyObject *other, int op)
2208{
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002209 PyObject *result;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002210 CHECK_BINOP(self, other);
2211 result = Py_CmpToRich(op, long_compare((PyLongObject*)self,
2212 (PyLongObject*)other));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002213 return result;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002214}
2215
Guido van Rossum9bfef441993-03-29 10:43:31 +00002216static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002217long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002218{
2219 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002220 Py_ssize_t i;
2221 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002222
2223 /* This is designed so that Python ints and longs with the
2224 same value hash to the same value, otherwise comparisons
2225 of mapping keys will turn out weird */
Christian Heimes90aa7642007-12-19 02:45:37 +00002226 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +00002227 switch(i) {
2228 case -1: return v->ob_digit[0]==1 ? -2 : -v->ob_digit[0];
2229 case 0: return 0;
2230 case 1: return v->ob_digit[0];
2231 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002232 sign = 1;
2233 x = 0;
2234 if (i < 0) {
2235 sign = -1;
2236 i = -(i);
2237 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002238#define LONG_BIT_PyLong_SHIFT (8*sizeof(long) - PyLong_SHIFT)
Thomas Woutersce272b62007-09-19 21:19:28 +00002239 /* The following loop produces a C long x such that (unsigned long)x
2240 is congruent to the absolute value of v modulo ULONG_MAX. The
2241 resulting x is nonzero if and only if v is. */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002242 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002243 /* Force a native long #-bits (32 or 64) circular shift */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002244 x = ((x << PyLong_SHIFT) & ~PyLong_MASK) | ((x >> LONG_BIT_PyLong_SHIFT) & PyLong_MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002245 x += v->ob_digit[i];
Thomas Woutersce272b62007-09-19 21:19:28 +00002246 /* If the addition above overflowed (thinking of x as
2247 unsigned), we compensate by incrementing. This preserves
2248 the value modulo ULONG_MAX. */
2249 if ((unsigned long)x < v->ob_digit[i])
2250 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002251 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002252#undef LONG_BIT_PyLong_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00002253 x = x * sign;
2254 if (x == -1)
2255 x = -2;
2256 return x;
2257}
2258
2259
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002260/* Add the absolute values of two long integers. */
2261
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002262static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002263x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002264{
Christian Heimes90aa7642007-12-19 02:45:37 +00002265 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002266 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002267 int i;
2268 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002269
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002270 /* Ensure a is the larger of the two: */
2271 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002272 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002273 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002274 size_a = size_b;
2275 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002276 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002277 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002278 if (z == NULL)
2279 return NULL;
2280 for (i = 0; i < size_b; ++i) {
2281 carry += a->ob_digit[i] + b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002282 z->ob_digit[i] = carry & PyLong_MASK;
2283 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002284 }
2285 for (; i < size_a; ++i) {
2286 carry += a->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002287 z->ob_digit[i] = carry & PyLong_MASK;
2288 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002289 }
2290 z->ob_digit[i] = carry;
2291 return long_normalize(z);
2292}
2293
2294/* Subtract the absolute values of two integers. */
2295
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002296static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002297x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002298{
Christian Heimes90aa7642007-12-19 02:45:37 +00002299 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002300 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002301 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002302 int sign = 1;
2303 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002304
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002305 /* Ensure a is the larger of the two: */
2306 if (size_a < size_b) {
2307 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002308 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002309 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002310 size_a = size_b;
2311 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002312 }
2313 else if (size_a == size_b) {
2314 /* Find highest digit where a and b differ: */
2315 i = size_a;
2316 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2317 ;
2318 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002319 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002320 if (a->ob_digit[i] < b->ob_digit[i]) {
2321 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002322 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002323 }
2324 size_a = size_b = i+1;
2325 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002326 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002327 if (z == NULL)
2328 return NULL;
2329 for (i = 0; i < size_b; ++i) {
2330 /* The following assumes unsigned arithmetic
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002331 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002332 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002333 z->ob_digit[i] = borrow & PyLong_MASK;
2334 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002335 borrow &= 1; /* Keep only one sign bit */
2336 }
2337 for (; i < size_a; ++i) {
2338 borrow = a->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002339 z->ob_digit[i] = borrow & PyLong_MASK;
2340 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002341 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002342 }
2343 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002344 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002345 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002346 return long_normalize(z);
2347}
2348
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002349static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002350long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002351{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002352 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002353
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002354 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002355
Christian Heimes90aa7642007-12-19 02:45:37 +00002356 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Christian Heimes217cfd12007-12-02 14:31:20 +00002357 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002358 MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002359 return result;
2360 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002361 if (Py_SIZE(a) < 0) {
2362 if (Py_SIZE(b) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002363 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002364 if (z != NULL && Py_SIZE(z) != 0)
2365 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002366 }
2367 else
2368 z = x_sub(b, a);
2369 }
2370 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002371 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002372 z = x_sub(a, b);
2373 else
2374 z = x_add(a, b);
2375 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002376 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002377}
2378
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002379static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002380long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002381{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002382 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002383
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002384 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002385
Christian Heimes90aa7642007-12-19 02:45:37 +00002386 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002387 PyObject* r;
2388 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002389 return r;
2390 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002391 if (Py_SIZE(a) < 0) {
2392 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002393 z = x_sub(a, b);
2394 else
2395 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002396 if (z != NULL && Py_SIZE(z) != 0)
2397 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002398 }
2399 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002400 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002401 z = x_add(a, b);
2402 else
2403 z = x_sub(a, b);
2404 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002405 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002406}
2407
Tim Peters5af4e6c2002-08-12 02:31:19 +00002408/* Grade school multiplication, ignoring the signs.
2409 * Returns the absolute value of the product, or NULL if error.
2410 */
2411static PyLongObject *
2412x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002413{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002414 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00002415 Py_ssize_t size_a = ABS(Py_SIZE(a));
2416 Py_ssize_t size_b = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002417 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002418
Tim Peters5af4e6c2002-08-12 02:31:19 +00002419 z = _PyLong_New(size_a + size_b);
2420 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002421 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002422
Christian Heimes90aa7642007-12-19 02:45:37 +00002423 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002424 if (a == b) {
2425 /* Efficient squaring per HAC, Algorithm 14.16:
2426 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2427 * Gives slightly less than a 2x speedup when a == b,
2428 * via exploiting that each entry in the multiplication
2429 * pyramid appears twice (except for the size_a squares).
2430 */
2431 for (i = 0; i < size_a; ++i) {
2432 twodigits carry;
2433 twodigits f = a->ob_digit[i];
2434 digit *pz = z->ob_digit + (i << 1);
2435 digit *pa = a->ob_digit + i + 1;
2436 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002437
Tim Peters0973b992004-08-29 22:16:50 +00002438 SIGCHECK({
2439 Py_DECREF(z);
2440 return NULL;
2441 })
2442
2443 carry = *pz + f * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002444 *pz++ = (digit)(carry & PyLong_MASK);
2445 carry >>= PyLong_SHIFT;
2446 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002447
2448 /* Now f is added in twice in each column of the
2449 * pyramid it appears. Same as adding f<<1 once.
2450 */
2451 f <<= 1;
2452 while (pa < paend) {
2453 carry += *pz + *pa++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002454 *pz++ = (digit)(carry & PyLong_MASK);
2455 carry >>= PyLong_SHIFT;
2456 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002457 }
2458 if (carry) {
2459 carry += *pz;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002460 *pz++ = (digit)(carry & PyLong_MASK);
2461 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002462 }
2463 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002464 *pz += (digit)(carry & PyLong_MASK);
2465 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002466 }
Tim Peters0973b992004-08-29 22:16:50 +00002467 }
2468 else { /* a is not the same as b -- gradeschool long mult */
2469 for (i = 0; i < size_a; ++i) {
2470 twodigits carry = 0;
2471 twodigits f = a->ob_digit[i];
2472 digit *pz = z->ob_digit + i;
2473 digit *pb = b->ob_digit;
2474 digit *pbend = b->ob_digit + size_b;
2475
2476 SIGCHECK({
2477 Py_DECREF(z);
2478 return NULL;
2479 })
2480
2481 while (pb < pbend) {
2482 carry += *pz + *pb++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002483 *pz++ = (digit)(carry & PyLong_MASK);
2484 carry >>= PyLong_SHIFT;
2485 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002486 }
2487 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002488 *pz += (digit)(carry & PyLong_MASK);
2489 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002490 }
2491 }
Tim Peters44121a62002-08-12 06:17:58 +00002492 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002493}
2494
2495/* A helper for Karatsuba multiplication (k_mul).
2496 Takes a long "n" and an integer "size" representing the place to
2497 split, and sets low and high such that abs(n) == (high << size) + low,
2498 viewing the shift as being by digits. The sign bit is ignored, and
2499 the return values are >= 0.
2500 Returns 0 on success, -1 on failure.
2501*/
2502static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002503kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002504{
2505 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002506 Py_ssize_t size_lo, size_hi;
Christian Heimes90aa7642007-12-19 02:45:37 +00002507 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002508
2509 size_lo = MIN(size_n, size);
2510 size_hi = size_n - size_lo;
2511
2512 if ((hi = _PyLong_New(size_hi)) == NULL)
2513 return -1;
2514 if ((lo = _PyLong_New(size_lo)) == NULL) {
2515 Py_DECREF(hi);
2516 return -1;
2517 }
2518
2519 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2520 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2521
2522 *high = long_normalize(hi);
2523 *low = long_normalize(lo);
2524 return 0;
2525}
2526
Tim Peters60004642002-08-12 22:01:34 +00002527static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2528
Tim Peters5af4e6c2002-08-12 02:31:19 +00002529/* Karatsuba multiplication. Ignores the input signs, and returns the
2530 * absolute value of the product (or NULL if error).
2531 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2532 */
2533static PyLongObject *
2534k_mul(PyLongObject *a, PyLongObject *b)
2535{
Christian Heimes90aa7642007-12-19 02:45:37 +00002536 Py_ssize_t asize = ABS(Py_SIZE(a));
2537 Py_ssize_t bsize = ABS(Py_SIZE(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002538 PyLongObject *ah = NULL;
2539 PyLongObject *al = NULL;
2540 PyLongObject *bh = NULL;
2541 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002542 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002543 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002544 Py_ssize_t shift; /* the number of digits we split off */
2545 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002546
Tim Peters5af4e6c2002-08-12 02:31:19 +00002547 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2548 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2549 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002550 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002551 * By picking X to be a power of 2, "*X" is just shifting, and it's
2552 * been reduced to 3 multiplies on numbers half the size.
2553 */
2554
Tim Petersfc07e562002-08-12 02:54:10 +00002555 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002556 * is largest.
2557 */
Tim Peters738eda72002-08-12 15:08:20 +00002558 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002559 t1 = a;
2560 a = b;
2561 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002562
2563 i = asize;
2564 asize = bsize;
2565 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002566 }
2567
2568 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002569 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2570 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002571 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002572 return _PyLong_New(0);
2573 else
2574 return x_mul(a, b);
2575 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002576
Tim Peters60004642002-08-12 22:01:34 +00002577 /* If a is small compared to b, splitting on b gives a degenerate
2578 * case with ah==0, and Karatsuba may be (even much) less efficient
2579 * than "grade school" then. However, we can still win, by viewing
2580 * b as a string of "big digits", each of width a->ob_size. That
2581 * leads to a sequence of balanced calls to k_mul.
2582 */
2583 if (2 * asize <= bsize)
2584 return k_lopsided_mul(a, b);
2585
Tim Petersd6974a52002-08-13 20:37:51 +00002586 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002587 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002588 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002589 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002590
Tim Peters0973b992004-08-29 22:16:50 +00002591 if (a == b) {
2592 bh = ah;
2593 bl = al;
2594 Py_INCREF(bh);
2595 Py_INCREF(bl);
2596 }
2597 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002598
Tim Petersd64c1de2002-08-12 17:36:03 +00002599 /* The plan:
2600 * 1. Allocate result space (asize + bsize digits: that's always
2601 * enough).
2602 * 2. Compute ah*bh, and copy into result at 2*shift.
2603 * 3. Compute al*bl, and copy into result at 0. Note that this
2604 * can't overlap with #2.
2605 * 4. Subtract al*bl from the result, starting at shift. This may
2606 * underflow (borrow out of the high digit), but we don't care:
2607 * we're effectively doing unsigned arithmetic mod
2608 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2609 * borrows and carries out of the high digit can be ignored.
2610 * 5. Subtract ah*bh from the result, starting at shift.
2611 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2612 * at shift.
2613 */
2614
2615 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002616 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002617 if (ret == NULL) goto fail;
2618#ifdef Py_DEBUG
2619 /* Fill with trash, to catch reference to uninitialized digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002620 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002621#endif
Tim Peters44121a62002-08-12 06:17:58 +00002622
Tim Petersd64c1de2002-08-12 17:36:03 +00002623 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002624 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002625 assert(Py_SIZE(t1) >= 0);
2626 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002627 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Christian Heimes90aa7642007-12-19 02:45:37 +00002628 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002629
2630 /* Zero-out the digits higher than the ah*bh copy. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002631 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002632 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002633 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002634 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002635
Tim Petersd64c1de2002-08-12 17:36:03 +00002636 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002637 if ((t2 = k_mul(al, bl)) == NULL) {
2638 Py_DECREF(t1);
2639 goto fail;
2640 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002641 assert(Py_SIZE(t2) >= 0);
2642 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2643 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002644
2645 /* Zero out remaining digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002646 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002647 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002648 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002649
Tim Petersd64c1de2002-08-12 17:36:03 +00002650 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2651 * because it's fresher in cache.
2652 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002653 i = Py_SIZE(ret) - shift; /* # digits after shift */
2654 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002655 Py_DECREF(t2);
2656
Christian Heimes90aa7642007-12-19 02:45:37 +00002657 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002658 Py_DECREF(t1);
2659
Tim Petersd64c1de2002-08-12 17:36:03 +00002660 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002661 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2662 Py_DECREF(ah);
2663 Py_DECREF(al);
2664 ah = al = NULL;
2665
Tim Peters0973b992004-08-29 22:16:50 +00002666 if (a == b) {
2667 t2 = t1;
2668 Py_INCREF(t2);
2669 }
2670 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002671 Py_DECREF(t1);
2672 goto fail;
2673 }
2674 Py_DECREF(bh);
2675 Py_DECREF(bl);
2676 bh = bl = NULL;
2677
Tim Peters738eda72002-08-12 15:08:20 +00002678 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002679 Py_DECREF(t1);
2680 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002681 if (t3 == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002682 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002683
Tim Petersd6974a52002-08-13 20:37:51 +00002684 /* Add t3. It's not obvious why we can't run out of room here.
2685 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002686 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002687 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002688 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002689
Tim Peters5af4e6c2002-08-12 02:31:19 +00002690 return long_normalize(ret);
2691
2692 fail:
2693 Py_XDECREF(ret);
2694 Py_XDECREF(ah);
2695 Py_XDECREF(al);
2696 Py_XDECREF(bh);
2697 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002698 return NULL;
2699}
2700
Tim Petersd6974a52002-08-13 20:37:51 +00002701/* (*) Why adding t3 can't "run out of room" above.
2702
Tim Petersab86c2b2002-08-15 20:06:00 +00002703Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2704to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002705
Tim Petersab86c2b2002-08-15 20:06:00 +000027061. For any integer i, i = c(i/2) + f(i/2). In particular,
2707 bsize = c(bsize/2) + f(bsize/2).
27082. shift = f(bsize/2)
27093. asize <= bsize
27104. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2711 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002712
Tim Petersab86c2b2002-08-15 20:06:00 +00002713We allocated asize + bsize result digits, and add t3 into them at an offset
2714of shift. This leaves asize+bsize-shift allocated digit positions for t3
2715to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2716asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002717
Tim Petersab86c2b2002-08-15 20:06:00 +00002718bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2719at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002720
Tim Petersab86c2b2002-08-15 20:06:00 +00002721If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2722digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2723most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002724
Tim Petersab86c2b2002-08-15 20:06:00 +00002725The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002726
Tim Petersab86c2b2002-08-15 20:06:00 +00002727 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002728
Tim Petersab86c2b2002-08-15 20:06:00 +00002729and we have asize + c(bsize/2) available digit positions. We need to show
2730this is always enough. An instance of c(bsize/2) cancels out in both, so
2731the question reduces to whether asize digits is enough to hold
2732(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2733then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2734asize 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 +00002735digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002736asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002737c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2738is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2739bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002740
Tim Peters48d52c02002-08-14 17:07:32 +00002741Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2742clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2743ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002744*/
2745
Tim Peters60004642002-08-12 22:01:34 +00002746/* b has at least twice the digits of a, and a is big enough that Karatsuba
2747 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2748 * of slices, each with a->ob_size digits, and multiply the slices by a,
2749 * one at a time. This gives k_mul balanced inputs to work with, and is
2750 * also cache-friendly (we compute one double-width slice of the result
2751 * at a time, then move on, never bactracking except for the helpful
2752 * single-width slice overlap between successive partial sums).
2753 */
2754static PyLongObject *
2755k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2756{
Christian Heimes90aa7642007-12-19 02:45:37 +00002757 const Py_ssize_t asize = ABS(Py_SIZE(a));
2758 Py_ssize_t bsize = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002759 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002760 PyLongObject *ret;
2761 PyLongObject *bslice = NULL;
2762
2763 assert(asize > KARATSUBA_CUTOFF);
2764 assert(2 * asize <= bsize);
2765
2766 /* Allocate result space, and zero it out. */
2767 ret = _PyLong_New(asize + bsize);
2768 if (ret == NULL)
2769 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00002770 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002771
2772 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002773 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002774 if (bslice == NULL)
2775 goto fail;
2776
2777 nbdone = 0;
2778 while (bsize > 0) {
2779 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002780 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002781
2782 /* Multiply the next slice of b by a. */
2783 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2784 nbtouse * sizeof(digit));
Christian Heimes90aa7642007-12-19 02:45:37 +00002785 Py_SIZE(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00002786 product = k_mul(a, bslice);
2787 if (product == NULL)
2788 goto fail;
2789
2790 /* Add into result. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002791 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
2792 product->ob_digit, Py_SIZE(product));
Tim Peters60004642002-08-12 22:01:34 +00002793 Py_DECREF(product);
2794
2795 bsize -= nbtouse;
2796 nbdone += nbtouse;
2797 }
2798
2799 Py_DECREF(bslice);
2800 return long_normalize(ret);
2801
2802 fail:
2803 Py_DECREF(ret);
2804 Py_XDECREF(bslice);
2805 return NULL;
2806}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002807
2808static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002809long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002810{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002811 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002812
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002813 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002814
Christian Heimes90aa7642007-12-19 02:45:37 +00002815 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002816 PyObject *r;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002817 r = PyLong_FromLong(MEDIUM_VALUE(a)*MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002818 return r;
2819 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00002820
Tim Petersd64c1de2002-08-12 17:36:03 +00002821 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002822 /* Negate if exactly one of the inputs is negative. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002823 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002824 NEGATE(z);
Tim Peters9973d742002-08-15 19:41:06 +00002825 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002826}
2827
Guido van Rossume32e0141992-01-19 16:31:05 +00002828/* The / and % operators are now defined in terms of divmod().
2829 The expression a mod b has the value a - b*floor(a/b).
2830 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002831 |a| by |b|, with the sign of a. This is also expressed
2832 as a - b*trunc(a/b), if trunc truncates towards zero.
2833 Some examples:
2834 a b a rem b a mod b
2835 13 10 3 3
2836 -13 10 -3 7
2837 13 -10 3 -7
2838 -13 -10 -3 -3
2839 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002840 have different signs. We then subtract one from the 'div'
2841 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002842
Tim Peters47e52ee2004-08-30 02:44:38 +00002843/* Compute
2844 * *pdiv, *pmod = divmod(v, w)
2845 * NULL can be passed for pdiv or pmod, in which case that part of
2846 * the result is simply thrown away. The caller owns a reference to
2847 * each of these it requests (does not pass NULL for).
2848 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002849static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002850l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002851 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002852{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002853 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002854
Guido van Rossume32e0141992-01-19 16:31:05 +00002855 if (long_divrem(v, w, &div, &mod) < 0)
2856 return -1;
Christian Heimes90aa7642007-12-19 02:45:37 +00002857 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
2858 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002859 PyLongObject *temp;
2860 PyLongObject *one;
2861 temp = (PyLongObject *) long_add(mod, w);
2862 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002863 mod = temp;
2864 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002865 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002866 return -1;
2867 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002868 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002869 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002870 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2871 Py_DECREF(mod);
2872 Py_DECREF(div);
2873 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002874 return -1;
2875 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002876 Py_DECREF(one);
2877 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002878 div = temp;
2879 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002880 if (pdiv != NULL)
2881 *pdiv = div;
2882 else
2883 Py_DECREF(div);
2884
2885 if (pmod != NULL)
2886 *pmod = mod;
2887 else
2888 Py_DECREF(mod);
2889
Guido van Rossume32e0141992-01-19 16:31:05 +00002890 return 0;
2891}
2892
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002893static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002894long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00002895{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002896 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002897
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002898 CHECK_BINOP(a, b);
2899 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00002900 div = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002901 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002902}
2903
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002904static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002905long_true_divide(PyObject *a, PyObject *b)
Tim Peters20dab9f2001-09-04 05:31:47 +00002906{
Tim Peterse2a60002001-09-04 06:17:36 +00002907 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002908 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002909
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002910 CHECK_BINOP(a, b);
Tim Peterse2a60002001-09-04 06:17:36 +00002911 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2912 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002913 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
Tim Peters6f97e492001-11-04 23:09:40 +00002914 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002915 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002916 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2917 but should really be set correctly after sucessful calls to
2918 _PyLong_AsScaledDouble() */
2919 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002920
2921 if (bd == 0.0) {
2922 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002923 "int division or modulo by zero");
Tim Peterse2a60002001-09-04 06:17:36 +00002924 return NULL;
2925 }
2926
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002927 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
Tim Peterse2a60002001-09-04 06:17:36 +00002928 ad /= bd; /* overflow/underflow impossible here */
2929 aexp -= bexp;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002930 if (aexp > INT_MAX / PyLong_SHIFT)
Tim Peterse2a60002001-09-04 06:17:36 +00002931 goto overflow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002932 else if (aexp < -(INT_MAX / PyLong_SHIFT))
Tim Peterse56ed9b2001-09-06 21:59:14 +00002933 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002934 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002935 ad = ldexp(ad, aexp * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002936 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002937 goto overflow;
2938 return PyFloat_FromDouble(ad);
2939
2940overflow:
2941 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002942 "int/int too large for a float");
Tim Peterse2a60002001-09-04 06:17:36 +00002943 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002944
Tim Peters20dab9f2001-09-04 05:31:47 +00002945}
2946
2947static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002948long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00002949{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002950 PyLongObject *mod;
2951
2952 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002953
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002954 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00002955 mod = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002956 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002957}
2958
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002959static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002960long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002961{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002962 PyLongObject *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002963 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002964
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002965 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002966
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002967 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002968 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002969 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002970 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002971 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002972 PyTuple_SetItem(z, 0, (PyObject *) div);
2973 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002974 }
2975 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002976 Py_DECREF(div);
2977 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002978 }
2979 return z;
2980}
2981
Tim Peters47e52ee2004-08-30 02:44:38 +00002982/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002983static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002984long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002985{
Tim Peters47e52ee2004-08-30 02:44:38 +00002986 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
2987 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002988
Tim Peters47e52ee2004-08-30 02:44:38 +00002989 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002990 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00002991 PyLongObject *temp = NULL;
2992
2993 /* 5-ary values. If the exponent is large enough, table is
2994 * precomputed so that table[i] == a**i % c for i in range(32).
2995 */
2996 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2997 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2998
2999 /* a, b, c = v, w, x */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003000 CHECK_BINOP(v, w);
3001 a = (PyLongObject*)v; Py_INCREF(a);
3002 b = (PyLongObject*)w; Py_INCREF(b);
Tim Peters47e52ee2004-08-30 02:44:38 +00003003 if (PyLong_Check(x)) {
3004 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003005 Py_INCREF(x);
3006 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003007 else if (x == Py_None)
3008 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003009 else {
3010 Py_DECREF(a);
3011 Py_DECREF(b);
3012 Py_INCREF(Py_NotImplemented);
3013 return Py_NotImplemented;
3014 }
Tim Peters4c483c42001-09-05 06:24:58 +00003015
Christian Heimes90aa7642007-12-19 02:45:37 +00003016 if (Py_SIZE(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00003017 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00003018 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00003019 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00003020 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00003021 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003022 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00003023 /* else return a float. This works because we know
3024 that this calls float_pow() which converts its
3025 arguments to double. */
3026 Py_DECREF(a);
3027 Py_DECREF(b);
3028 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003029 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003030 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003031
3032 if (c) {
3033 /* if modulus == 0:
3034 raise ValueError() */
Christian Heimes90aa7642007-12-19 02:45:37 +00003035 if (Py_SIZE(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003036 PyErr_SetString(PyExc_ValueError,
3037 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003038 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003039 }
3040
3041 /* if modulus < 0:
3042 negativeOutput = True
3043 modulus = -modulus */
Christian Heimes90aa7642007-12-19 02:45:37 +00003044 if (Py_SIZE(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003045 negativeOutput = 1;
3046 temp = (PyLongObject *)_PyLong_Copy(c);
3047 if (temp == NULL)
3048 goto Error;
3049 Py_DECREF(c);
3050 c = temp;
3051 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003052 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003053 }
3054
3055 /* if modulus == 1:
3056 return 0 */
Christian Heimes90aa7642007-12-19 02:45:37 +00003057 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003058 z = (PyLongObject *)PyLong_FromLong(0L);
3059 goto Done;
3060 }
3061
3062 /* if base < 0:
3063 base = base % modulus
3064 Having the base positive just makes things easier. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003065 if (Py_SIZE(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003066 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003067 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003068 Py_DECREF(a);
3069 a = temp;
3070 temp = NULL;
3071 }
3072 }
3073
3074 /* At this point a, b, and c are guaranteed non-negative UNLESS
3075 c is NULL, in which case a may be negative. */
3076
3077 z = (PyLongObject *)PyLong_FromLong(1L);
3078 if (z == NULL)
3079 goto Error;
3080
3081 /* Perform a modular reduction, X = X % c, but leave X alone if c
3082 * is NULL.
3083 */
3084#define REDUCE(X) \
3085 if (c != NULL) { \
3086 if (l_divmod(X, c, NULL, &temp) < 0) \
3087 goto Error; \
3088 Py_XDECREF(X); \
3089 X = temp; \
3090 temp = NULL; \
3091 }
3092
3093 /* Multiply two values, then reduce the result:
3094 result = X*Y % c. If c is NULL, skip the mod. */
3095#define MULT(X, Y, result) \
3096{ \
3097 temp = (PyLongObject *)long_mul(X, Y); \
3098 if (temp == NULL) \
3099 goto Error; \
3100 Py_XDECREF(result); \
3101 result = temp; \
3102 temp = NULL; \
3103 REDUCE(result) \
3104}
3105
Christian Heimes90aa7642007-12-19 02:45:37 +00003106 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003107 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3108 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Christian Heimes90aa7642007-12-19 02:45:37 +00003109 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003110 digit bi = b->ob_digit[i];
3111
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003112 for (j = 1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003113 MULT(z, z, z)
3114 if (bi & j)
3115 MULT(z, a, z)
3116 }
3117 }
3118 }
3119 else {
3120 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3121 Py_INCREF(z); /* still holds 1L */
3122 table[0] = z;
3123 for (i = 1; i < 32; ++i)
3124 MULT(table[i-1], a, table[i])
3125
Christian Heimes90aa7642007-12-19 02:45:37 +00003126 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003127 const digit bi = b->ob_digit[i];
3128
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003129 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003130 const int index = (bi >> j) & 0x1f;
3131 for (k = 0; k < 5; ++k)
3132 MULT(z, z, z)
3133 if (index)
3134 MULT(z, table[index], z)
3135 }
3136 }
3137 }
3138
Christian Heimes90aa7642007-12-19 02:45:37 +00003139 if (negativeOutput && (Py_SIZE(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003140 temp = (PyLongObject *)long_sub(z, c);
3141 if (temp == NULL)
3142 goto Error;
3143 Py_DECREF(z);
3144 z = temp;
3145 temp = NULL;
3146 }
3147 goto Done;
3148
3149 Error:
3150 if (z != NULL) {
3151 Py_DECREF(z);
3152 z = NULL;
3153 }
3154 /* fall through */
3155 Done:
Christian Heimes90aa7642007-12-19 02:45:37 +00003156 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003157 for (i = 0; i < 32; ++i)
3158 Py_XDECREF(table[i]);
3159 }
Tim Petersde7990b2005-07-17 23:45:23 +00003160 Py_DECREF(a);
3161 Py_DECREF(b);
3162 Py_XDECREF(c);
3163 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003164 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003165}
3166
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003167static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003168long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003169{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003170 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003171 PyLongObject *x;
3172 PyLongObject *w;
Christian Heimes90aa7642007-12-19 02:45:37 +00003173 if (ABS(Py_SIZE(v)) <=1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003174 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003175 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003176 if (w == NULL)
3177 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003178 x = (PyLongObject *) long_add(v, w);
3179 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003180 if (x == NULL)
3181 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00003182 Py_SIZE(x) = -(Py_SIZE(x));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003183 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003184}
3185
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003186static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003187long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003188{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003189 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00003190 if (ABS(Py_SIZE(v)) <= 1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003191 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003192 z = (PyLongObject *)_PyLong_Copy(v);
3193 if (z != NULL)
Christian Heimes90aa7642007-12-19 02:45:37 +00003194 Py_SIZE(z) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003195 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003196}
3197
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003198static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003199long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003200{
Christian Heimes90aa7642007-12-19 02:45:37 +00003201 if (Py_SIZE(v) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003202 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003203 else
Guido van Rossumb43daf72007-08-01 18:08:08 +00003204 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003205}
3206
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003207static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003208long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003209{
Christian Heimes90aa7642007-12-19 02:45:37 +00003210 return ABS(Py_SIZE(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003211}
3212
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003213static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003214long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003215{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003216 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003217 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003218 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003219 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003220
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003221 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003222
Christian Heimes90aa7642007-12-19 02:45:37 +00003223 if (Py_SIZE(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003224 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003225 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003226 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003227 if (a1 == NULL)
3228 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003229 a2 = (PyLongObject *) long_rshift(a1, b);
3230 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003231 if (a2 == NULL)
3232 goto rshift_error;
3233 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003234 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003235 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003236 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003237
Neil Schemenauerba872e22001-01-04 01:46:03 +00003238 shiftby = PyLong_AsLong((PyObject *)b);
3239 if (shiftby == -1L && PyErr_Occurred())
3240 goto rshift_error;
3241 if (shiftby < 0) {
3242 PyErr_SetString(PyExc_ValueError,
3243 "negative shift count");
3244 goto rshift_error;
3245 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003246 wordshift = shiftby / PyLong_SHIFT;
Christian Heimes90aa7642007-12-19 02:45:37 +00003247 newsize = ABS(Py_SIZE(a)) - wordshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003248 if (newsize <= 0) {
3249 z = _PyLong_New(0);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003250 return (PyObject *)z;
3251 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003252 loshift = shiftby % PyLong_SHIFT;
3253 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003254 lomask = ((digit)1 << hishift) - 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003255 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003256 z = _PyLong_New(newsize);
3257 if (z == NULL)
3258 goto rshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003259 if (Py_SIZE(a) < 0)
3260 Py_SIZE(z) = -(Py_SIZE(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003261 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3262 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3263 if (i+1 < newsize)
3264 z->ob_digit[i] |=
3265 (a->ob_digit[j+1] << hishift) & himask;
3266 }
3267 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003268 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003269rshift_error:
Neil Schemenauerba872e22001-01-04 01:46:03 +00003270 return (PyObject *) z;
3271
Guido van Rossumc6913e71991-11-19 20:26:46 +00003272}
3273
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003274static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003275long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003276{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003277 /* This version due to Tim Peters */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003278 PyLongObject *a = (PyLongObject*)v;
3279 PyLongObject *b = (PyLongObject*)w;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003280 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003281 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003282 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003283 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003284
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003285 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003286
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003287 shiftby = PyLong_AsLong((PyObject *)b);
3288 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003289 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003290 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003291 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003292 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003293 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003294 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003295 PyErr_SetString(PyExc_ValueError,
3296 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003297 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003298 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003299 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3300 wordshift = (int)shiftby / PyLong_SHIFT;
3301 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003302
Christian Heimes90aa7642007-12-19 02:45:37 +00003303 oldsize = ABS(Py_SIZE(a));
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003304 newsize = oldsize + wordshift;
3305 if (remshift)
3306 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003307 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003308 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003309 goto lshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003310 if (Py_SIZE(a) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003311 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003312 for (i = 0; i < wordshift; i++)
3313 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003314 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003315 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003316 accum |= (twodigits)a->ob_digit[j] << remshift;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003317 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3318 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003319 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003320 if (remshift)
3321 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003322 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003323 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003324 z = long_normalize(z);
3325lshift_error:
Neil Schemenauerba872e22001-01-04 01:46:03 +00003326 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003327}
3328
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003329
3330/* Bitwise and/xor/or operations */
3331
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003332static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003333long_bitwise(PyLongObject *a,
3334 int op, /* '&', '|', '^' */
3335 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003336{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003337 digit maska, maskb; /* 0 or PyLong_MASK */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003338 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003339 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003340 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003341 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003342 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003343 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003344
Christian Heimes90aa7642007-12-19 02:45:37 +00003345 if (Py_SIZE(a) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003346 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003347 if (a == NULL)
3348 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003349 maska = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003350 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003351 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003352 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003353 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003354 }
Christian Heimes90aa7642007-12-19 02:45:37 +00003355 if (Py_SIZE(b) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003356 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003357 if (b == NULL) {
3358 Py_DECREF(a);
3359 return NULL;
3360 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003361 maskb = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003362 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003363 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003364 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003365 maskb = 0;
3366 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003367
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003368 negz = 0;
3369 switch (op) {
3370 case '^':
3371 if (maska != maskb) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003372 maska ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003373 negz = -1;
3374 }
3375 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003376 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003377 if (maska && maskb) {
3378 op = '|';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003379 maska ^= PyLong_MASK;
3380 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003381 negz = -1;
3382 }
3383 break;
3384 case '|':
3385 if (maska || maskb) {
3386 op = '&';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003387 maska ^= PyLong_MASK;
3388 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003389 negz = -1;
3390 }
3391 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003392 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003393
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003394 /* JRH: The original logic here was to allocate the result value (z)
3395 as the longer of the two operands. However, there are some cases
3396 where the result is guaranteed to be shorter than that: AND of two
3397 positives, OR of two negatives: use the shorter number. AND with
3398 mixed signs: use the positive number. OR with mixed signs: use the
3399 negative number. After the transformations above, op will be '&'
3400 iff one of these cases applies, and mask will be non-0 for operands
3401 whose length should be ignored.
3402 */
3403
Christian Heimes90aa7642007-12-19 02:45:37 +00003404 size_a = Py_SIZE(a);
3405 size_b = Py_SIZE(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003406 size_z = op == '&'
3407 ? (maska
3408 ? size_b
3409 : (maskb ? size_a : MIN(size_a, size_b)))
3410 : MAX(size_a, size_b);
3411 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003412 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003413 Py_DECREF(a);
3414 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003415 return NULL;
3416 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003417
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003418 for (i = 0; i < size_z; ++i) {
3419 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3420 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3421 switch (op) {
3422 case '&': z->ob_digit[i] = diga & digb; break;
3423 case '|': z->ob_digit[i] = diga | digb; break;
3424 case '^': z->ob_digit[i] = diga ^ digb; break;
3425 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003426 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003427
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003428 Py_DECREF(a);
3429 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003430 z = long_normalize(z);
3431 if (negz == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003432 return (PyObject *) z;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003433 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003434 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003435 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003436}
3437
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003438static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003439long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003440{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003441 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003442 CHECK_BINOP(a, b);
3443 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003444 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003445}
3446
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003447static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003448long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003449{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003450 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003451 CHECK_BINOP(a, b);
3452 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003453 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003454}
3455
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003456static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003457long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003458{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003459 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003460 CHECK_BINOP(a, b);
3461 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003462 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003463}
3464
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003465static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003466long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003467{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003468 if (PyLong_CheckExact(v))
3469 Py_INCREF(v);
3470 else
3471 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003472 return v;
3473}
3474
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003475static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003476long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003477{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003478 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003479 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003480 if (result == -1.0 && PyErr_Occurred())
3481 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003482 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003483}
3484
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003485static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003486long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003487
Tim Peters6d6c1a32001-08-02 04:15:00 +00003488static PyObject *
3489long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3490{
3491 PyObject *x = NULL;
3492 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003493 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003494
Guido van Rossumbef14172001-08-29 15:47:46 +00003495 if (type != &PyLong_Type)
3496 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003497 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003498 &x, &base))
3499 return NULL;
3500 if (x == NULL)
3501 return PyLong_FromLong(0L);
3502 if (base == -909)
3503 return PyNumber_Long(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003504 else if (PyUnicode_Check(x))
3505 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3506 PyUnicode_GET_SIZE(x),
3507 base);
3508 else if (PyBytes_Check(x) || PyString_Check(x)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003509 /* Since PyLong_FromString doesn't have a length parameter,
3510 * check here for possible NULs in the string. */
Guido van Rossum98297ee2007-11-06 21:34:58 +00003511 char *string;
Christian Heimes90aa7642007-12-19 02:45:37 +00003512 int size = Py_SIZE(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003513 if (PyBytes_Check(x))
3514 string = PyBytes_AS_STRING(x);
3515 else
3516 string = PyString_AS_STRING(x);
Guido van Rossum4581ae52007-05-22 21:56:47 +00003517 if (strlen(string) != size) {
Guido van Rossum25236212007-08-22 23:28:23 +00003518 /* We only see this if there's a null byte in x,
Guido van Rossum98297ee2007-11-06 21:34:58 +00003519 x is a bytes or buffer, *and* a base is given. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003520 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00003521 "invalid literal for int() with base %d: %R",
3522 base, x);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003523 return NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003524 }
Guido van Rossum4581ae52007-05-22 21:56:47 +00003525 return PyLong_FromString(string, NULL, base);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003526 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003527 else {
3528 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003529 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003530 return NULL;
3531 }
3532}
3533
Guido van Rossumbef14172001-08-29 15:47:46 +00003534/* Wimpy, slow approach to tp_new calls for subtypes of long:
3535 first create a regular long from whatever arguments we got,
3536 then allocate a subtype instance and initialize it from
3537 the regular long. The regular long is then thrown away.
3538*/
3539static PyObject *
3540long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3541{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003542 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003543 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003544
3545 assert(PyType_IsSubtype(type, &PyLong_Type));
3546 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3547 if (tmp == NULL)
3548 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003549 assert(PyLong_CheckExact(tmp));
Christian Heimes90aa7642007-12-19 02:45:37 +00003550 n = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003551 if (n < 0)
3552 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003553 newobj = (PyLongObject *)type->tp_alloc(type, n);
3554 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003555 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003556 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003557 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003558 assert(PyLong_Check(newobj));
Christian Heimes90aa7642007-12-19 02:45:37 +00003559 Py_SIZE(newobj) = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003560 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003561 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003562 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003563 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003564}
3565
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003566static PyObject *
3567long_getnewargs(PyLongObject *v)
3568{
3569 return Py_BuildValue("(N)", _PyLong_Copy(v));
3570}
3571
Guido van Rossumb43daf72007-08-01 18:08:08 +00003572static PyObject *
3573long_getN(PyLongObject *v, void *context) {
Christian Heimesc36625b2008-01-04 13:33:00 +00003574 return PyLong_FromLong((Py_intptr_t)context);
Guido van Rossumb43daf72007-08-01 18:08:08 +00003575}
3576
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003577static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00003578long__format__(PyObject *self, PyObject *args)
3579{
3580 /* when back porting this to 2.6, check type of the format_spec
3581 and call either unicode_long__format__ or
3582 string_long__format__ */
3583 return unicode_long__format__(self, args);
3584}
3585
3586
3587static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003588long_round(PyObject *self, PyObject *args)
3589{
3590#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
3591 int ndigits = UNDEF_NDIGITS;
3592 double x;
3593 PyObject *res;
3594
3595 if (!PyArg_ParseTuple(args, "|i", &ndigits))
3596 return NULL;
3597
3598 if (ndigits == UNDEF_NDIGITS)
3599 return long_long(self);
3600
3601 /* If called with two args, defer to float.__round__(). */
3602 x = PyLong_AsDouble(self);
3603 if (x == -1.0 && PyErr_Occurred())
3604 return NULL;
3605 self = PyFloat_FromDouble(x);
3606 if (self == NULL)
3607 return NULL;
3608 res = PyObject_CallMethod(self, "__round__", "i", ndigits);
3609 Py_DECREF(self);
3610 return res;
3611#undef UNDEF_NDIGITS
3612}
3613
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003614static PyMethodDef long_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00003615 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
3616 "Returns self, the complex conjugate of any int."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003617 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
3618 "Truncating an Integral returns itself."},
3619 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
3620 "Flooring an Integral returns itself."},
3621 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
3622 "Ceiling of an Integral returns itself."},
3623 {"__round__", (PyCFunction)long_round, METH_VARARGS,
3624 "Rounding an Integral returns itself.\n"
3625 "Rounding with an ndigits arguments defers to float.__round__."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003626 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smith8c663262007-08-25 02:26:07 +00003627 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003628 {NULL, NULL} /* sentinel */
3629};
3630
Guido van Rossumb43daf72007-08-01 18:08:08 +00003631static PyGetSetDef long_getset[] = {
3632 {"real",
3633 (getter)long_long, (setter)NULL,
3634 "the real part of a complex number",
3635 NULL},
3636 {"imag",
3637 (getter)long_getN, (setter)NULL,
3638 "the imaginary part of a complex number",
3639 (void*)0},
3640 {"numerator",
3641 (getter)long_long, (setter)NULL,
3642 "the numerator of a rational number in lowest terms",
3643 NULL},
3644 {"denominator",
3645 (getter)long_getN, (setter)NULL,
3646 "the denominator of a rational number in lowest terms",
3647 (void*)1},
3648 {NULL} /* Sentinel */
3649};
3650
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003651PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003652"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003653\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00003654Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003655point argument will be truncated towards zero (this does not include a\n\
3656string representation of a floating point number!) When converting a\n\
3657string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003658converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003659
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003660static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003661 (binaryfunc) long_add, /*nb_add*/
3662 (binaryfunc) long_sub, /*nb_subtract*/
3663 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003664 long_mod, /*nb_remainder*/
3665 long_divmod, /*nb_divmod*/
3666 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003667 (unaryfunc) long_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003668 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003669 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00003670 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003671 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003672 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003673 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003674 long_and, /*nb_and*/
3675 long_xor, /*nb_xor*/
3676 long_or, /*nb_or*/
Neil Schemenauer16c70752007-09-21 20:19:23 +00003677 0, /*nb_reserved*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003678 long_long, /*nb_int*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003679 long_long, /*nb_long*/
3680 long_float, /*nb_float*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003681 0, /*nb_oct*/ /* not used */
3682 0, /*nb_hex*/ /* not used */
Guido van Rossum4668b002001-08-08 05:00:18 +00003683 0, /* nb_inplace_add */
3684 0, /* nb_inplace_subtract */
3685 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00003686 0, /* nb_inplace_remainder */
3687 0, /* nb_inplace_power */
3688 0, /* nb_inplace_lshift */
3689 0, /* nb_inplace_rshift */
3690 0, /* nb_inplace_and */
3691 0, /* nb_inplace_xor */
3692 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003693 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003694 long_true_divide, /* nb_true_divide */
3695 0, /* nb_inplace_floor_divide */
3696 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003697 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003698};
3699
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003700PyTypeObject PyLong_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003701 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003702 "int", /* tp_name */
3703 /* See _PyLong_New for why this isn't
3704 sizeof(PyLongObject) - sizeof(digit) */
3705 sizeof(PyVarObject), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003706 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003707 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003708 0, /* tp_print */
3709 0, /* tp_getattr */
3710 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003711 0, /* tp_compare */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003712 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003713 &long_as_number, /* tp_as_number */
3714 0, /* tp_as_sequence */
3715 0, /* tp_as_mapping */
3716 (hashfunc)long_hash, /* tp_hash */
3717 0, /* tp_call */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003718 long_repr, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003719 PyObject_GenericGetAttr, /* tp_getattro */
3720 0, /* tp_setattro */
3721 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00003722 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
3723 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003724 long_doc, /* tp_doc */
3725 0, /* tp_traverse */
3726 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003727 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003728 0, /* tp_weaklistoffset */
3729 0, /* tp_iter */
3730 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003731 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003732 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00003733 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003734 0, /* tp_base */
3735 0, /* tp_dict */
3736 0, /* tp_descr_get */
3737 0, /* tp_descr_set */
3738 0, /* tp_dictoffset */
3739 0, /* tp_init */
3740 0, /* tp_alloc */
3741 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003742 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003743};
Guido van Rossumddefaf32007-01-14 03:31:43 +00003744
3745int
3746_PyLong_Init(void)
3747{
3748#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003749 int ival, size;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003750 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003751
3752 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
3753 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
3754 if (Py_TYPE(v) == &PyLong_Type) {
3755 /* The element is already initialized, most likely
3756 * the Python interpreter was initialized before.
3757 */
Christian Heimes48aa4b12008-02-01 16:56:30 +00003758 Py_ssize_t refcnt;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003759 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003760
Christian Heimes48aa4b12008-02-01 16:56:30 +00003761 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
3762 _Py_NewReference(op);
3763 /* _Py_NewReference sets the ref count to 1 but
3764 * the ref count might be larger. Set the refcnt
3765 * to the original refcnt + 1 */
3766 Py_REFCNT(op) = refcnt + 1;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003767 assert(Py_SIZE(op) == size);
3768 assert(v->ob_digit[0] == abs(ival));
3769 }
3770 else {
3771 PyObject_INIT(v, &PyLong_Type);
3772 }
3773 Py_SIZE(v) = size;
3774 v->ob_digit[0] = abs(ival);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003775 }
3776#endif
3777 return 1;
3778}
3779
3780void
3781PyLong_Fini(void)
3782{
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003783 /* Integers are currently statically allocated. Py_DECREF is not
3784 needed, but Python must forget about the reference or multiple
3785 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003786#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003787 int i;
3788 PyLongObject *v = small_ints;
3789 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
3790 _Py_DEC_REFTOTAL;
3791 _Py_ForgetReference((PyObject*)v);
3792 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003793#endif
3794}