blob: f14f298513b63479f1fe249423be15c0ccc9e43a [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003/* Long (arbitrary precision) integer object implementation */
4
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00005/* XXX The functional organization of this file is terrible */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Guido van Rossumedcc38a1991-05-05 20:09:44 +00008#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00009
Guido van Rossumeb1fafc1994-08-29 12:47:19 +000010#include <ctype.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000011
Tim Peters5af4e6c2002-08-12 02:31:19 +000012/* For long multiplication, use the O(N**2) school algorithm unless
13 * both operands contain more than KARATSUBA_CUTOFF digits (this
14 * being an internal Python long digit, in base BASE).
15 */
Tim Peters0973b992004-08-29 22:16:50 +000016#define KARATSUBA_CUTOFF 70
17#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000018
Tim Peters47e52ee2004-08-30 02:44:38 +000019/* For exponentiation, use the binary left-to-right algorithm
20 * unless the exponent contains more than FIVEARY_CUTOFF digits.
21 * In that case, do 5 bits at a time. The potential drawback is that
22 * a table of 2**5 intermediate results is computed.
23 */
24#define FIVEARY_CUTOFF 8
25
Guido van Rossume32e0141992-01-19 16:31:05 +000026#define ABS(x) ((x) < 0 ? -(x) : (x))
27
Tim Peters5af4e6c2002-08-12 02:31:19 +000028#undef MIN
29#undef MAX
30#define MAX(x, y) ((x) < (y) ? (y) : (x))
31#define MIN(x, y) ((x) > (y) ? (y) : (x))
32
Guido van Rossume32e0141992-01-19 16:31:05 +000033/* Forward */
Tim Peters9f688bf2000-07-07 15:53:28 +000034static PyLongObject *long_normalize(PyLongObject *);
35static PyLongObject *mul1(PyLongObject *, wdigit);
36static PyLongObject *muladd1(PyLongObject *, wdigit, wdigit);
Tim Peters212e6142001-07-14 12:23:19 +000037static PyLongObject *divrem1(PyLongObject *, digit, digit *);
Tim Peters9f688bf2000-07-07 15:53:28 +000038static PyObject *long_format(PyObject *aa, int base, int addL);
Guido van Rossume32e0141992-01-19 16:31:05 +000039
Guido van Rossumc0b618a1997-05-02 03:12:38 +000040#define SIGCHECK(PyTryBlock) \
Skip Montanarod581d772002-09-03 20:10:45 +000041 if (--_Py_Ticker < 0) { \
42 _Py_Ticker = _Py_CheckInterval; \
Tim Petersd89fc222006-05-25 22:28:46 +000043 if (PyErr_CheckSignals()) PyTryBlock \
Guido van Rossum23d6f0e1991-05-14 12:06:49 +000044 }
45
Guido van Rossumedcc38a1991-05-05 20:09:44 +000046/* Normalize (remove leading zeros from) a long int object.
47 Doesn't attempt to free the storage--in most cases, due to the nature
48 of the algorithms used, this could save at most be one word anyway. */
49
Guido van Rossumc0b618a1997-05-02 03:12:38 +000050static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +000051long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +000052{
Martin v. Löwis68192102007-07-21 06:55:02 +000053 Py_ssize_t j = ABS(Py_Size(v));
Martin v. Löwis18e16552006-02-15 17:27:45 +000054 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +000055
Guido van Rossumedcc38a1991-05-05 20:09:44 +000056 while (i > 0 && v->ob_digit[i-1] == 0)
57 --i;
58 if (i != j)
Martin v. Löwis68192102007-07-21 06:55:02 +000059 Py_Size(v) = (Py_Size(v) < 0) ? -(i) : i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +000060 return v;
61}
62
63/* Allocate a new long int object with size digits.
64 Return NULL and set exception if we run out of memory. */
65
Guido van Rossumc0b618a1997-05-02 03:12:38 +000066PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000067_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +000068{
Neal Norwitzc6a989a2006-05-10 06:57:58 +000069 if (size > PY_SSIZE_T_MAX) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000070 PyErr_NoMemory();
71 return NULL;
72 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +000073 return PyObject_NEW_VAR(PyLongObject, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +000074}
75
Tim Peters64b5ce32001-09-10 20:52:51 +000076PyObject *
77_PyLong_Copy(PyLongObject *src)
78{
79 PyLongObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +000080 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +000081
82 assert(src != NULL);
83 i = src->ob_size;
84 if (i < 0)
85 i = -(i);
86 result = _PyLong_New(i);
87 if (result != NULL) {
Tim Peters5329cdb2002-03-02 04:18:04 +000088 result->ob_size = src->ob_size;
Tim Peters64b5ce32001-09-10 20:52:51 +000089 while (--i >= 0)
90 result->ob_digit[i] = src->ob_digit[i];
91 }
92 return (PyObject *)result;
93}
94
Guido van Rossumedcc38a1991-05-05 20:09:44 +000095/* Create a new long int object from a C long int */
96
Guido van Rossumc0b618a1997-05-02 03:12:38 +000097PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +000098PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +000099{
Tim Petersce9de2f2001-06-14 04:56:19 +0000100 PyLongObject *v;
101 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
102 int ndigits = 0;
103 int negative = 0;
104
105 if (ival < 0) {
106 ival = -ival;
107 negative = 1;
108 }
109
110 /* Count the number of Python digits.
111 We used to pick 5 ("big enough for anything"), but that's a
112 waste of time and space given that 5*15 = 75 bits are rarely
113 needed. */
114 t = (unsigned long)ival;
115 while (t) {
116 ++ndigits;
117 t >>= SHIFT;
118 }
119 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000120 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000121 digit *p = v->ob_digit;
122 v->ob_size = negative ? -ndigits : ndigits;
123 t = (unsigned long)ival;
124 while (t) {
125 *p++ = (digit)(t & MASK);
Guido van Rossum472c04f1996-12-05 21:57:21 +0000126 t >>= SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000127 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000128 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000129 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000130}
131
Guido van Rossum53756b11997-01-03 17:14:46 +0000132/* Create a new long int object from a C unsigned long int */
133
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000134PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000135PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000136{
Tim Petersce9de2f2001-06-14 04:56:19 +0000137 PyLongObject *v;
138 unsigned long t;
139 int ndigits = 0;
140
141 /* Count the number of Python digits. */
142 t = (unsigned long)ival;
143 while (t) {
144 ++ndigits;
145 t >>= SHIFT;
146 }
147 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000148 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000149 digit *p = v->ob_digit;
Martin v. Löwis68192102007-07-21 06:55:02 +0000150 Py_Size(v) = ndigits;
Tim Petersce9de2f2001-06-14 04:56:19 +0000151 while (ival) {
152 *p++ = (digit)(ival & MASK);
153 ival >>= SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000154 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000155 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000156 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000157}
158
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000159/* Create a new long int object from a C double */
160
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000161PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000162PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000163{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000164 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000165 double frac;
166 int i, ndig, expo, neg;
167 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000168 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000169 PyErr_SetString(PyExc_OverflowError,
170 "cannot convert float infinity to long");
171 return NULL;
172 }
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000173 if (dval < 0.0) {
174 neg = 1;
175 dval = -dval;
176 }
177 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
178 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000179 return PyLong_FromLong(0L);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000180 ndig = (expo-1) / SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000181 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000182 if (v == NULL)
183 return NULL;
184 frac = ldexp(frac, (expo-1) % SHIFT + 1);
185 for (i = ndig; --i >= 0; ) {
186 long bits = (long)frac;
Guido van Rossum2095d241997-04-09 19:41:24 +0000187 v->ob_digit[i] = (digit) bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000188 frac = frac - (double)bits;
189 frac = ldexp(frac, SHIFT);
190 }
191 if (neg)
Martin v. Löwis68192102007-07-21 06:55:02 +0000192 Py_Size(v) = -(Py_Size(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000193 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000194}
195
Armin Rigo7ccbca92006-10-04 12:17:45 +0000196/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
197 * anything about what happens when a signed integer operation overflows,
198 * and some compilers think they're doing you a favor by being "clever"
199 * then. The bit pattern for the largest postive signed long is
200 * (unsigned long)LONG_MAX, and for the smallest negative signed long
201 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
202 * However, some other compilers warn about applying unary minus to an
203 * unsigned operand. Hence the weird "0-".
204 */
205#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
206#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
207
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000208/* Get a C long int from a long int object.
209 Returns -1 and sets an error condition if overflow occurs. */
210
211long
Tim Peters9f688bf2000-07-07 15:53:28 +0000212PyLong_AsLong(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000213{
Guido van Rossumf7531811998-05-26 14:33:37 +0000214 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000215 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000216 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000217 Py_ssize_t i;
218 int sign;
Guido van Rossumf7531811998-05-26 14:33:37 +0000219
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000220 if (vv == NULL || !PyLong_Check(vv)) {
Guido van Rossum7e35d572001-09-15 03:14:32 +0000221 if (vv != NULL && PyInt_Check(vv))
222 return PyInt_AsLong(vv);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000223 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000224 return -1;
225 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000226 v = (PyLongObject *)vv;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000227 i = v->ob_size;
228 sign = 1;
229 x = 0;
230 if (i < 0) {
231 sign = -1;
Guido van Rossum4c260ff1992-01-14 18:36:43 +0000232 i = -(i);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000233 }
234 while (--i >= 0) {
235 prev = x;
236 x = (x << SHIFT) + v->ob_digit[i];
Guido van Rossumf7531811998-05-26 14:33:37 +0000237 if ((x >> SHIFT) != prev)
238 goto overflow;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000239 }
Armin Rigo7ccbca92006-10-04 12:17:45 +0000240 /* Haven't lost any bits, but casting to long requires extra care
241 * (see comment above).
242 */
243 if (x <= (unsigned long)LONG_MAX) {
244 return (long)x * sign;
245 }
246 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
247 return LONG_MIN;
248 }
249 /* else overflow */
Guido van Rossumf7531811998-05-26 14:33:37 +0000250
251 overflow:
252 PyErr_SetString(PyExc_OverflowError,
Skip Montanarobafedec2001-09-13 19:05:30 +0000253 "long int too large to convert to int");
Guido van Rossumf7531811998-05-26 14:33:37 +0000254 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000255}
256
Neal Norwitz8a87f5d2006-08-12 17:03:09 +0000257/* Get a Py_ssize_t from a long int object.
258 Returns -1 and sets an error condition if overflow occurs. */
259
260Py_ssize_t
261_PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000262 register PyLongObject *v;
263 size_t x, prev;
264 Py_ssize_t i;
265 int sign;
266
267 if (vv == NULL || !PyLong_Check(vv)) {
268 PyErr_BadInternalCall();
269 return -1;
270 }
271 v = (PyLongObject *)vv;
272 i = v->ob_size;
273 sign = 1;
274 x = 0;
275 if (i < 0) {
276 sign = -1;
277 i = -(i);
278 }
279 while (--i >= 0) {
280 prev = x;
281 x = (x << SHIFT) + v->ob_digit[i];
282 if ((x >> SHIFT) != prev)
283 goto overflow;
284 }
Armin Rigo7ccbca92006-10-04 12:17:45 +0000285 /* Haven't lost any bits, but casting to a signed type requires
286 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000287 */
Armin Rigo7ccbca92006-10-04 12:17:45 +0000288 if (x <= (size_t)PY_SSIZE_T_MAX) {
289 return (Py_ssize_t)x * sign;
290 }
291 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
292 return PY_SSIZE_T_MIN;
293 }
294 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000295
296 overflow:
297 PyErr_SetString(PyExc_OverflowError,
298 "long int too large to convert to int");
Neal Norwitz8a87f5d2006-08-12 17:03:09 +0000299 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000300}
301
Guido van Rossumd8c80482002-08-13 00:24:58 +0000302/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000303 Returns -1 and sets an error condition if overflow occurs. */
304
305unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000306PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000307{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000308 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000309 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000310 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000311
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000312 if (vv == NULL || !PyLong_Check(vv)) {
Martin v. Löwis729d47d2004-09-20 06:17:46 +0000313 if (vv != NULL && PyInt_Check(vv)) {
314 long val = PyInt_AsLong(vv);
315 if (val < 0) {
316 PyErr_SetString(PyExc_OverflowError,
317 "can't convert negative value to unsigned long");
318 return (unsigned long) -1;
319 }
320 return val;
321 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000322 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000323 return (unsigned long) -1;
324 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000325 v = (PyLongObject *)vv;
Martin v. Löwis68192102007-07-21 06:55:02 +0000326 i = Py_Size(v);
Guido van Rossum53756b11997-01-03 17:14:46 +0000327 x = 0;
328 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000329 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum53756b11997-01-03 17:14:46 +0000330 "can't convert negative value to unsigned long");
331 return (unsigned long) -1;
332 }
333 while (--i >= 0) {
334 prev = x;
335 x = (x << SHIFT) + v->ob_digit[i];
336 if ((x >> SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000337 PyErr_SetString(PyExc_OverflowError,
Fred Drake661ea262000-10-24 19:57:45 +0000338 "long int too large to convert");
Guido van Rossum53756b11997-01-03 17:14:46 +0000339 return (unsigned long) -1;
340 }
341 }
342 return x;
343}
344
Thomas Hellera4ea6032003-04-17 18:55:45 +0000345/* Get a C unsigned long int from a long int object, ignoring the high bits.
346 Returns -1 and sets an error condition if an error occurs. */
347
348unsigned long
349PyLong_AsUnsignedLongMask(PyObject *vv)
350{
351 register PyLongObject *v;
352 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000353 Py_ssize_t i;
354 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000355
356 if (vv == NULL || !PyLong_Check(vv)) {
Martin v. Löwis729d47d2004-09-20 06:17:46 +0000357 if (vv != NULL && PyInt_Check(vv))
358 return PyInt_AsUnsignedLongMask(vv);
Thomas Hellera4ea6032003-04-17 18:55:45 +0000359 PyErr_BadInternalCall();
360 return (unsigned long) -1;
361 }
362 v = (PyLongObject *)vv;
363 i = v->ob_size;
364 sign = 1;
365 x = 0;
366 if (i < 0) {
367 sign = -1;
368 i = -i;
369 }
370 while (--i >= 0) {
371 x = (x << SHIFT) + v->ob_digit[i];
372 }
373 return x * sign;
374}
375
Tim Peters5b8132f2003-01-31 15:52:05 +0000376int
377_PyLong_Sign(PyObject *vv)
378{
379 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000380
381 assert(v != NULL);
382 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000383
Martin v. Löwis68192102007-07-21 06:55:02 +0000384 return Py_Size(v) == 0 ? 0 : (Py_Size(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000385}
386
Tim Petersbaefd9e2003-01-28 20:37:45 +0000387size_t
388_PyLong_NumBits(PyObject *vv)
389{
390 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000391 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000392 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000393
394 assert(v != NULL);
395 assert(PyLong_Check(v));
Martin v. Löwis68192102007-07-21 06:55:02 +0000396 ndigits = ABS(Py_Size(v));
Tim Petersbaefd9e2003-01-28 20:37:45 +0000397 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
398 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000399 digit msd = v->ob_digit[ndigits - 1];
400
Tim Peters5b8132f2003-01-31 15:52:05 +0000401 result = (ndigits - 1) * SHIFT;
Skip Montanaro429433b2006-04-18 00:35:43 +0000402 if (result / SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000403 goto Overflow;
404 do {
405 ++result;
406 if (result == 0)
407 goto Overflow;
408 msd >>= 1;
409 } while (msd);
410 }
411 return result;
412
413Overflow:
414 PyErr_SetString(PyExc_OverflowError, "long has too many bits "
415 "to express in a platform size_t");
416 return (size_t)-1;
417}
418
Tim Peters2a9b3672001-06-11 21:23:58 +0000419PyObject *
420_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
421 int little_endian, int is_signed)
422{
423 const unsigned char* pstartbyte;/* LSB of bytes */
424 int incr; /* direction to move pstartbyte */
425 const unsigned char* pendbyte; /* MSB of bytes */
426 size_t numsignificantbytes; /* number of bytes that matter */
427 size_t ndigits; /* number of Python long digits */
428 PyLongObject* v; /* result */
429 int idigit = 0; /* next free index in v->ob_digit */
430
431 if (n == 0)
432 return PyLong_FromLong(0L);
433
434 if (little_endian) {
435 pstartbyte = bytes;
436 pendbyte = bytes + n - 1;
437 incr = 1;
438 }
439 else {
440 pstartbyte = bytes + n - 1;
441 pendbyte = bytes;
442 incr = -1;
443 }
444
445 if (is_signed)
446 is_signed = *pendbyte >= 0x80;
447
448 /* Compute numsignificantbytes. This consists of finding the most
449 significant byte. Leading 0 bytes are insignficant if the number
450 is positive, and leading 0xff bytes if negative. */
451 {
452 size_t i;
453 const unsigned char* p = pendbyte;
454 const int pincr = -incr; /* search MSB to LSB */
455 const unsigned char insignficant = is_signed ? 0xff : 0x00;
456
457 for (i = 0; i < n; ++i, p += pincr) {
458 if (*p != insignficant)
459 break;
460 }
461 numsignificantbytes = n - i;
462 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
463 actually has 2 significant bytes. OTOH, 0xff0001 ==
464 -0x00ffff, so we wouldn't *need* to bump it there; but we
465 do for 0xffff = -0x0001. To be safe without bothering to
466 check every case, bump it regardless. */
467 if (is_signed && numsignificantbytes < n)
468 ++numsignificantbytes;
469 }
470
471 /* How many Python long digits do we need? We have
472 8*numsignificantbytes bits, and each Python long digit has SHIFT
473 bits, so it's the ceiling of the quotient. */
474 ndigits = (numsignificantbytes * 8 + SHIFT - 1) / SHIFT;
475 if (ndigits > (size_t)INT_MAX)
476 return PyErr_NoMemory();
477 v = _PyLong_New((int)ndigits);
478 if (v == NULL)
479 return NULL;
480
481 /* Copy the bits over. The tricky parts are computing 2's-comp on
482 the fly for signed numbers, and dealing with the mismatch between
483 8-bit bytes and (probably) 15-bit Python digits.*/
484 {
485 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000486 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000487 twodigits accum = 0; /* sliding register */
488 unsigned int accumbits = 0; /* number of bits in accum */
489 const unsigned char* p = pstartbyte;
490
491 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000492 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000493 /* Compute correction for 2's comp, if needed. */
494 if (is_signed) {
495 thisbyte = (0xff ^ thisbyte) + carry;
496 carry = thisbyte >> 8;
497 thisbyte &= 0xff;
498 }
499 /* Because we're going LSB to MSB, thisbyte is
500 more significant than what's already in accum,
501 so needs to be prepended to accum. */
502 accum |= thisbyte << accumbits;
503 accumbits += 8;
504 if (accumbits >= SHIFT) {
505 /* There's enough to fill a Python digit. */
506 assert(idigit < (int)ndigits);
507 v->ob_digit[idigit] = (digit)(accum & MASK);
508 ++idigit;
509 accum >>= SHIFT;
510 accumbits -= SHIFT;
511 assert(accumbits < SHIFT);
512 }
513 }
514 assert(accumbits < SHIFT);
515 if (accumbits) {
516 assert(idigit < (int)ndigits);
517 v->ob_digit[idigit] = (digit)accum;
518 ++idigit;
519 }
520 }
521
Martin v. Löwis68192102007-07-21 06:55:02 +0000522 Py_Size(v) = is_signed ? -idigit : idigit;
Tim Peters2a9b3672001-06-11 21:23:58 +0000523 return (PyObject *)long_normalize(v);
524}
525
526int
527_PyLong_AsByteArray(PyLongObject* v,
528 unsigned char* bytes, size_t n,
529 int little_endian, int is_signed)
530{
531 int i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000532 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000533 twodigits accum; /* sliding register */
534 unsigned int accumbits; /* # bits in accum */
535 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
536 twodigits carry; /* for computing 2's-comp */
537 size_t j; /* # bytes filled */
538 unsigned char* p; /* pointer to next byte in bytes */
539 int pincr; /* direction to move p */
540
541 assert(v != NULL && PyLong_Check(v));
542
Martin v. Löwis68192102007-07-21 06:55:02 +0000543 if (Py_Size(v) < 0) {
544 ndigits = -(Py_Size(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000545 if (!is_signed) {
546 PyErr_SetString(PyExc_TypeError,
547 "can't convert negative long to unsigned");
548 return -1;
549 }
550 do_twos_comp = 1;
551 }
552 else {
Martin v. Löwis68192102007-07-21 06:55:02 +0000553 ndigits = Py_Size(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000554 do_twos_comp = 0;
555 }
556
557 if (little_endian) {
558 p = bytes;
559 pincr = 1;
560 }
561 else {
562 p = bytes + n - 1;
563 pincr = -1;
564 }
565
Tim Peters898cf852001-06-13 20:50:08 +0000566 /* Copy over all the Python digits.
567 It's crucial that every Python digit except for the MSD contribute
568 exactly SHIFT bits to the total, so first assert that the long is
569 normalized. */
570 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000571 j = 0;
572 accum = 0;
573 accumbits = 0;
574 carry = do_twos_comp ? 1 : 0;
575 for (i = 0; i < ndigits; ++i) {
576 twodigits thisdigit = v->ob_digit[i];
577 if (do_twos_comp) {
578 thisdigit = (thisdigit ^ MASK) + carry;
579 carry = thisdigit >> SHIFT;
580 thisdigit &= MASK;
581 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000582 /* Because we're going LSB to MSB, thisdigit is more
583 significant than what's already in accum, so needs to be
584 prepended to accum. */
585 accum |= thisdigit << accumbits;
Tim Petersede05092001-06-14 08:53:38 +0000586 accumbits += SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000587
Tim Petersede05092001-06-14 08:53:38 +0000588 /* The most-significant digit may be (probably is) at least
589 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000590 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000591 /* Count # of sign bits -- they needn't be stored,
592 * although for signed conversion we need later to
593 * make sure at least one sign bit gets stored.
594 * First shift conceptual sign bit to real sign bit.
595 */
596 stwodigits s = (stwodigits)(thisdigit <<
597 (8*sizeof(stwodigits) - SHIFT));
Tim Peters7a3bfc32001-06-12 01:22:22 +0000598 unsigned int nsignbits = 0;
Tim Petersede05092001-06-14 08:53:38 +0000599 while ((s < 0) == do_twos_comp && nsignbits < SHIFT) {
Tim Peters7a3bfc32001-06-12 01:22:22 +0000600 ++nsignbits;
Tim Petersede05092001-06-14 08:53:38 +0000601 s <<= 1;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000602 }
Tim Petersede05092001-06-14 08:53:38 +0000603 accumbits -= nsignbits;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000604 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000605
Tim Peters2a9b3672001-06-11 21:23:58 +0000606 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000607 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000608 if (j >= n)
609 goto Overflow;
610 ++j;
611 *p = (unsigned char)(accum & 0xff);
612 p += pincr;
613 accumbits -= 8;
614 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000615 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000616 }
617
618 /* Store the straggler (if any). */
619 assert(accumbits < 8);
620 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000621 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000622 if (j >= n)
623 goto Overflow;
624 ++j;
625 if (do_twos_comp) {
626 /* Fill leading bits of the byte with sign bits
627 (appropriately pretending that the long had an
628 infinite supply of sign bits). */
629 accum |= (~(twodigits)0) << accumbits;
630 }
631 *p = (unsigned char)(accum & 0xff);
632 p += pincr;
633 }
Tim Peters05607ad2001-06-13 21:01:27 +0000634 else if (j == n && n > 0 && is_signed) {
635 /* The main loop filled the byte array exactly, so the code
636 just above didn't get to ensure there's a sign bit, and the
637 loop below wouldn't add one either. Make sure a sign bit
638 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000639 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000640 int sign_bit_set = msb >= 0x80;
641 assert(accumbits == 0);
642 if (sign_bit_set == do_twos_comp)
643 return 0;
644 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000645 goto Overflow;
646 }
Tim Peters05607ad2001-06-13 21:01:27 +0000647
648 /* Fill remaining bytes with copies of the sign bit. */
649 {
650 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
651 for ( ; j < n; ++j, p += pincr)
652 *p = signbyte;
653 }
654
Tim Peters2a9b3672001-06-11 21:23:58 +0000655 return 0;
656
657Overflow:
658 PyErr_SetString(PyExc_OverflowError, "long too big to convert");
659 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000660
Tim Peters2a9b3672001-06-11 21:23:58 +0000661}
662
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000663double
664_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
665{
666/* NBITS_WANTED should be > the number of bits in a double's precision,
667 but small enough so that 2**NBITS_WANTED is within the normal double
668 range. nbitsneeded is set to 1 less than that because the most-significant
669 Python digit contains at least 1 significant bit, but we don't want to
670 bother counting them (catering to the worst case cheaply).
671
672 57 is one more than VAX-D double precision; I (Tim) don't know of a double
673 format with more precision than that; it's 1 larger so that we add in at
674 least one round bit to stand in for the ignored least-significant bits.
675*/
676#define NBITS_WANTED 57
677 PyLongObject *v;
678 double x;
679 const double multiplier = (double)(1L << SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000680 Py_ssize_t i;
681 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000682 int nbitsneeded;
683
684 if (vv == NULL || !PyLong_Check(vv)) {
685 PyErr_BadInternalCall();
686 return -1;
687 }
688 v = (PyLongObject *)vv;
Martin v. Löwis68192102007-07-21 06:55:02 +0000689 i = Py_Size(v);
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000690 sign = 1;
691 if (i < 0) {
692 sign = -1;
693 i = -(i);
694 }
695 else if (i == 0) {
696 *exponent = 0;
697 return 0.0;
698 }
699 --i;
700 x = (double)v->ob_digit[i];
701 nbitsneeded = NBITS_WANTED - 1;
702 /* Invariant: i Python digits remain unaccounted for. */
703 while (i > 0 && nbitsneeded > 0) {
704 --i;
705 x = x * multiplier + (double)v->ob_digit[i];
706 nbitsneeded -= SHIFT;
707 }
708 /* There are i digits we didn't shift in. Pretending they're all
709 zeroes, the true value is x * 2**(i*SHIFT). */
710 *exponent = i;
711 assert(x > 0.0);
712 return x * sign;
713#undef NBITS_WANTED
714}
715
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000716/* Get a C double from a long int object. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000717
718double
Tim Peters9f688bf2000-07-07 15:53:28 +0000719PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000720{
Thomas Wouters553489a2006-02-01 21:32:04 +0000721 int e = -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000722 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000723
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000724 if (vv == NULL || !PyLong_Check(vv)) {
725 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000726 return -1;
727 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000728 x = _PyLong_AsScaledDouble(vv, &e);
729 if (x == -1.0 && PyErr_Occurred())
730 return -1.0;
Thomas Wouters553489a2006-02-01 21:32:04 +0000731 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
732 set correctly after a successful _PyLong_AsScaledDouble() call */
733 assert(e >= 0);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000734 if (e > INT_MAX / SHIFT)
735 goto overflow;
736 errno = 0;
737 x = ldexp(x, e * SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +0000738 if (Py_OVERFLOWED(x))
Tim Peters9fffa3e2001-09-04 05:14:19 +0000739 goto overflow;
740 return x;
741
742overflow:
743 PyErr_SetString(PyExc_OverflowError,
744 "long int too large to convert to float");
745 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000746}
747
Guido van Rossum78694d91998-09-18 14:14:13 +0000748/* Create a new long (or int) object from a C pointer */
749
750PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000751PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000752{
Tim Peters70128a12001-06-16 08:48:40 +0000753#if SIZEOF_VOID_P <= SIZEOF_LONG
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000754 if ((long)p < 0)
755 return PyLong_FromUnsignedLong((unsigned long)p);
Guido van Rossum78694d91998-09-18 14:14:13 +0000756 return PyInt_FromLong((long)p);
757#else
Guido van Rossum78694d91998-09-18 14:14:13 +0000758
Tim Peters70128a12001-06-16 08:48:40 +0000759#ifndef HAVE_LONG_LONG
760# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
761#endif
762#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000763# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000764#endif
765 /* optimize null pointers */
766 if (p == NULL)
767 return PyInt_FromLong(0);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000768 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)p);
Tim Peters70128a12001-06-16 08:48:40 +0000769
770#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000771}
772
773/* Get a C pointer from a long object (or an int object in some cases) */
774
775void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000776PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000777{
778 /* This function will allow int or long objects. If vv is neither,
779 then the PyLong_AsLong*() functions will raise the exception:
780 PyExc_SystemError, "bad argument to internal function"
781 */
Tim Peters70128a12001-06-16 08:48:40 +0000782#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +0000783 long x;
784
Tim Peters70128a12001-06-16 08:48:40 +0000785 if (PyInt_Check(vv))
Guido van Rossum78694d91998-09-18 14:14:13 +0000786 x = PyInt_AS_LONG(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000787 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000788 x = PyLong_AsLong(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000789 else
790 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000791#else
Tim Peters70128a12001-06-16 08:48:40 +0000792
793#ifndef HAVE_LONG_LONG
794# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
795#endif
796#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000797# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000798#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000799 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000800
Tim Peters70128a12001-06-16 08:48:40 +0000801 if (PyInt_Check(vv))
Guido van Rossum78694d91998-09-18 14:14:13 +0000802 x = PyInt_AS_LONG(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000803 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000804 x = PyLong_AsLongLong(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000805 else
806 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000807
808#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000809
810 if (x == -1 && PyErr_Occurred())
811 return NULL;
812 return (void *)x;
813}
814
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000815#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000816
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000817/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000818 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000819 */
820
Tim Peterscf37dfc2001-06-14 18:42:50 +0000821#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +0000822
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000823/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000824
825PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000826PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000827{
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000828 PyLongObject *v;
829 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
830 int ndigits = 0;
831 int negative = 0;
832
833 if (ival < 0) {
834 ival = -ival;
835 negative = 1;
836 }
837
838 /* Count the number of Python digits.
839 We used to pick 5 ("big enough for anything"), but that's a
840 waste of time and space given that 5*15 = 75 bits are rarely
841 needed. */
842 t = (unsigned PY_LONG_LONG)ival;
843 while (t) {
844 ++ndigits;
845 t >>= SHIFT;
846 }
847 v = _PyLong_New(ndigits);
848 if (v != NULL) {
849 digit *p = v->ob_digit;
Martin v. Löwis68192102007-07-21 06:55:02 +0000850 Py_Size(v) = negative ? -ndigits : ndigits;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000851 t = (unsigned PY_LONG_LONG)ival;
852 while (t) {
853 *p++ = (digit)(t & MASK);
854 t >>= SHIFT;
855 }
856 }
857 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000858}
859
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000860/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +0000861
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000862PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000863PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000864{
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000865 PyLongObject *v;
866 unsigned PY_LONG_LONG t;
867 int ndigits = 0;
868
869 /* Count the number of Python digits. */
870 t = (unsigned PY_LONG_LONG)ival;
871 while (t) {
872 ++ndigits;
873 t >>= SHIFT;
874 }
875 v = _PyLong_New(ndigits);
876 if (v != NULL) {
877 digit *p = v->ob_digit;
Martin v. Löwis68192102007-07-21 06:55:02 +0000878 Py_Size(v) = ndigits;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000879 while (ival) {
880 *p++ = (digit)(ival & MASK);
881 ival >>= SHIFT;
882 }
883 }
884 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000885}
886
Martin v. Löwis18e16552006-02-15 17:27:45 +0000887/* Create a new long int object from a C Py_ssize_t. */
888
889PyObject *
890_PyLong_FromSsize_t(Py_ssize_t ival)
891{
892 Py_ssize_t bytes = ival;
893 int one = 1;
894 return _PyLong_FromByteArray(
895 (unsigned char *)&bytes,
Kristján Valur Jónssonf0303942007-05-03 20:27:03 +0000896 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000897}
898
899/* Create a new long int object from a C size_t. */
900
901PyObject *
902_PyLong_FromSize_t(size_t ival)
903{
904 size_t bytes = ival;
905 int one = 1;
906 return _PyLong_FromByteArray(
907 (unsigned char *)&bytes,
908 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
909}
910
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000911/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000912 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000913
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000914PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000915PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000916{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000917 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +0000918 int one = 1;
919 int res;
920
Tim Petersd38b1c72001-09-30 05:09:37 +0000921 if (vv == NULL) {
922 PyErr_BadInternalCall();
923 return -1;
924 }
925 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +0000926 PyNumberMethods *nb;
927 PyObject *io;
Tim Petersd38b1c72001-09-30 05:09:37 +0000928 if (PyInt_Check(vv))
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000929 return (PY_LONG_LONG)PyInt_AsLong(vv);
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +0000930 if ((nb = vv->ob_type->tp_as_number) == NULL ||
931 nb->nb_int == NULL) {
932 PyErr_SetString(PyExc_TypeError, "an integer is required");
933 return -1;
934 }
935 io = (*nb->nb_int) (vv);
936 if (io == NULL)
937 return -1;
938 if (PyInt_Check(io)) {
939 bytes = PyInt_AsLong(io);
940 Py_DECREF(io);
941 return bytes;
942 }
943 if (PyLong_Check(io)) {
944 bytes = PyLong_AsLongLong(io);
945 Py_DECREF(io);
946 return bytes;
947 }
948 Py_DECREF(io);
949 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000950 return -1;
951 }
952
Tim Petersd1a7da62001-06-13 00:35:57 +0000953 res = _PyLong_AsByteArray(
954 (PyLongObject *)vv, (unsigned char *)&bytes,
955 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000956
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000957 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000958 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000959 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000960 else
961 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000962}
963
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000964/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000965 Return -1 and set an error if overflow occurs. */
966
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000967unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000968PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000969{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000970 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +0000971 int one = 1;
972 int res;
973
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000974 if (vv == NULL || !PyLong_Check(vv)) {
975 PyErr_BadInternalCall();
Skip Montanaro429433b2006-04-18 00:35:43 +0000976 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000977 }
978
Tim Petersd1a7da62001-06-13 00:35:57 +0000979 res = _PyLong_AsByteArray(
980 (PyLongObject *)vv, (unsigned char *)&bytes,
981 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000982
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000983 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000984 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000985 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000986 else
987 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000988}
Tim Petersd1a7da62001-06-13 00:35:57 +0000989
Thomas Hellera4ea6032003-04-17 18:55:45 +0000990/* Get a C unsigned long int from a long int object, ignoring the high bits.
991 Returns -1 and sets an error condition if an error occurs. */
992
993unsigned PY_LONG_LONG
994PyLong_AsUnsignedLongLongMask(PyObject *vv)
995{
996 register PyLongObject *v;
997 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000998 Py_ssize_t i;
999 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001000
1001 if (vv == NULL || !PyLong_Check(vv)) {
1002 PyErr_BadInternalCall();
1003 return (unsigned long) -1;
1004 }
1005 v = (PyLongObject *)vv;
1006 i = v->ob_size;
1007 sign = 1;
1008 x = 0;
1009 if (i < 0) {
1010 sign = -1;
1011 i = -i;
1012 }
1013 while (--i >= 0) {
1014 x = (x << SHIFT) + v->ob_digit[i];
1015 }
1016 return x * sign;
1017}
Tim Petersd1a7da62001-06-13 00:35:57 +00001018#undef IS_LITTLE_ENDIAN
1019
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001020#endif /* HAVE_LONG_LONG */
1021
Neil Schemenauerba872e22001-01-04 01:46:03 +00001022
1023static int
1024convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00001025 if (PyLong_Check(v)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001026 *a = (PyLongObject *) v;
1027 Py_INCREF(v);
1028 }
1029 else if (PyInt_Check(v)) {
1030 *a = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(v));
1031 }
1032 else {
1033 return 0;
1034 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001035 if (PyLong_Check(w)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001036 *b = (PyLongObject *) w;
1037 Py_INCREF(w);
1038 }
1039 else if (PyInt_Check(w)) {
1040 *b = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(w));
1041 }
1042 else {
1043 Py_DECREF(*a);
1044 return 0;
1045 }
1046 return 1;
1047}
1048
1049#define CONVERT_BINOP(v, w, a, b) \
1050 if (!convert_binop(v, w, a, b)) { \
1051 Py_INCREF(Py_NotImplemented); \
1052 return Py_NotImplemented; \
1053 }
1054
Tim Peters877a2122002-08-12 05:09:36 +00001055/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1056 * is modified in place, by adding y to it. Carries are propagated as far as
1057 * x[m-1], and the remaining carry (0 or 1) is returned.
1058 */
1059static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001060v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001061{
1062 int i;
1063 digit carry = 0;
1064
1065 assert(m >= n);
1066 for (i = 0; i < n; ++i) {
1067 carry += x[i] + y[i];
1068 x[i] = carry & MASK;
1069 carry >>= SHIFT;
1070 assert((carry & 1) == carry);
1071 }
1072 for (; carry && i < m; ++i) {
1073 carry += x[i];
1074 x[i] = carry & MASK;
1075 carry >>= SHIFT;
1076 assert((carry & 1) == carry);
1077 }
1078 return carry;
1079}
1080
1081/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1082 * is modified in place, by subtracting y from it. Borrows are propagated as
1083 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1084 */
1085static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001086v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001087{
1088 int i;
1089 digit borrow = 0;
1090
1091 assert(m >= n);
1092 for (i = 0; i < n; ++i) {
1093 borrow = x[i] - y[i] - borrow;
1094 x[i] = borrow & MASK;
1095 borrow >>= SHIFT;
1096 borrow &= 1; /* keep only 1 sign bit */
1097 }
1098 for (; borrow && i < m; ++i) {
1099 borrow = x[i] - borrow;
1100 x[i] = borrow & MASK;
1101 borrow >>= SHIFT;
1102 borrow &= 1;
1103 }
1104 return borrow;
1105}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001106
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001107/* Multiply by a single digit, ignoring the sign. */
1108
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001109static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001110mul1(PyLongObject *a, wdigit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001111{
1112 return muladd1(a, n, (digit)0);
1113}
1114
1115/* Multiply by a single digit and add a single digit, ignoring the sign. */
1116
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001117static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001118muladd1(PyLongObject *a, wdigit n, wdigit extra)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001119{
Martin v. Löwis68192102007-07-21 06:55:02 +00001120 Py_ssize_t size_a = ABS(Py_Size(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001121 PyLongObject *z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001122 twodigits carry = extra;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001123 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001124
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001125 if (z == NULL)
1126 return NULL;
1127 for (i = 0; i < size_a; ++i) {
1128 carry += (twodigits)a->ob_digit[i] * n;
Guido van Rossum2095d241997-04-09 19:41:24 +00001129 z->ob_digit[i] = (digit) (carry & MASK);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001130 carry >>= SHIFT;
1131 }
Guido van Rossum2095d241997-04-09 19:41:24 +00001132 z->ob_digit[i] = (digit) carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001133 return long_normalize(z);
1134}
1135
Tim Peters212e6142001-07-14 12:23:19 +00001136/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1137 in pout, and returning the remainder. pin and pout point at the LSD.
1138 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
1139 long_format, but that should be done with great care since longs are
1140 immutable. */
1141
1142static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001143inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001144{
1145 twodigits rem = 0;
1146
1147 assert(n > 0 && n <= MASK);
1148 pin += size;
1149 pout += size;
1150 while (--size >= 0) {
1151 digit hi;
1152 rem = (rem << SHIFT) + *--pin;
1153 *--pout = hi = (digit)(rem / n);
1154 rem -= hi * n;
1155 }
1156 return (digit)rem;
1157}
1158
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001159/* Divide a long integer by a digit, returning both the quotient
1160 (as function result) and the remainder (through *prem).
1161 The sign of a is ignored; n should not be zero. */
1162
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001163static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001164divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001165{
Martin v. Löwis68192102007-07-21 06:55:02 +00001166 const Py_ssize_t size = ABS(Py_Size(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001167 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001168
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001169 assert(n > 0 && n <= MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001170 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001171 if (z == NULL)
1172 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001173 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001174 return long_normalize(z);
1175}
1176
1177/* Convert a long int object to a string, using a given conversion base.
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001178 Return a string object.
Fred Drake121ee271999-12-23 15:41:28 +00001179 If base is 8 or 16, add the proper prefix '0' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001180
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001181static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001182long_format(PyObject *aa, int base, int addL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001183{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001184 register PyLongObject *a = (PyLongObject *)aa;
1185 PyStringObject *str;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001186 Py_ssize_t i, j, sz;
Neal Norwitzc09efa82006-07-23 07:53:14 +00001187 Py_ssize_t size_a;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001188 char *p;
1189 int bits;
1190 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001191
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001192 if (a == NULL || !PyLong_Check(a)) {
1193 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001194 return NULL;
1195 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001196 assert(base >= 2 && base <= 36);
Martin v. Löwis68192102007-07-21 06:55:02 +00001197 size_a = ABS(Py_Size(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001198
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001199 /* Compute a rough upper bound for the length of the string */
1200 i = base;
1201 bits = 0;
1202 while (i > 1) {
1203 ++bits;
1204 i >>= 1;
1205 }
Armin Rigo7ccbca92006-10-04 12:17:45 +00001206 i = 5 + (addL ? 1 : 0);
1207 j = size_a*SHIFT + bits-1;
1208 sz = i + j / bits;
1209 if (j / SHIFT < size_a || sz < i) {
1210 PyErr_SetString(PyExc_OverflowError,
1211 "long is too large to format");
1212 return NULL;
1213 }
1214 str = (PyStringObject *) PyString_FromStringAndSize((char *)0, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001215 if (str == NULL)
1216 return NULL;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001217 p = PyString_AS_STRING(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001218 *p = '\0';
Fred Drake121ee271999-12-23 15:41:28 +00001219 if (addL)
1220 *--p = 'L';
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001221 if (a->ob_size < 0)
1222 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001223
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001224 if (a->ob_size == 0) {
1225 *--p = '0';
1226 }
1227 else if ((base & (base - 1)) == 0) {
1228 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001229 twodigits accum = 0;
1230 int accumbits = 0; /* # of bits in accum */
1231 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001232 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001233 while ((i >>= 1) > 1)
1234 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001235
1236 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001237 accum |= (twodigits)a->ob_digit[i] << accumbits;
Tim Peters586b2e32001-07-15 09:11:14 +00001238 accumbits += SHIFT;
1239 assert(accumbits >= basebits);
1240 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001241 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001242 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001243 assert(p > PyString_AS_STRING(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001244 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001245 accumbits -= basebits;
1246 accum >>= basebits;
1247 } while (i < size_a-1 ? accumbits >= basebits :
1248 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001249 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001250 }
1251 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001252 /* Not 0, and base not a power of 2. Divide repeatedly by
1253 base, but for speed use the highest power of base that
1254 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001255 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001256 digit *pin = a->ob_digit;
1257 PyLongObject *scratch;
1258 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001259 digit powbase = base; /* powbase == base ** power */
1260 int power = 1;
1261 for (;;) {
1262 unsigned long newpow = powbase * (unsigned long)base;
1263 if (newpow >> SHIFT) /* doesn't fit in a digit */
1264 break;
1265 powbase = (digit)newpow;
1266 ++power;
1267 }
Tim Peters212e6142001-07-14 12:23:19 +00001268
1269 /* Get a scratch area for repeated division. */
1270 scratch = _PyLong_New(size);
1271 if (scratch == NULL) {
1272 Py_DECREF(str);
1273 return NULL;
1274 }
1275
1276 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001277 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001278 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001279 digit rem = inplace_divrem1(scratch->ob_digit,
1280 pin, size, powbase);
1281 pin = scratch->ob_digit; /* no need to use a again */
1282 if (pin[size - 1] == 0)
1283 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001284 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001285 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001286 Py_DECREF(str);
1287 return NULL;
1288 })
Tim Peters212e6142001-07-14 12:23:19 +00001289
1290 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001291 assert(ntostore > 0);
1292 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001293 digit nextrem = (digit)(rem / base);
1294 char c = (char)(rem - nextrem * base);
1295 assert(p > PyString_AS_STRING(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001296 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001297 *--p = c;
1298 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001299 --ntostore;
1300 /* Termination is a bit delicate: must not
1301 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001302 remaining quotient and rem are both 0. */
1303 } while (ntostore && (size || rem));
1304 } while (size != 0);
1305 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001306 }
1307
Guido van Rossum2c475421992-08-14 15:13:07 +00001308 if (base == 8) {
1309 if (size_a != 0)
1310 *--p = '0';
1311 }
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001312 else if (base == 16) {
1313 *--p = 'x';
1314 *--p = '0';
1315 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001316 else if (base != 10) {
1317 *--p = '#';
1318 *--p = '0' + base%10;
1319 if (base > 10)
1320 *--p = '0' + base/10;
1321 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001322 if (sign)
1323 *--p = sign;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001324 if (p != PyString_AS_STRING(str)) {
1325 char *q = PyString_AS_STRING(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001326 assert(p > q);
1327 do {
1328 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001329 q--;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001330 _PyString_Resize((PyObject **)&str,
Armin Rigo7ccbca92006-10-04 12:17:45 +00001331 (Py_ssize_t) (q - PyString_AS_STRING(str)));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001332 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001333 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001334}
1335
Tim Petersda53afa2006-05-25 17:34:03 +00001336/* Table of digit values for 8-bit string -> integer conversion.
1337 * '0' maps to 0, ..., '9' maps to 9.
1338 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1339 * All other indices map to 37.
1340 * Note that when converting a base B string, a char c is a legitimate
1341 * base B digit iff _PyLong_DigitValue[Py_CHARMASK(c)] < B.
1342 */
1343int _PyLong_DigitValue[256] = {
Tim Peters696cf432006-05-24 21:10:40 +00001344 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1345 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1346 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1347 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1348 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1349 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1350 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1351 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1352 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1353 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1354 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1355 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1356 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1357 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1358 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1359 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Tim Peters696cf432006-05-24 21:10:40 +00001360};
1361
1362/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001363 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1364 * non-digit (which may be *str!). A normalized long is returned.
1365 * The point to this routine is that it takes time linear in the number of
1366 * string characters.
1367 */
1368static PyLongObject *
1369long_from_binary_base(char **str, int base)
1370{
1371 char *p = *str;
1372 char *start = p;
1373 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001374 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001375 PyLongObject *z;
1376 twodigits accum;
1377 int bits_in_accum;
1378 digit *pdigit;
1379
1380 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1381 n = base;
1382 for (bits_per_char = -1; n; ++bits_per_char)
1383 n >>= 1;
1384 /* n <- total # of bits needed, while setting p to end-of-string */
1385 n = 0;
Tim Petersda53afa2006-05-25 17:34:03 +00001386 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001387 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001388 *str = p;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001389 /* n <- # of Python digits needed, = ceiling(n/SHIFT). */
1390 n = (p - start) * bits_per_char + SHIFT - 1;
1391 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001392 PyErr_SetString(PyExc_ValueError,
1393 "long string too large to convert");
1394 return NULL;
1395 }
Armin Rigo7ccbca92006-10-04 12:17:45 +00001396 n = n / SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001397 z = _PyLong_New(n);
1398 if (z == NULL)
1399 return NULL;
1400 /* Read string from right, and fill in long from left; i.e.,
1401 * from least to most significant in both.
1402 */
1403 accum = 0;
1404 bits_in_accum = 0;
1405 pdigit = z->ob_digit;
1406 while (--p >= start) {
Tim Petersda53afa2006-05-25 17:34:03 +00001407 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001408 assert(k >= 0 && k < base);
1409 accum |= (twodigits)(k << bits_in_accum);
Tim Petersbf2674b2003-02-02 07:51:32 +00001410 bits_in_accum += bits_per_char;
1411 if (bits_in_accum >= SHIFT) {
1412 *pdigit++ = (digit)(accum & MASK);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001413 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001414 accum >>= SHIFT;
1415 bits_in_accum -= SHIFT;
1416 assert(bits_in_accum < SHIFT);
1417 }
1418 }
1419 if (bits_in_accum) {
1420 assert(bits_in_accum <= SHIFT);
1421 *pdigit++ = (digit)accum;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001422 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001423 }
1424 while (pdigit - z->ob_digit < n)
1425 *pdigit++ = 0;
1426 return long_normalize(z);
1427}
1428
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001429PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001430PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001431{
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001432 int sign = 1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001433 char *start, *orig_str = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001434 PyLongObject *z;
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001435 PyObject *strobj, *strrepr;
1436 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001437
Guido van Rossum472c04f1996-12-05 21:57:21 +00001438 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001439 PyErr_SetString(PyExc_ValueError,
Fred Drake661ea262000-10-24 19:57:45 +00001440 "long() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001441 return NULL;
1442 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001443 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001444 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001445 if (*str == '+')
1446 ++str;
1447 else if (*str == '-') {
1448 ++str;
1449 sign = -1;
1450 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001451 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001452 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001453 if (base == 0) {
1454 if (str[0] != '0')
1455 base = 10;
1456 else if (str[1] == 'x' || str[1] == 'X')
1457 base = 16;
1458 else
1459 base = 8;
1460 }
1461 if (base == 16 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
1462 str += 2;
Tim Peters696cf432006-05-24 21:10:40 +00001463
Guido van Rossume6762971998-06-22 03:54:46 +00001464 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001465 if ((base & (base - 1)) == 0)
1466 z = long_from_binary_base(&str, base);
1467 else {
Tim Peters696cf432006-05-24 21:10:40 +00001468/***
1469Binary bases can be converted in time linear in the number of digits, because
1470Python's representation base is binary. Other bases (including decimal!) use
1471the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001472
Tim Peters696cf432006-05-24 21:10:40 +00001473First some math: the largest integer that can be expressed in N base-B digits
1474is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1475case number of Python digits needed to hold it is the smallest integer n s.t.
1476
1477 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1478 BASE**n >= B**N [taking logs to base BASE]
1479 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1480
1481The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1482this quickly. A Python long with that much space is reserved near the start,
1483and the result is computed into it.
1484
1485The input string is actually treated as being in base base**i (i.e., i digits
1486are processed at a time), where two more static arrays hold:
1487
1488 convwidth_base[base] = the largest integer i such that base**i <= BASE
1489 convmultmax_base[base] = base ** convwidth_base[base]
1490
1491The first of these is the largest i such that i consecutive input digits
1492must fit in a single Python digit. The second is effectively the input
1493base we're really using.
1494
1495Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1496convmultmax_base[base], the result is "simply"
1497
1498 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1499
1500where B = convmultmax_base[base].
Tim Peters9faa3ed2006-05-30 15:53:34 +00001501
1502Error analysis: as above, the number of Python digits `n` needed is worst-
1503case
1504
1505 n >= N * log(B)/log(BASE)
1506
1507where `N` is the number of input digits in base `B`. This is computed via
1508
1509 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1510
1511below. Two numeric concerns are how much space this can waste, and whether
1512the computed result can be too small. To be concrete, assume BASE = 2**15,
1513which is the default (and it's unlikely anyone changes that).
1514
1515Waste isn't a problem: provided the first input digit isn't 0, the difference
1516between the worst-case input with N digits and the smallest input with N
1517digits is about a factor of B, but B is small compared to BASE so at most
1518one allocated Python digit can remain unused on that count. If
1519N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1520and adding 1 returns a result 1 larger than necessary. However, that can't
1521happen: whenever B is a power of 2, long_from_binary_base() is called
1522instead, and it's impossible for B**i to be an integer power of 2**15 when
1523B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1524an exact integer when B is not a power of 2, since B**i has a prime factor
1525other than 2 in that case, but (2**15)**j's only prime factor is 2).
1526
1527The computed result can be too small if the true value of N*log(B)/log(BASE)
1528is a little bit larger than an exact integer, but due to roundoff errors (in
1529computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1530yields a numeric result a little less than that integer. Unfortunately, "how
1531close can a transcendental function get to an integer over some range?"
1532questions are generally theoretically intractable. Computer analysis via
1533continued fractions is practical: expand log(B)/log(BASE) via continued
1534fractions, giving a sequence i/j of "the best" rational approximations. Then
1535j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1536we can get very close to being in trouble, but very rarely. For example,
153776573 is a denominator in one of the continued-fraction approximations to
1538log(10)/log(2**15), and indeed:
1539
1540 >>> log(10)/log(2**15)*76573
1541 16958.000000654003
1542
1543is very close to an integer. If we were working with IEEE single-precision,
1544rounding errors could kill us. Finding worst cases in IEEE double-precision
1545requires better-than-double-precision log() functions, and Tim didn't bother.
1546Instead the code checks to see whether the allocated space is enough as each
1547new Python digit is added, and copies the whole thing to a larger long if not.
1548This should happen extremely rarely, and in fact I don't have a test case
1549that triggers it(!). Instead the code was tested by artificially allocating
1550just 1 digit at the start, so that the copying code was exercised for every
1551digit beyond the first.
Tim Peters696cf432006-05-24 21:10:40 +00001552***/
1553 register twodigits c; /* current input character */
1554 Py_ssize_t size_z;
1555 int i;
1556 int convwidth;
1557 twodigits convmultmax, convmult;
1558 digit *pz, *pzstop;
1559 char* scan;
1560
1561 static double log_base_BASE[37] = {0.0e0,};
1562 static int convwidth_base[37] = {0,};
1563 static twodigits convmultmax_base[37] = {0,};
1564
1565 if (log_base_BASE[base] == 0.0) {
1566 twodigits convmax = base;
1567 int i = 1;
1568
1569 log_base_BASE[base] = log((double)base) /
1570 log((double)BASE);
1571 for (;;) {
1572 twodigits next = convmax * base;
1573 if (next > BASE)
1574 break;
1575 convmax = next;
1576 ++i;
1577 }
1578 convmultmax_base[base] = convmax;
1579 assert(i > 0);
1580 convwidth_base[base] = i;
1581 }
1582
1583 /* Find length of the string of numeric characters. */
1584 scan = str;
Tim Petersda53afa2006-05-25 17:34:03 +00001585 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
Tim Peters696cf432006-05-24 21:10:40 +00001586 ++scan;
1587
1588 /* Create a long object that can contain the largest possible
1589 * integer with this base and length. Note that there's no
1590 * need to initialize z->ob_digit -- no slot is read up before
1591 * being stored into.
1592 */
1593 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
Tim Peters9faa3ed2006-05-30 15:53:34 +00001594 /* Uncomment next line to test exceedingly rare copy code */
1595 /* size_z = 1; */
Tim Peters696cf432006-05-24 21:10:40 +00001596 assert(size_z > 0);
1597 z = _PyLong_New(size_z);
1598 if (z == NULL)
1599 return NULL;
Martin v. Löwis68192102007-07-21 06:55:02 +00001600 Py_Size(z) = 0;
Tim Peters696cf432006-05-24 21:10:40 +00001601
1602 /* `convwidth` consecutive input digits are treated as a single
1603 * digit in base `convmultmax`.
1604 */
1605 convwidth = convwidth_base[base];
1606 convmultmax = convmultmax_base[base];
1607
1608 /* Work ;-) */
1609 while (str < scan) {
1610 /* grab up to convwidth digits from the input string */
Tim Petersda53afa2006-05-25 17:34:03 +00001611 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Tim Peters696cf432006-05-24 21:10:40 +00001612 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1613 c = (twodigits)(c * base +
Tim Petersda53afa2006-05-25 17:34:03 +00001614 _PyLong_DigitValue[Py_CHARMASK(*str)]);
Tim Peters696cf432006-05-24 21:10:40 +00001615 assert(c < BASE);
1616 }
1617
1618 convmult = convmultmax;
1619 /* Calculate the shift only if we couldn't get
1620 * convwidth digits.
1621 */
1622 if (i != convwidth) {
1623 convmult = base;
1624 for ( ; i > 1; --i)
1625 convmult *= base;
1626 }
1627
1628 /* Multiply z by convmult, and add c. */
1629 pz = z->ob_digit;
Martin v. Löwis68192102007-07-21 06:55:02 +00001630 pzstop = pz + Py_Size(z);
Tim Peters696cf432006-05-24 21:10:40 +00001631 for (; pz < pzstop; ++pz) {
1632 c += (twodigits)*pz * convmult;
1633 *pz = (digit)(c & MASK);
1634 c >>= SHIFT;
1635 }
1636 /* carry off the current end? */
1637 if (c) {
1638 assert(c < BASE);
Martin v. Löwis68192102007-07-21 06:55:02 +00001639 if (Py_Size(z) < size_z) {
Tim Peters9faa3ed2006-05-30 15:53:34 +00001640 *pz = (digit)c;
Martin v. Löwis68192102007-07-21 06:55:02 +00001641 ++Py_Size(z);
Tim Peters9faa3ed2006-05-30 15:53:34 +00001642 }
1643 else {
1644 PyLongObject *tmp;
1645 /* Extremely rare. Get more space. */
Martin v. Löwis68192102007-07-21 06:55:02 +00001646 assert(Py_Size(z) == size_z);
Tim Peters9faa3ed2006-05-30 15:53:34 +00001647 tmp = _PyLong_New(size_z + 1);
1648 if (tmp == NULL) {
1649 Py_DECREF(z);
1650 return NULL;
1651 }
1652 memcpy(tmp->ob_digit,
1653 z->ob_digit,
1654 sizeof(digit) * size_z);
1655 Py_DECREF(z);
1656 z = tmp;
1657 z->ob_digit[size_z] = (digit)c;
1658 ++size_z;
1659 }
Tim Peters696cf432006-05-24 21:10:40 +00001660 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001661 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001662 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001663 if (z == NULL)
1664 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001665 if (str == start)
1666 goto onError;
Tim Peters696cf432006-05-24 21:10:40 +00001667 if (sign < 0)
Martin v. Löwis68192102007-07-21 06:55:02 +00001668 Py_Size(z) = -(Py_Size(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00001669 if (*str == 'L' || *str == 'l')
1670 str++;
1671 while (*str && isspace(Py_CHARMASK(*str)))
1672 str++;
1673 if (*str != '\0')
1674 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001675 if (pend)
1676 *pend = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001677 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001678
1679 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00001680 Py_XDECREF(z);
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001681 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
1682 strobj = PyString_FromStringAndSize(orig_str, slen);
1683 if (strobj == NULL)
1684 return NULL;
1685 strrepr = PyObject_Repr(strobj);
1686 Py_DECREF(strobj);
1687 if (strrepr == NULL)
1688 return NULL;
1689 PyErr_Format(PyExc_ValueError,
1690 "invalid literal for long() with base %d: %s",
1691 base, PyString_AS_STRING(strrepr));
1692 Py_DECREF(strrepr);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001693 return NULL;
1694}
1695
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001696#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +00001697PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001698PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001699{
Walter Dörwald07e14762002-11-06 16:15:14 +00001700 PyObject *result;
Anthony Baxter377be112006-04-11 06:54:30 +00001701 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001702
Walter Dörwald07e14762002-11-06 16:15:14 +00001703 if (buffer == NULL)
1704 return NULL;
1705
1706 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1707 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001708 return NULL;
1709 }
Walter Dörwald07e14762002-11-06 16:15:14 +00001710 result = PyLong_FromString(buffer, NULL, base);
1711 PyMem_FREE(buffer);
1712 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001713}
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001714#endif
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001715
Tim Peters9f688bf2000-07-07 15:53:28 +00001716/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001717static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00001718 (PyLongObject *, PyLongObject *, PyLongObject **);
1719static PyObject *long_pos(PyLongObject *);
1720static int long_divrem(PyLongObject *, PyLongObject *,
1721 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001722
1723/* Long division with remainder, top-level routine */
1724
Guido van Rossume32e0141992-01-19 16:31:05 +00001725static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001726long_divrem(PyLongObject *a, PyLongObject *b,
1727 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001728{
Martin v. Löwis68192102007-07-21 06:55:02 +00001729 Py_ssize_t size_a = ABS(Py_Size(a)), size_b = ABS(Py_Size(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001730 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001731
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001732 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001733 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +00001734 "long division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00001735 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001736 }
1737 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00001738 (size_a == size_b &&
1739 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001740 /* |a| < |b|. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001741 *pdiv = _PyLong_New(0);
Georg Brandlc02e1312007-04-11 17:16:24 +00001742 if (*pdiv == NULL)
1743 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001744 Py_INCREF(a);
1745 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00001746 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001747 }
1748 if (size_b == 1) {
1749 digit rem = 0;
1750 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001751 if (z == NULL)
1752 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001753 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Georg Brandlc02e1312007-04-11 17:16:24 +00001754 if (*prem == NULL) {
1755 Py_DECREF(z);
1756 return -1;
1757 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001758 }
Guido van Rossume32e0141992-01-19 16:31:05 +00001759 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001760 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001761 if (z == NULL)
1762 return -1;
1763 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001764 /* Set the signs.
1765 The quotient z has the sign of a*b;
1766 the remainder r has the sign of a,
1767 so a = b*z + r. */
Guido van Rossume32e0141992-01-19 16:31:05 +00001768 if ((a->ob_size < 0) != (b->ob_size < 0))
1769 z->ob_size = -(z->ob_size);
1770 if (a->ob_size < 0 && (*prem)->ob_size != 0)
1771 (*prem)->ob_size = -((*prem)->ob_size);
1772 *pdiv = z;
1773 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001774}
1775
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001776/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001777
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001778static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001779x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001780{
Martin v. Löwis68192102007-07-21 06:55:02 +00001781 Py_ssize_t size_v = ABS(Py_Size(v1)), size_w = ABS(Py_Size(w1));
Guido van Rossum2095d241997-04-09 19:41:24 +00001782 digit d = (digit) ((twodigits)BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001783 PyLongObject *v = mul1(v1, d);
1784 PyLongObject *w = mul1(w1, d);
1785 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001786 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001787
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001788 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001789 Py_XDECREF(v);
1790 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001791 return NULL;
1792 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001793
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001794 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Martin v. Löwis68192102007-07-21 06:55:02 +00001795 assert(Py_Refcnt(v) == 1); /* Since v will be used as accumulator! */
1796 assert(size_w == ABS(Py_Size(w))); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00001797
Martin v. Löwis68192102007-07-21 06:55:02 +00001798 size_v = ABS(Py_Size(v));
Neal Norwitzc6a989a2006-05-10 06:57:58 +00001799 k = size_v - size_w;
1800 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001801
Neal Norwitzc6a989a2006-05-10 06:57:58 +00001802 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001803 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
1804 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001805 stwodigits carry = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001806 int i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001807
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001808 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001809 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001810 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001811 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001812 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001813 if (vj == w->ob_digit[size_w-1])
1814 q = MASK;
1815 else
1816 q = (((twodigits)vj << SHIFT) + v->ob_digit[j-1]) /
1817 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00001818
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001819 while (w->ob_digit[size_w-2]*q >
1820 ((
1821 ((twodigits)vj << SHIFT)
1822 + v->ob_digit[j-1]
1823 - q*w->ob_digit[size_w-1]
1824 ) << SHIFT)
1825 + v->ob_digit[j-2])
1826 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001827
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001828 for (i = 0; i < size_w && i+k < size_v; ++i) {
1829 twodigits z = w->ob_digit[i] * q;
Guido van Rossum2095d241997-04-09 19:41:24 +00001830 digit zz = (digit) (z >> SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001831 carry += v->ob_digit[i+k] - z
1832 + ((twodigits)zz << SHIFT);
Jeremy Hyltonfc61f9a2003-05-01 21:31:53 +00001833 v->ob_digit[i+k] = (digit)(carry & MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00001834 carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
1835 carry, SHIFT);
1836 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001837 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001838
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001839 if (i+k < size_v) {
1840 carry += v->ob_digit[i+k];
1841 v->ob_digit[i+k] = 0;
1842 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001843
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001844 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00001845 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001846 else {
1847 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00001848 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001849 carry = 0;
1850 for (i = 0; i < size_w && i+k < size_v; ++i) {
1851 carry += v->ob_digit[i+k] + w->ob_digit[i];
Jeremy Hyltonfc61f9a2003-05-01 21:31:53 +00001852 v->ob_digit[i+k] = (digit)(carry & MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00001853 carry = Py_ARITHMETIC_RIGHT_SHIFT(
1854 BASE_TWODIGITS_TYPE,
1855 carry, SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001856 }
1857 }
1858 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00001859
Guido van Rossumc206c761995-01-10 15:23:19 +00001860 if (a == NULL)
1861 *prem = NULL;
1862 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00001863 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00001864 *prem = divrem1(v, d, &d);
1865 /* d receives the (unused) remainder */
1866 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001867 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00001868 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00001869 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001870 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001871 Py_DECREF(v);
1872 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001873 return a;
1874}
1875
1876/* Methods */
1877
1878static void
Tim Peters9f688bf2000-07-07 15:53:28 +00001879long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001880{
Martin v. Löwis68192102007-07-21 06:55:02 +00001881 Py_Type(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001882}
1883
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001884static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001885long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001886{
Fred Drake121ee271999-12-23 15:41:28 +00001887 return long_format(v, 10, 1);
1888}
1889
1890static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001891long_str(PyObject *v)
Fred Drake121ee271999-12-23 15:41:28 +00001892{
1893 return long_format(v, 10, 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001894}
1895
1896static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001897long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001898{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001899 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001900
Martin v. Löwis68192102007-07-21 06:55:02 +00001901 if (Py_Size(a) != Py_Size(b)) {
1902 if (ABS(Py_Size(a)) == 0 && ABS(Py_Size(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00001903 sign = 0;
1904 else
Martin v. Löwis68192102007-07-21 06:55:02 +00001905 sign = Py_Size(a) - Py_Size(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00001906 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001907 else {
Martin v. Löwis68192102007-07-21 06:55:02 +00001908 Py_ssize_t i = ABS(Py_Size(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001909 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
1910 ;
1911 if (i < 0)
1912 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00001913 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001914 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Martin v. Löwis68192102007-07-21 06:55:02 +00001915 if (Py_Size(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00001916 sign = -sign;
1917 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001918 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001919 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001920}
1921
Guido van Rossum9bfef441993-03-29 10:43:31 +00001922static long
Tim Peters9f688bf2000-07-07 15:53:28 +00001923long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001924{
1925 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001926 Py_ssize_t i;
1927 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001928
1929 /* This is designed so that Python ints and longs with the
1930 same value hash to the same value, otherwise comparisons
1931 of mapping keys will turn out weird */
1932 i = v->ob_size;
1933 sign = 1;
1934 x = 0;
1935 if (i < 0) {
1936 sign = -1;
1937 i = -(i);
1938 }
Neal Norwitzd5a65a72003-02-23 23:11:41 +00001939#define LONG_BIT_SHIFT (8*sizeof(long) - SHIFT)
Facundo Batistad544df72007-09-19 15:10:06 +00001940 /* The following loop produces a C long x such that (unsigned long)x
1941 is congruent to the absolute value of v modulo ULONG_MAX. The
1942 resulting x is nonzero if and only if v is. */
Guido van Rossum9bfef441993-03-29 10:43:31 +00001943 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00001944 /* Force a native long #-bits (32 or 64) circular shift */
1945 x = ((x << SHIFT) & ~MASK) | ((x >> LONG_BIT_SHIFT) & MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001946 x += v->ob_digit[i];
Facundo Batistad544df72007-09-19 15:10:06 +00001947 /* If the addition above overflowed (thinking of x as
1948 unsigned), we compensate by incrementing. This preserves
1949 the value modulo ULONG_MAX. */
1950 if ((unsigned long)x < v->ob_digit[i])
1951 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001952 }
Neal Norwitzd5a65a72003-02-23 23:11:41 +00001953#undef LONG_BIT_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00001954 x = x * sign;
1955 if (x == -1)
1956 x = -2;
1957 return x;
1958}
1959
1960
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001961/* Add the absolute values of two long integers. */
1962
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001963static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001964x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001965{
Martin v. Löwis68192102007-07-21 06:55:02 +00001966 Py_ssize_t size_a = ABS(Py_Size(a)), size_b = ABS(Py_Size(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001967 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001968 int i;
1969 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00001970
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001971 /* Ensure a is the larger of the two: */
1972 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001973 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00001974 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001975 size_a = size_b;
1976 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001977 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001978 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001979 if (z == NULL)
1980 return NULL;
1981 for (i = 0; i < size_b; ++i) {
1982 carry += a->ob_digit[i] + b->ob_digit[i];
1983 z->ob_digit[i] = carry & MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001984 carry >>= SHIFT;
1985 }
1986 for (; i < size_a; ++i) {
1987 carry += a->ob_digit[i];
1988 z->ob_digit[i] = carry & MASK;
1989 carry >>= SHIFT;
1990 }
1991 z->ob_digit[i] = carry;
1992 return long_normalize(z);
1993}
1994
1995/* Subtract the absolute values of two integers. */
1996
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001997static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001998x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001999{
Martin v. Löwis68192102007-07-21 06:55:02 +00002000 Py_ssize_t size_a = ABS(Py_Size(a)), size_b = ABS(Py_Size(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002001 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002002 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002003 int sign = 1;
2004 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002005
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002006 /* Ensure a is the larger of the two: */
2007 if (size_a < size_b) {
2008 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002009 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002010 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002011 size_a = size_b;
2012 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002013 }
2014 else if (size_a == size_b) {
2015 /* Find highest digit where a and b differ: */
2016 i = size_a;
2017 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2018 ;
2019 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002020 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002021 if (a->ob_digit[i] < b->ob_digit[i]) {
2022 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002023 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002024 }
2025 size_a = size_b = i+1;
2026 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002027 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002028 if (z == NULL)
2029 return NULL;
2030 for (i = 0; i < size_b; ++i) {
2031 /* The following assumes unsigned arithmetic
2032 works module 2**N for some N>SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002033 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002034 z->ob_digit[i] = borrow & MASK;
2035 borrow >>= SHIFT;
2036 borrow &= 1; /* Keep only one sign bit */
2037 }
2038 for (; i < size_a; ++i) {
2039 borrow = a->ob_digit[i] - borrow;
2040 z->ob_digit[i] = borrow & MASK;
2041 borrow >>= SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002042 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002043 }
2044 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002045 if (sign < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002046 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002047 return long_normalize(z);
2048}
2049
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002050static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002051long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002052{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002053 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002054
Neil Schemenauerba872e22001-01-04 01:46:03 +00002055 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2056
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002057 if (a->ob_size < 0) {
2058 if (b->ob_size < 0) {
2059 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002060 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002061 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002062 }
2063 else
2064 z = x_sub(b, a);
2065 }
2066 else {
2067 if (b->ob_size < 0)
2068 z = x_sub(a, b);
2069 else
2070 z = x_add(a, b);
2071 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002072 Py_DECREF(a);
2073 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002074 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002075}
2076
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002077static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002078long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002079{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002080 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002081
Neil Schemenauerba872e22001-01-04 01:46:03 +00002082 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2083
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002084 if (a->ob_size < 0) {
2085 if (b->ob_size < 0)
2086 z = x_sub(a, b);
2087 else
2088 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002089 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002090 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002091 }
2092 else {
2093 if (b->ob_size < 0)
2094 z = x_add(a, b);
2095 else
2096 z = x_sub(a, b);
2097 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002098 Py_DECREF(a);
2099 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002100 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002101}
2102
Tim Peters5af4e6c2002-08-12 02:31:19 +00002103/* Grade school multiplication, ignoring the signs.
2104 * Returns the absolute value of the product, or NULL if error.
2105 */
2106static PyLongObject *
2107x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002108{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002109 PyLongObject *z;
Martin v. Löwis68192102007-07-21 06:55:02 +00002110 Py_ssize_t size_a = ABS(Py_Size(a));
2111 Py_ssize_t size_b = ABS(Py_Size(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002112 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002113
Tim Peters5af4e6c2002-08-12 02:31:19 +00002114 z = _PyLong_New(size_a + size_b);
2115 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002116 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002117
Martin v. Löwis68192102007-07-21 06:55:02 +00002118 memset(z->ob_digit, 0, Py_Size(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002119 if (a == b) {
2120 /* Efficient squaring per HAC, Algorithm 14.16:
2121 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2122 * Gives slightly less than a 2x speedup when a == b,
2123 * via exploiting that each entry in the multiplication
2124 * pyramid appears twice (except for the size_a squares).
2125 */
2126 for (i = 0; i < size_a; ++i) {
2127 twodigits carry;
2128 twodigits f = a->ob_digit[i];
2129 digit *pz = z->ob_digit + (i << 1);
2130 digit *pa = a->ob_digit + i + 1;
2131 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002132
Tim Peters0973b992004-08-29 22:16:50 +00002133 SIGCHECK({
2134 Py_DECREF(z);
2135 return NULL;
2136 })
2137
2138 carry = *pz + f * f;
2139 *pz++ = (digit)(carry & MASK);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002140 carry >>= SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002141 assert(carry <= MASK);
2142
2143 /* Now f is added in twice in each column of the
2144 * pyramid it appears. Same as adding f<<1 once.
2145 */
2146 f <<= 1;
2147 while (pa < paend) {
2148 carry += *pz + *pa++ * f;
2149 *pz++ = (digit)(carry & MASK);
2150 carry >>= SHIFT;
2151 assert(carry <= (MASK << 1));
2152 }
2153 if (carry) {
2154 carry += *pz;
2155 *pz++ = (digit)(carry & MASK);
2156 carry >>= SHIFT;
2157 }
2158 if (carry)
2159 *pz += (digit)(carry & MASK);
2160 assert((carry >> SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002161 }
Tim Peters0973b992004-08-29 22:16:50 +00002162 }
2163 else { /* a is not the same as b -- gradeschool long mult */
2164 for (i = 0; i < size_a; ++i) {
2165 twodigits carry = 0;
2166 twodigits f = a->ob_digit[i];
2167 digit *pz = z->ob_digit + i;
2168 digit *pb = b->ob_digit;
2169 digit *pbend = b->ob_digit + size_b;
2170
2171 SIGCHECK({
2172 Py_DECREF(z);
2173 return NULL;
2174 })
2175
2176 while (pb < pbend) {
2177 carry += *pz + *pb++ * f;
2178 *pz++ = (digit)(carry & MASK);
2179 carry >>= SHIFT;
2180 assert(carry <= MASK);
2181 }
2182 if (carry)
2183 *pz += (digit)(carry & MASK);
2184 assert((carry >> SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002185 }
2186 }
Tim Peters44121a62002-08-12 06:17:58 +00002187 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002188}
2189
2190/* A helper for Karatsuba multiplication (k_mul).
2191 Takes a long "n" and an integer "size" representing the place to
2192 split, and sets low and high such that abs(n) == (high << size) + low,
2193 viewing the shift as being by digits. The sign bit is ignored, and
2194 the return values are >= 0.
2195 Returns 0 on success, -1 on failure.
2196*/
2197static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002198kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002199{
2200 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002201 Py_ssize_t size_lo, size_hi;
Martin v. Löwis68192102007-07-21 06:55:02 +00002202 const Py_ssize_t size_n = ABS(Py_Size(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002203
2204 size_lo = MIN(size_n, size);
2205 size_hi = size_n - size_lo;
2206
2207 if ((hi = _PyLong_New(size_hi)) == NULL)
2208 return -1;
2209 if ((lo = _PyLong_New(size_lo)) == NULL) {
2210 Py_DECREF(hi);
2211 return -1;
2212 }
2213
2214 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2215 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2216
2217 *high = long_normalize(hi);
2218 *low = long_normalize(lo);
2219 return 0;
2220}
2221
Tim Peters60004642002-08-12 22:01:34 +00002222static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2223
Tim Peters5af4e6c2002-08-12 02:31:19 +00002224/* Karatsuba multiplication. Ignores the input signs, and returns the
2225 * absolute value of the product (or NULL if error).
2226 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2227 */
2228static PyLongObject *
2229k_mul(PyLongObject *a, PyLongObject *b)
2230{
Martin v. Löwis68192102007-07-21 06:55:02 +00002231 Py_ssize_t asize = ABS(Py_Size(a));
2232 Py_ssize_t bsize = ABS(Py_Size(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002233 PyLongObject *ah = NULL;
2234 PyLongObject *al = NULL;
2235 PyLongObject *bh = NULL;
2236 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002237 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002238 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002239 Py_ssize_t shift; /* the number of digits we split off */
2240 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002241
Tim Peters5af4e6c2002-08-12 02:31:19 +00002242 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2243 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2244 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002245 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002246 * By picking X to be a power of 2, "*X" is just shifting, and it's
2247 * been reduced to 3 multiplies on numbers half the size.
2248 */
2249
Tim Petersfc07e562002-08-12 02:54:10 +00002250 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002251 * is largest.
2252 */
Tim Peters738eda72002-08-12 15:08:20 +00002253 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002254 t1 = a;
2255 a = b;
2256 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002257
2258 i = asize;
2259 asize = bsize;
2260 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002261 }
2262
2263 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002264 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2265 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002266 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002267 return _PyLong_New(0);
2268 else
2269 return x_mul(a, b);
2270 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002271
Tim Peters60004642002-08-12 22:01:34 +00002272 /* If a is small compared to b, splitting on b gives a degenerate
2273 * case with ah==0, and Karatsuba may be (even much) less efficient
2274 * than "grade school" then. However, we can still win, by viewing
2275 * b as a string of "big digits", each of width a->ob_size. That
2276 * leads to a sequence of balanced calls to k_mul.
2277 */
2278 if (2 * asize <= bsize)
2279 return k_lopsided_mul(a, b);
2280
Tim Petersd6974a52002-08-13 20:37:51 +00002281 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002282 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002283 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Martin v. Löwis68192102007-07-21 06:55:02 +00002284 assert(Py_Size(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002285
Tim Peters0973b992004-08-29 22:16:50 +00002286 if (a == b) {
2287 bh = ah;
2288 bl = al;
2289 Py_INCREF(bh);
2290 Py_INCREF(bl);
2291 }
2292 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002293
Tim Petersd64c1de2002-08-12 17:36:03 +00002294 /* The plan:
2295 * 1. Allocate result space (asize + bsize digits: that's always
2296 * enough).
2297 * 2. Compute ah*bh, and copy into result at 2*shift.
2298 * 3. Compute al*bl, and copy into result at 0. Note that this
2299 * can't overlap with #2.
2300 * 4. Subtract al*bl from the result, starting at shift. This may
2301 * underflow (borrow out of the high digit), but we don't care:
2302 * we're effectively doing unsigned arithmetic mod
2303 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2304 * borrows and carries out of the high digit can be ignored.
2305 * 5. Subtract ah*bh from the result, starting at shift.
2306 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2307 * at shift.
2308 */
2309
2310 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002311 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002312 if (ret == NULL) goto fail;
2313#ifdef Py_DEBUG
2314 /* Fill with trash, to catch reference to uninitialized digits. */
Martin v. Löwis68192102007-07-21 06:55:02 +00002315 memset(ret->ob_digit, 0xDF, Py_Size(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002316#endif
Tim Peters44121a62002-08-12 06:17:58 +00002317
Tim Petersd64c1de2002-08-12 17:36:03 +00002318 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002319 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Martin v. Löwis68192102007-07-21 06:55:02 +00002320 assert(Py_Size(t1) >= 0);
2321 assert(2*shift + Py_Size(t1) <= Py_Size(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002322 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Martin v. Löwis68192102007-07-21 06:55:02 +00002323 Py_Size(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002324
2325 /* Zero-out the digits higher than the ah*bh copy. */
Martin v. Löwis68192102007-07-21 06:55:02 +00002326 i = Py_Size(ret) - 2*shift - Py_Size(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002327 if (i)
Martin v. Löwis68192102007-07-21 06:55:02 +00002328 memset(ret->ob_digit + 2*shift + Py_Size(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002329 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002330
Tim Petersd64c1de2002-08-12 17:36:03 +00002331 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002332 if ((t2 = k_mul(al, bl)) == NULL) {
2333 Py_DECREF(t1);
2334 goto fail;
2335 }
Martin v. Löwis68192102007-07-21 06:55:02 +00002336 assert(Py_Size(t2) >= 0);
2337 assert(Py_Size(t2) <= 2*shift); /* no overlap with high digits */
2338 memcpy(ret->ob_digit, t2->ob_digit, Py_Size(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002339
2340 /* Zero out remaining digits. */
Martin v. Löwis68192102007-07-21 06:55:02 +00002341 i = 2*shift - Py_Size(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002342 if (i)
Martin v. Löwis68192102007-07-21 06:55:02 +00002343 memset(ret->ob_digit + Py_Size(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002344
Tim Petersd64c1de2002-08-12 17:36:03 +00002345 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2346 * because it's fresher in cache.
2347 */
Martin v. Löwis68192102007-07-21 06:55:02 +00002348 i = Py_Size(ret) - shift; /* # digits after shift */
2349 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_Size(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002350 Py_DECREF(t2);
2351
Martin v. Löwis68192102007-07-21 06:55:02 +00002352 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_Size(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002353 Py_DECREF(t1);
2354
Tim Petersd64c1de2002-08-12 17:36:03 +00002355 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002356 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2357 Py_DECREF(ah);
2358 Py_DECREF(al);
2359 ah = al = NULL;
2360
Tim Peters0973b992004-08-29 22:16:50 +00002361 if (a == b) {
2362 t2 = t1;
2363 Py_INCREF(t2);
2364 }
2365 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002366 Py_DECREF(t1);
2367 goto fail;
2368 }
2369 Py_DECREF(bh);
2370 Py_DECREF(bl);
2371 bh = bl = NULL;
2372
Tim Peters738eda72002-08-12 15:08:20 +00002373 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002374 Py_DECREF(t1);
2375 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002376 if (t3 == NULL) goto fail;
Martin v. Löwis68192102007-07-21 06:55:02 +00002377 assert(Py_Size(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002378
Tim Petersd6974a52002-08-13 20:37:51 +00002379 /* Add t3. It's not obvious why we can't run out of room here.
2380 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002381 */
Martin v. Löwis68192102007-07-21 06:55:02 +00002382 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_Size(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002383 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002384
Tim Peters5af4e6c2002-08-12 02:31:19 +00002385 return long_normalize(ret);
2386
2387 fail:
2388 Py_XDECREF(ret);
2389 Py_XDECREF(ah);
2390 Py_XDECREF(al);
2391 Py_XDECREF(bh);
2392 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002393 return NULL;
2394}
2395
Tim Petersd6974a52002-08-13 20:37:51 +00002396/* (*) Why adding t3 can't "run out of room" above.
2397
Tim Petersab86c2b2002-08-15 20:06:00 +00002398Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2399to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002400
Tim Petersab86c2b2002-08-15 20:06:00 +000024011. For any integer i, i = c(i/2) + f(i/2). In particular,
2402 bsize = c(bsize/2) + f(bsize/2).
24032. shift = f(bsize/2)
24043. asize <= bsize
24054. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2406 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002407
Tim Petersab86c2b2002-08-15 20:06:00 +00002408We allocated asize + bsize result digits, and add t3 into them at an offset
2409of shift. This leaves asize+bsize-shift allocated digit positions for t3
2410to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2411asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002412
Tim Petersab86c2b2002-08-15 20:06:00 +00002413bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2414at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002415
Tim Petersab86c2b2002-08-15 20:06:00 +00002416If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2417digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2418most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002419
Tim Petersab86c2b2002-08-15 20:06:00 +00002420The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002421
Tim Petersab86c2b2002-08-15 20:06:00 +00002422 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002423
Tim Petersab86c2b2002-08-15 20:06:00 +00002424and we have asize + c(bsize/2) available digit positions. We need to show
2425this is always enough. An instance of c(bsize/2) cancels out in both, so
2426the question reduces to whether asize digits is enough to hold
2427(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2428then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2429asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
2430digit is enough to hold 2 bits. This is so since SHIFT=15 >= 2. If
2431asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002432c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2433is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2434bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002435
Tim Peters48d52c02002-08-14 17:07:32 +00002436Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2437clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2438ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002439*/
2440
Tim Peters60004642002-08-12 22:01:34 +00002441/* b has at least twice the digits of a, and a is big enough that Karatsuba
2442 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2443 * of slices, each with a->ob_size digits, and multiply the slices by a,
2444 * one at a time. This gives k_mul balanced inputs to work with, and is
2445 * also cache-friendly (we compute one double-width slice of the result
2446 * at a time, then move on, never bactracking except for the helpful
2447 * single-width slice overlap between successive partial sums).
2448 */
2449static PyLongObject *
2450k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2451{
Martin v. Löwis68192102007-07-21 06:55:02 +00002452 const Py_ssize_t asize = ABS(Py_Size(a));
2453 Py_ssize_t bsize = ABS(Py_Size(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002454 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002455 PyLongObject *ret;
2456 PyLongObject *bslice = NULL;
2457
2458 assert(asize > KARATSUBA_CUTOFF);
2459 assert(2 * asize <= bsize);
2460
2461 /* Allocate result space, and zero it out. */
2462 ret = _PyLong_New(asize + bsize);
2463 if (ret == NULL)
2464 return NULL;
Martin v. Löwis68192102007-07-21 06:55:02 +00002465 memset(ret->ob_digit, 0, Py_Size(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002466
2467 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002468 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002469 if (bslice == NULL)
2470 goto fail;
2471
2472 nbdone = 0;
2473 while (bsize > 0) {
2474 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002475 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002476
2477 /* Multiply the next slice of b by a. */
2478 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2479 nbtouse * sizeof(digit));
Martin v. Löwis68192102007-07-21 06:55:02 +00002480 Py_Size(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00002481 product = k_mul(a, bslice);
2482 if (product == NULL)
2483 goto fail;
2484
2485 /* Add into result. */
Martin v. Löwis68192102007-07-21 06:55:02 +00002486 (void)v_iadd(ret->ob_digit + nbdone, Py_Size(ret) - nbdone,
2487 product->ob_digit, Py_Size(product));
Tim Peters60004642002-08-12 22:01:34 +00002488 Py_DECREF(product);
2489
2490 bsize -= nbtouse;
2491 nbdone += nbtouse;
2492 }
2493
2494 Py_DECREF(bslice);
2495 return long_normalize(ret);
2496
2497 fail:
2498 Py_DECREF(ret);
2499 Py_XDECREF(bslice);
2500 return NULL;
2501}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002502
2503static PyObject *
2504long_mul(PyLongObject *v, PyLongObject *w)
2505{
2506 PyLongObject *a, *b, *z;
2507
2508 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002509 Py_INCREF(Py_NotImplemented);
2510 return Py_NotImplemented;
2511 }
2512
Tim Petersd64c1de2002-08-12 17:36:03 +00002513 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002514 /* Negate if exactly one of the inputs is negative. */
2515 if (((a->ob_size ^ b->ob_size) < 0) && z)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002516 z->ob_size = -(z->ob_size);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002517 Py_DECREF(a);
2518 Py_DECREF(b);
Tim Peters9973d742002-08-15 19:41:06 +00002519 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002520}
2521
Guido van Rossume32e0141992-01-19 16:31:05 +00002522/* The / and % operators are now defined in terms of divmod().
2523 The expression a mod b has the value a - b*floor(a/b).
2524 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002525 |a| by |b|, with the sign of a. This is also expressed
2526 as a - b*trunc(a/b), if trunc truncates towards zero.
2527 Some examples:
2528 a b a rem b a mod b
2529 13 10 3 3
2530 -13 10 -3 7
2531 13 -10 3 -7
2532 -13 -10 -3 -3
2533 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002534 have different signs. We then subtract one from the 'div'
2535 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002536
Tim Peters47e52ee2004-08-30 02:44:38 +00002537/* Compute
2538 * *pdiv, *pmod = divmod(v, w)
2539 * NULL can be passed for pdiv or pmod, in which case that part of
2540 * the result is simply thrown away. The caller owns a reference to
2541 * each of these it requests (does not pass NULL for).
2542 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002543static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002544l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002545 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002546{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002547 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002548
Guido van Rossume32e0141992-01-19 16:31:05 +00002549 if (long_divrem(v, w, &div, &mod) < 0)
2550 return -1;
Martin v. Löwis68192102007-07-21 06:55:02 +00002551 if ((Py_Size(mod) < 0 && Py_Size(w) > 0) ||
2552 (Py_Size(mod) > 0 && Py_Size(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002553 PyLongObject *temp;
2554 PyLongObject *one;
2555 temp = (PyLongObject *) long_add(mod, w);
2556 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002557 mod = temp;
2558 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002559 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002560 return -1;
2561 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002562 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002563 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002564 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2565 Py_DECREF(mod);
2566 Py_DECREF(div);
2567 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002568 return -1;
2569 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002570 Py_DECREF(one);
2571 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002572 div = temp;
2573 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002574 if (pdiv != NULL)
2575 *pdiv = div;
2576 else
2577 Py_DECREF(div);
2578
2579 if (pmod != NULL)
2580 *pmod = mod;
2581 else
2582 Py_DECREF(mod);
2583
Guido van Rossume32e0141992-01-19 16:31:05 +00002584 return 0;
2585}
2586
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002587static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002588long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002589{
Tim Peters47e52ee2004-08-30 02:44:38 +00002590 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002591
2592 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002593 if (l_divmod(a, b, &div, NULL) < 0)
2594 div = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002595 Py_DECREF(a);
2596 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002597 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002598}
2599
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002600static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +00002601long_classic_div(PyObject *v, PyObject *w)
2602{
Tim Peters47e52ee2004-08-30 02:44:38 +00002603 PyLongObject *a, *b, *div;
Guido van Rossum393661d2001-08-31 17:40:15 +00002604
2605 CONVERT_BINOP(v, w, &a, &b);
Guido van Rossum393661d2001-08-31 17:40:15 +00002606 if (Py_DivisionWarningFlag &&
2607 PyErr_Warn(PyExc_DeprecationWarning, "classic long division") < 0)
2608 div = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00002609 else if (l_divmod(a, b, &div, NULL) < 0)
Guido van Rossum393661d2001-08-31 17:40:15 +00002610 div = NULL;
Guido van Rossum393661d2001-08-31 17:40:15 +00002611 Py_DECREF(a);
2612 Py_DECREF(b);
2613 return (PyObject *)div;
2614}
2615
2616static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00002617long_true_divide(PyObject *v, PyObject *w)
2618{
Tim Peterse2a60002001-09-04 06:17:36 +00002619 PyLongObject *a, *b;
2620 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002621 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002622
2623 CONVERT_BINOP(v, w, &a, &b);
2624 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2625 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002626 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
2627 Py_DECREF(a);
2628 Py_DECREF(b);
2629 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002630 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002631 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2632 but should really be set correctly after sucessful calls to
2633 _PyLong_AsScaledDouble() */
2634 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002635
2636 if (bd == 0.0) {
2637 PyErr_SetString(PyExc_ZeroDivisionError,
2638 "long division or modulo by zero");
2639 return NULL;
2640 }
2641
2642 /* True value is very close to ad/bd * 2**(SHIFT*(aexp-bexp)) */
2643 ad /= bd; /* overflow/underflow impossible here */
2644 aexp -= bexp;
2645 if (aexp > INT_MAX / SHIFT)
2646 goto overflow;
Tim Peterse56ed9b2001-09-06 21:59:14 +00002647 else if (aexp < -(INT_MAX / SHIFT))
2648 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002649 errno = 0;
2650 ad = ldexp(ad, aexp * SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002651 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002652 goto overflow;
2653 return PyFloat_FromDouble(ad);
2654
2655overflow:
2656 PyErr_SetString(PyExc_OverflowError,
2657 "long/long too large for a float");
2658 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002659
Tim Peters20dab9f2001-09-04 05:31:47 +00002660}
2661
2662static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002663long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002664{
Tim Peters47e52ee2004-08-30 02:44:38 +00002665 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002666
2667 CONVERT_BINOP(v, w, &a, &b);
2668
Tim Peters47e52ee2004-08-30 02:44:38 +00002669 if (l_divmod(a, b, NULL, &mod) < 0)
2670 mod = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002671 Py_DECREF(a);
2672 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002673 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002674}
2675
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002676static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002677long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002678{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002679 PyLongObject *a, *b, *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002680 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002681
2682 CONVERT_BINOP(v, w, &a, &b);
2683
2684 if (l_divmod(a, b, &div, &mod) < 0) {
2685 Py_DECREF(a);
2686 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002687 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002688 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002689 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002690 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002691 PyTuple_SetItem(z, 0, (PyObject *) div);
2692 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002693 }
2694 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002695 Py_DECREF(div);
2696 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002697 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002698 Py_DECREF(a);
2699 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002700 return z;
2701}
2702
Tim Peters47e52ee2004-08-30 02:44:38 +00002703/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002704static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002705long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002706{
Tim Peters47e52ee2004-08-30 02:44:38 +00002707 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
2708 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002709
Tim Peters47e52ee2004-08-30 02:44:38 +00002710 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002711 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00002712 PyLongObject *temp = NULL;
2713
2714 /* 5-ary values. If the exponent is large enough, table is
2715 * precomputed so that table[i] == a**i % c for i in range(32).
2716 */
2717 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2718 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2719
2720 /* a, b, c = v, w, x */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002721 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002722 if (PyLong_Check(x)) {
2723 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002724 Py_INCREF(x);
2725 }
Tim Petersde7990b2005-07-17 23:45:23 +00002726 else if (PyInt_Check(x)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002727 c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x));
Tim Petersde7990b2005-07-17 23:45:23 +00002728 if (c == NULL)
2729 goto Error;
2730 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002731 else if (x == Py_None)
2732 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002733 else {
2734 Py_DECREF(a);
2735 Py_DECREF(b);
2736 Py_INCREF(Py_NotImplemented);
2737 return Py_NotImplemented;
2738 }
Tim Peters4c483c42001-09-05 06:24:58 +00002739
Martin v. Löwis68192102007-07-21 06:55:02 +00002740 if (Py_Size(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00002741 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00002742 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00002743 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00002744 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00002745 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002746 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00002747 /* else return a float. This works because we know
2748 that this calls float_pow() which converts its
2749 arguments to double. */
2750 Py_DECREF(a);
2751 Py_DECREF(b);
2752 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002753 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002754 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002755
2756 if (c) {
2757 /* if modulus == 0:
2758 raise ValueError() */
Martin v. Löwis68192102007-07-21 06:55:02 +00002759 if (Py_Size(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002760 PyErr_SetString(PyExc_ValueError,
2761 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00002762 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002763 }
2764
2765 /* if modulus < 0:
2766 negativeOutput = True
2767 modulus = -modulus */
Martin v. Löwis68192102007-07-21 06:55:02 +00002768 if (Py_Size(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002769 negativeOutput = 1;
2770 temp = (PyLongObject *)_PyLong_Copy(c);
2771 if (temp == NULL)
2772 goto Error;
2773 Py_DECREF(c);
2774 c = temp;
2775 temp = NULL;
2776 c->ob_size = - c->ob_size;
2777 }
2778
2779 /* if modulus == 1:
2780 return 0 */
Martin v. Löwis68192102007-07-21 06:55:02 +00002781 if ((Py_Size(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002782 z = (PyLongObject *)PyLong_FromLong(0L);
2783 goto Done;
2784 }
2785
2786 /* if base < 0:
2787 base = base % modulus
2788 Having the base positive just makes things easier. */
Martin v. Löwis68192102007-07-21 06:55:02 +00002789 if (Py_Size(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002790 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00002791 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002792 Py_DECREF(a);
2793 a = temp;
2794 temp = NULL;
2795 }
2796 }
2797
2798 /* At this point a, b, and c are guaranteed non-negative UNLESS
2799 c is NULL, in which case a may be negative. */
2800
2801 z = (PyLongObject *)PyLong_FromLong(1L);
2802 if (z == NULL)
2803 goto Error;
2804
2805 /* Perform a modular reduction, X = X % c, but leave X alone if c
2806 * is NULL.
2807 */
2808#define REDUCE(X) \
2809 if (c != NULL) { \
2810 if (l_divmod(X, c, NULL, &temp) < 0) \
2811 goto Error; \
2812 Py_XDECREF(X); \
2813 X = temp; \
2814 temp = NULL; \
2815 }
2816
2817 /* Multiply two values, then reduce the result:
2818 result = X*Y % c. If c is NULL, skip the mod. */
2819#define MULT(X, Y, result) \
2820{ \
2821 temp = (PyLongObject *)long_mul(X, Y); \
2822 if (temp == NULL) \
2823 goto Error; \
2824 Py_XDECREF(result); \
2825 result = temp; \
2826 temp = NULL; \
2827 REDUCE(result) \
2828}
2829
Martin v. Löwis68192102007-07-21 06:55:02 +00002830 if (Py_Size(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002831 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
2832 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Martin v. Löwis68192102007-07-21 06:55:02 +00002833 for (i = Py_Size(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002834 digit bi = b->ob_digit[i];
2835
2836 for (j = 1 << (SHIFT-1); j != 0; j >>= 1) {
2837 MULT(z, z, z)
2838 if (bi & j)
2839 MULT(z, a, z)
2840 }
2841 }
2842 }
2843 else {
2844 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
2845 Py_INCREF(z); /* still holds 1L */
2846 table[0] = z;
2847 for (i = 1; i < 32; ++i)
2848 MULT(table[i-1], a, table[i])
2849
Martin v. Löwis68192102007-07-21 06:55:02 +00002850 for (i = Py_Size(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002851 const digit bi = b->ob_digit[i];
2852
2853 for (j = SHIFT - 5; j >= 0; j -= 5) {
2854 const int index = (bi >> j) & 0x1f;
2855 for (k = 0; k < 5; ++k)
2856 MULT(z, z, z)
2857 if (index)
2858 MULT(z, table[index], z)
2859 }
2860 }
2861 }
2862
Martin v. Löwis68192102007-07-21 06:55:02 +00002863 if (negativeOutput && (Py_Size(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002864 temp = (PyLongObject *)long_sub(z, c);
2865 if (temp == NULL)
2866 goto Error;
2867 Py_DECREF(z);
2868 z = temp;
2869 temp = NULL;
2870 }
2871 goto Done;
2872
2873 Error:
2874 if (z != NULL) {
2875 Py_DECREF(z);
2876 z = NULL;
2877 }
2878 /* fall through */
2879 Done:
Martin v. Löwis68192102007-07-21 06:55:02 +00002880 if (Py_Size(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002881 for (i = 0; i < 32; ++i)
2882 Py_XDECREF(table[i]);
2883 }
Tim Petersde7990b2005-07-17 23:45:23 +00002884 Py_DECREF(a);
2885 Py_DECREF(b);
2886 Py_XDECREF(c);
2887 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002888 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002889}
2890
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002891static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002892long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002893{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002894 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002895 PyLongObject *x;
2896 PyLongObject *w;
2897 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002898 if (w == NULL)
2899 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002900 x = (PyLongObject *) long_add(v, w);
2901 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002902 if (x == NULL)
2903 return NULL;
Martin v. Löwis68192102007-07-21 06:55:02 +00002904 Py_Size(x) = -(Py_Size(x));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002905 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002906}
2907
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002908static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002909long_pos(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002910{
Tim Peters69c2de32001-09-11 22:31:33 +00002911 if (PyLong_CheckExact(v)) {
2912 Py_INCREF(v);
2913 return (PyObject *)v;
2914 }
2915 else
2916 return _PyLong_Copy(v);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002917}
2918
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002919static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002920long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002921{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002922 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002923 if (v->ob_size == 0 && PyLong_CheckExact(v)) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002924 /* -0 == 0 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002925 Py_INCREF(v);
2926 return (PyObject *) v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002927 }
Tim Peters69c2de32001-09-11 22:31:33 +00002928 z = (PyLongObject *)_PyLong_Copy(v);
2929 if (z != NULL)
2930 z->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002931 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002932}
2933
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002934static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002935long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002936{
2937 if (v->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002938 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00002939 else
2940 return long_pos(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002941}
2942
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002943static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002944long_nonzero(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002945{
Martin v. Löwis68192102007-07-21 06:55:02 +00002946 return ABS(Py_Size(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002947}
2948
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002949static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002950long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002951{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002952 PyLongObject *a, *b;
2953 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002954 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002955 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002956 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002957
Neil Schemenauerba872e22001-01-04 01:46:03 +00002958 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2959
Martin v. Löwis68192102007-07-21 06:55:02 +00002960 if (Py_Size(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002961 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002962 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002963 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002964 if (a1 == NULL)
2965 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002966 a2 = (PyLongObject *) long_rshift(a1, b);
2967 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002968 if (a2 == NULL)
2969 goto rshift_error;
2970 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002971 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002972 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002973 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002974
Neil Schemenauerba872e22001-01-04 01:46:03 +00002975 shiftby = PyLong_AsLong((PyObject *)b);
2976 if (shiftby == -1L && PyErr_Occurred())
2977 goto rshift_error;
2978 if (shiftby < 0) {
2979 PyErr_SetString(PyExc_ValueError,
2980 "negative shift count");
2981 goto rshift_error;
2982 }
2983 wordshift = shiftby / SHIFT;
Martin v. Löwis68192102007-07-21 06:55:02 +00002984 newsize = ABS(Py_Size(a)) - wordshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002985 if (newsize <= 0) {
2986 z = _PyLong_New(0);
2987 Py_DECREF(a);
2988 Py_DECREF(b);
2989 return (PyObject *)z;
2990 }
2991 loshift = shiftby % SHIFT;
2992 hishift = SHIFT - loshift;
2993 lomask = ((digit)1 << hishift) - 1;
2994 himask = MASK ^ lomask;
2995 z = _PyLong_New(newsize);
2996 if (z == NULL)
2997 goto rshift_error;
Martin v. Löwis68192102007-07-21 06:55:02 +00002998 if (Py_Size(a) < 0)
2999 Py_Size(z) = -(Py_Size(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003000 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3001 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3002 if (i+1 < newsize)
3003 z->ob_digit[i] |=
3004 (a->ob_digit[j+1] << hishift) & himask;
3005 }
3006 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003007 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003008rshift_error:
3009 Py_DECREF(a);
3010 Py_DECREF(b);
3011 return (PyObject *) z;
3012
Guido van Rossumc6913e71991-11-19 20:26:46 +00003013}
3014
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003015static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003016long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003017{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003018 /* This version due to Tim Peters */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003019 PyLongObject *a, *b;
3020 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003021 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003022 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003023 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003024
Neil Schemenauerba872e22001-01-04 01:46:03 +00003025 CONVERT_BINOP(v, w, &a, &b);
3026
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003027 shiftby = PyLong_AsLong((PyObject *)b);
3028 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003029 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003030 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003031 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003032 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003033 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003034 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003035 PyErr_SetString(PyExc_ValueError,
3036 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003037 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003038 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003039 /* wordshift, remshift = divmod(shiftby, SHIFT) */
3040 wordshift = (int)shiftby / SHIFT;
3041 remshift = (int)shiftby - wordshift * SHIFT;
3042
3043 oldsize = ABS(a->ob_size);
3044 newsize = oldsize + wordshift;
3045 if (remshift)
3046 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003047 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003048 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003049 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003050 if (a->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003051 z->ob_size = -(z->ob_size);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003052 for (i = 0; i < wordshift; i++)
3053 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003054 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003055 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003056 accum |= (twodigits)a->ob_digit[j] << remshift;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003057 z->ob_digit[i] = (digit)(accum & MASK);
3058 accum >>= SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003059 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003060 if (remshift)
3061 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003062 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003063 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003064 z = long_normalize(z);
3065lshift_error:
3066 Py_DECREF(a);
3067 Py_DECREF(b);
3068 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003069}
3070
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003071
3072/* Bitwise and/xor/or operations */
3073
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003074static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003075long_bitwise(PyLongObject *a,
3076 int op, /* '&', '|', '^' */
3077 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003078{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003079 digit maska, maskb; /* 0 or MASK */
3080 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003081 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003082 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003083 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003084 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003085 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003086
Martin v. Löwis68192102007-07-21 06:55:02 +00003087 if (Py_Size(a) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003088 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003089 if (a == NULL)
3090 return NULL;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003091 maska = MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003092 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003093 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003094 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003095 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003096 }
Martin v. Löwis68192102007-07-21 06:55:02 +00003097 if (Py_Size(b) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003098 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003099 if (b == NULL) {
3100 Py_DECREF(a);
3101 return NULL;
3102 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003103 maskb = MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003104 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003105 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003106 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003107 maskb = 0;
3108 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003109
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003110 negz = 0;
3111 switch (op) {
3112 case '^':
3113 if (maska != maskb) {
3114 maska ^= MASK;
3115 negz = -1;
3116 }
3117 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003118 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003119 if (maska && maskb) {
3120 op = '|';
3121 maska ^= MASK;
3122 maskb ^= MASK;
3123 negz = -1;
3124 }
3125 break;
3126 case '|':
3127 if (maska || maskb) {
3128 op = '&';
3129 maska ^= MASK;
3130 maskb ^= MASK;
3131 negz = -1;
3132 }
3133 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003134 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003135
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003136 /* JRH: The original logic here was to allocate the result value (z)
3137 as the longer of the two operands. However, there are some cases
3138 where the result is guaranteed to be shorter than that: AND of two
3139 positives, OR of two negatives: use the shorter number. AND with
3140 mixed signs: use the positive number. OR with mixed signs: use the
3141 negative number. After the transformations above, op will be '&'
3142 iff one of these cases applies, and mask will be non-0 for operands
3143 whose length should be ignored.
3144 */
3145
Martin v. Löwis68192102007-07-21 06:55:02 +00003146 size_a = Py_Size(a);
3147 size_b = Py_Size(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003148 size_z = op == '&'
3149 ? (maska
3150 ? size_b
3151 : (maskb ? size_a : MIN(size_a, size_b)))
3152 : MAX(size_a, size_b);
3153 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003154 if (z == NULL) {
Neal Norwitzef02b9e2006-07-16 02:00:32 +00003155 Py_DECREF(a);
3156 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003157 return NULL;
3158 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003159
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003160 for (i = 0; i < size_z; ++i) {
3161 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3162 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3163 switch (op) {
3164 case '&': z->ob_digit[i] = diga & digb; break;
3165 case '|': z->ob_digit[i] = diga | digb; break;
3166 case '^': z->ob_digit[i] = diga ^ digb; break;
3167 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003168 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003169
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003170 Py_DECREF(a);
3171 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003172 z = long_normalize(z);
3173 if (negz == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003174 return (PyObject *) z;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003175 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003176 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003177 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003178}
3179
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003180static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003181long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003182{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003183 PyLongObject *a, *b;
3184 PyObject *c;
3185 CONVERT_BINOP(v, w, &a, &b);
3186 c = long_bitwise(a, '&', b);
3187 Py_DECREF(a);
3188 Py_DECREF(b);
3189 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003190}
3191
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003192static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003193long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003194{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003195 PyLongObject *a, *b;
3196 PyObject *c;
3197 CONVERT_BINOP(v, w, &a, &b);
3198 c = long_bitwise(a, '^', b);
3199 Py_DECREF(a);
3200 Py_DECREF(b);
3201 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003202}
3203
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003204static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003205long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003206{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003207 PyLongObject *a, *b;
3208 PyObject *c;
3209 CONVERT_BINOP(v, w, &a, &b);
3210 c = long_bitwise(a, '|', b);
3211 Py_DECREF(a);
3212 Py_DECREF(b);
3213 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003214}
3215
Guido van Rossum234f9421993-06-17 12:35:49 +00003216static int
Tim Peters9f688bf2000-07-07 15:53:28 +00003217long_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00003218{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003219 if (PyInt_Check(*pw)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00003220 *pw = PyLong_FromLong(PyInt_AS_LONG(*pw));
Georg Brandlc02e1312007-04-11 17:16:24 +00003221 if (*pw == NULL)
3222 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003223 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00003224 return 0;
3225 }
Guido van Rossum1952e382001-09-19 01:25:16 +00003226 else if (PyLong_Check(*pw)) {
3227 Py_INCREF(*pv);
3228 Py_INCREF(*pw);
3229 return 0;
3230 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00003231 return 1; /* Can't do it */
3232}
3233
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003234static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003235long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003236{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003237 if (PyLong_CheckExact(v))
3238 Py_INCREF(v);
3239 else
3240 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003241 return v;
3242}
3243
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003244static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00003245long_int(PyObject *v)
3246{
3247 long x;
3248 x = PyLong_AsLong(v);
3249 if (PyErr_Occurred()) {
3250 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
3251 PyErr_Clear();
3252 if (PyLong_CheckExact(v)) {
3253 Py_INCREF(v);
3254 return v;
3255 }
3256 else
3257 return _PyLong_Copy((PyLongObject *)v);
3258 }
3259 else
3260 return NULL;
3261 }
3262 return PyInt_FromLong(x);
3263}
3264
3265static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003266long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003267{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003268 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003269 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003270 if (result == -1.0 && PyErr_Occurred())
3271 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003272 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003273}
3274
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003275static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003276long_oct(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003277{
Fred Drake121ee271999-12-23 15:41:28 +00003278 return long_format(v, 8, 1);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003279}
3280
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003281static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003282long_hex(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003283{
Fred Drake121ee271999-12-23 15:41:28 +00003284 return long_format(v, 16, 1);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003285}
Jeremy Hylton938ace62002-07-17 16:30:39 +00003286
3287static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003288long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003289
Tim Peters6d6c1a32001-08-02 04:15:00 +00003290static PyObject *
3291long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3292{
3293 PyObject *x = NULL;
3294 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003295 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003296
Guido van Rossumbef14172001-08-29 15:47:46 +00003297 if (type != &PyLong_Type)
3298 return long_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003299 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist,
3300 &x, &base))
3301 return NULL;
3302 if (x == NULL)
3303 return PyLong_FromLong(0L);
3304 if (base == -909)
3305 return PyNumber_Long(x);
Georg Brandl00cd8182007-03-06 18:41:12 +00003306 else if (PyString_Check(x)) {
3307 /* Since PyLong_FromString doesn't have a length parameter,
3308 * check here for possible NULs in the string. */
3309 char *string = PyString_AS_STRING(x);
3310 if (strlen(string) != PyString_Size(x)) {
3311 /* create a repr() of the input string,
3312 * just like PyLong_FromString does. */
3313 PyObject *srepr;
3314 srepr = PyObject_Repr(x);
3315 if (srepr == NULL)
3316 return NULL;
3317 PyErr_Format(PyExc_ValueError,
3318 "invalid literal for long() with base %d: %s",
3319 base, PyString_AS_STRING(srepr));
3320 Py_DECREF(srepr);
3321 return NULL;
3322 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003323 return PyLong_FromString(PyString_AS_STRING(x), NULL, base);
Georg Brandl00cd8182007-03-06 18:41:12 +00003324 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003325#ifdef Py_USING_UNICODE
Tim Peters6d6c1a32001-08-02 04:15:00 +00003326 else if (PyUnicode_Check(x))
3327 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3328 PyUnicode_GET_SIZE(x),
3329 base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003330#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +00003331 else {
3332 PyErr_SetString(PyExc_TypeError,
3333 "long() can't convert non-string with explicit base");
3334 return NULL;
3335 }
3336}
3337
Guido van Rossumbef14172001-08-29 15:47:46 +00003338/* Wimpy, slow approach to tp_new calls for subtypes of long:
3339 first create a regular long from whatever arguments we got,
3340 then allocate a subtype instance and initialize it from
3341 the regular long. The regular long is then thrown away.
3342*/
3343static PyObject *
3344long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3345{
Anthony Baxter377be112006-04-11 06:54:30 +00003346 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003347 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003348
3349 assert(PyType_IsSubtype(type, &PyLong_Type));
3350 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3351 if (tmp == NULL)
3352 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003353 assert(PyLong_CheckExact(tmp));
Martin v. Löwis68192102007-07-21 06:55:02 +00003354 n = Py_Size(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003355 if (n < 0)
3356 n = -n;
Anthony Baxter377be112006-04-11 06:54:30 +00003357 newobj = (PyLongObject *)type->tp_alloc(type, n);
3358 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003359 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003360 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003361 }
Anthony Baxter377be112006-04-11 06:54:30 +00003362 assert(PyLong_Check(newobj));
Martin v. Löwis68192102007-07-21 06:55:02 +00003363 Py_Size(newobj) = Py_Size(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003364 for (i = 0; i < n; i++)
Anthony Baxter377be112006-04-11 06:54:30 +00003365 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003366 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00003367 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003368}
3369
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003370static PyObject *
3371long_getnewargs(PyLongObject *v)
3372{
3373 return Py_BuildValue("(N)", _PyLong_Copy(v));
3374}
3375
3376static PyMethodDef long_methods[] = {
3377 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
3378 {NULL, NULL} /* sentinel */
3379};
3380
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003381PyDoc_STRVAR(long_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003382"long(x[, base]) -> integer\n\
3383\n\
3384Convert a string or number to a long integer, if possible. A floating\n\
3385point argument will be truncated towards zero (this does not include a\n\
3386string representation of a floating point number!) When converting a\n\
3387string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003388converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003389
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003390static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003391 (binaryfunc) long_add, /*nb_add*/
3392 (binaryfunc) long_sub, /*nb_subtract*/
3393 (binaryfunc) long_mul, /*nb_multiply*/
Georg Brandl347b3002006-03-30 11:57:00 +00003394 long_classic_div, /*nb_divide*/
3395 long_mod, /*nb_remainder*/
3396 long_divmod, /*nb_divmod*/
3397 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003398 (unaryfunc) long_neg, /*nb_negative*/
3399 (unaryfunc) long_pos, /*tp_positive*/
3400 (unaryfunc) long_abs, /*tp_absolute*/
3401 (inquiry) long_nonzero, /*tp_nonzero*/
3402 (unaryfunc) long_invert, /*nb_invert*/
Georg Brandl347b3002006-03-30 11:57:00 +00003403 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003404 (binaryfunc) long_rshift, /*nb_rshift*/
Georg Brandl347b3002006-03-30 11:57:00 +00003405 long_and, /*nb_and*/
3406 long_xor, /*nb_xor*/
3407 long_or, /*nb_or*/
3408 long_coerce, /*nb_coerce*/
3409 long_int, /*nb_int*/
3410 long_long, /*nb_long*/
3411 long_float, /*nb_float*/
3412 long_oct, /*nb_oct*/
3413 long_hex, /*nb_hex*/
Guido van Rossum4668b002001-08-08 05:00:18 +00003414 0, /* nb_inplace_add */
3415 0, /* nb_inplace_subtract */
3416 0, /* nb_inplace_multiply */
3417 0, /* nb_inplace_divide */
3418 0, /* nb_inplace_remainder */
3419 0, /* nb_inplace_power */
3420 0, /* nb_inplace_lshift */
3421 0, /* nb_inplace_rshift */
3422 0, /* nb_inplace_and */
3423 0, /* nb_inplace_xor */
3424 0, /* nb_inplace_or */
Georg Brandl347b3002006-03-30 11:57:00 +00003425 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003426 long_true_divide, /* nb_true_divide */
3427 0, /* nb_inplace_floor_divide */
3428 0, /* nb_inplace_true_divide */
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00003429 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003430};
3431
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003432PyTypeObject PyLong_Type = {
3433 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003434 0, /* ob_size */
3435 "long", /* tp_name */
3436 sizeof(PyLongObject) - sizeof(digit), /* tp_basicsize */
3437 sizeof(digit), /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00003438 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003439 0, /* tp_print */
3440 0, /* tp_getattr */
3441 0, /* tp_setattr */
3442 (cmpfunc)long_compare, /* tp_compare */
Georg Brandl347b3002006-03-30 11:57:00 +00003443 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003444 &long_as_number, /* tp_as_number */
3445 0, /* tp_as_sequence */
3446 0, /* tp_as_mapping */
3447 (hashfunc)long_hash, /* tp_hash */
3448 0, /* tp_call */
Georg Brandl347b3002006-03-30 11:57:00 +00003449 long_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003450 PyObject_GenericGetAttr, /* tp_getattro */
3451 0, /* tp_setattro */
3452 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00003453 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003454 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003455 long_doc, /* tp_doc */
3456 0, /* tp_traverse */
3457 0, /* tp_clear */
3458 0, /* tp_richcompare */
3459 0, /* tp_weaklistoffset */
3460 0, /* tp_iter */
3461 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003462 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003463 0, /* tp_members */
3464 0, /* tp_getset */
3465 0, /* tp_base */
3466 0, /* tp_dict */
3467 0, /* tp_descr_get */
3468 0, /* tp_descr_set */
3469 0, /* tp_dictoffset */
3470 0, /* tp_init */
3471 0, /* tp_alloc */
3472 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003473 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003474};