blob: 17aab35548f6bb6df09c24a53d2883c822be6c0c [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; \
Guido van Rossumc0b618a1997-05-02 03:12:38 +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öwis18e16552006-02-15 17:27:45 +000053 Py_ssize_t j = ABS(v->ob_size);
54 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)
Guido van Rossum4c260ff1992-01-14 18:36:43 +000059 v->ob_size = (v->ob_size < 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{
Martin v. Löwis18e16552006-02-15 17:27:45 +000069 if (size > INT_MAX) {
70 /* XXX: Fix this check when ob_size becomes ssize_t */
71 PyErr_NoMemory();
72 return NULL;
73 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +000074 return PyObject_NEW_VAR(PyLongObject, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +000075}
76
Tim Peters64b5ce32001-09-10 20:52:51 +000077PyObject *
78_PyLong_Copy(PyLongObject *src)
79{
80 PyLongObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +000081 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +000082
83 assert(src != NULL);
84 i = src->ob_size;
85 if (i < 0)
86 i = -(i);
87 result = _PyLong_New(i);
88 if (result != NULL) {
Tim Peters5329cdb2002-03-02 04:18:04 +000089 result->ob_size = src->ob_size;
Tim Peters64b5ce32001-09-10 20:52:51 +000090 while (--i >= 0)
91 result->ob_digit[i] = src->ob_digit[i];
92 }
93 return (PyObject *)result;
94}
95
Guido van Rossumedcc38a1991-05-05 20:09:44 +000096/* Create a new long int object from a C long int */
97
Guido van Rossumc0b618a1997-05-02 03:12:38 +000098PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +000099PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000100{
Tim Petersce9de2f2001-06-14 04:56:19 +0000101 PyLongObject *v;
102 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
103 int ndigits = 0;
104 int negative = 0;
105
106 if (ival < 0) {
107 ival = -ival;
108 negative = 1;
109 }
110
111 /* Count the number of Python digits.
112 We used to pick 5 ("big enough for anything"), but that's a
113 waste of time and space given that 5*15 = 75 bits are rarely
114 needed. */
115 t = (unsigned long)ival;
116 while (t) {
117 ++ndigits;
118 t >>= SHIFT;
119 }
120 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000121 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000122 digit *p = v->ob_digit;
123 v->ob_size = negative ? -ndigits : ndigits;
124 t = (unsigned long)ival;
125 while (t) {
126 *p++ = (digit)(t & MASK);
Guido van Rossum472c04f1996-12-05 21:57:21 +0000127 t >>= SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000128 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000129 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000130 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000131}
132
Guido van Rossum53756b11997-01-03 17:14:46 +0000133/* Create a new long int object from a C unsigned long int */
134
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000135PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000136PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000137{
Tim Petersce9de2f2001-06-14 04:56:19 +0000138 PyLongObject *v;
139 unsigned long t;
140 int ndigits = 0;
141
142 /* Count the number of Python digits. */
143 t = (unsigned long)ival;
144 while (t) {
145 ++ndigits;
146 t >>= SHIFT;
147 }
148 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000149 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000150 digit *p = v->ob_digit;
151 v->ob_size = ndigits;
152 while (ival) {
153 *p++ = (digit)(ival & MASK);
154 ival >>= SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000155 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000156 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000157 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000158}
159
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000160/* Create a new long int object from a C double */
161
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000162PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000163PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000164{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000165 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000166 double frac;
167 int i, ndig, expo, neg;
168 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000169 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000170 PyErr_SetString(PyExc_OverflowError,
171 "cannot convert float infinity to long");
172 return NULL;
173 }
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000174 if (dval < 0.0) {
175 neg = 1;
176 dval = -dval;
177 }
178 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
179 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000180 return PyLong_FromLong(0L);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000181 ndig = (expo-1) / SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000182 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000183 if (v == NULL)
184 return NULL;
185 frac = ldexp(frac, (expo-1) % SHIFT + 1);
186 for (i = ndig; --i >= 0; ) {
187 long bits = (long)frac;
Guido van Rossum2095d241997-04-09 19:41:24 +0000188 v->ob_digit[i] = (digit) bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000189 frac = frac - (double)bits;
190 frac = ldexp(frac, SHIFT);
191 }
192 if (neg)
Guido van Rossum4c260ff1992-01-14 18:36:43 +0000193 v->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000194 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000195}
196
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000197/* Get a C long int from a long int object.
198 Returns -1 and sets an error condition if overflow occurs. */
199
200long
Tim Peters9f688bf2000-07-07 15:53:28 +0000201PyLong_AsLong(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000202{
Guido van Rossumf7531811998-05-26 14:33:37 +0000203 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000204 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000205 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000206 Py_ssize_t i;
207 int sign;
Guido van Rossumf7531811998-05-26 14:33:37 +0000208
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000209 if (vv == NULL || !PyLong_Check(vv)) {
Guido van Rossum7e35d572001-09-15 03:14:32 +0000210 if (vv != NULL && PyInt_Check(vv))
211 return PyInt_AsLong(vv);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000212 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000213 return -1;
214 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000215 v = (PyLongObject *)vv;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000216 i = v->ob_size;
217 sign = 1;
218 x = 0;
219 if (i < 0) {
220 sign = -1;
Guido van Rossum4c260ff1992-01-14 18:36:43 +0000221 i = -(i);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000222 }
223 while (--i >= 0) {
224 prev = x;
225 x = (x << SHIFT) + v->ob_digit[i];
Guido van Rossumf7531811998-05-26 14:33:37 +0000226 if ((x >> SHIFT) != prev)
227 goto overflow;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000228 }
Guido van Rossumf7531811998-05-26 14:33:37 +0000229 /* Haven't lost any bits, but if the sign bit is set we're in
230 * trouble *unless* this is the min negative number. So,
231 * trouble iff sign bit set && (positive || some bit set other
232 * than the sign bit).
233 */
234 if ((long)x < 0 && (sign > 0 || (x << 1) != 0))
235 goto overflow;
236 return (long)x * sign;
237
238 overflow:
239 PyErr_SetString(PyExc_OverflowError,
Skip Montanarobafedec2001-09-13 19:05:30 +0000240 "long int too large to convert to int");
Guido van Rossumf7531811998-05-26 14:33:37 +0000241 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000242}
243
Martin v. Löwis18e16552006-02-15 17:27:45 +0000244/* Get a Py_ssize_t from a long int object.
245 Returns -1 and sets an error condition if overflow occurs. */
246
247Py_ssize_t
248_PyLong_AsSsize_t(PyObject *vv)
249{
250 register PyLongObject *v;
251 size_t x, prev;
252 Py_ssize_t i;
253 int sign;
254
255 if (vv == NULL || !PyLong_Check(vv)) {
256 PyErr_BadInternalCall();
257 return -1;
258 }
259 v = (PyLongObject *)vv;
260 i = v->ob_size;
261 sign = 1;
262 x = 0;
263 if (i < 0) {
264 sign = -1;
265 i = -(i);
266 }
267 while (--i >= 0) {
268 prev = x;
269 x = (x << SHIFT) + v->ob_digit[i];
270 if ((x >> SHIFT) != prev)
271 goto overflow;
272 }
273 /* Haven't lost any bits, but if the sign bit is set we're in
274 * trouble *unless* this is the min negative number. So,
275 * trouble iff sign bit set && (positive || some bit set other
276 * than the sign bit).
277 */
278 if ((Py_ssize_t)x < 0 && (sign > 0 || (x << 1) != 0))
279 goto overflow;
280 return (Py_ssize_t)x * sign;
281
282 overflow:
283 PyErr_SetString(PyExc_OverflowError,
284 "long int too large to convert to int");
285 return -1;
286}
287
Guido van Rossumd8c80482002-08-13 00:24:58 +0000288/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000289 Returns -1 and sets an error condition if overflow occurs. */
290
291unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000292PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000293{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000294 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000295 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000296 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000297
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000298 if (vv == NULL || !PyLong_Check(vv)) {
Martin v. Löwis729d47d2004-09-20 06:17:46 +0000299 if (vv != NULL && PyInt_Check(vv)) {
300 long val = PyInt_AsLong(vv);
301 if (val < 0) {
302 PyErr_SetString(PyExc_OverflowError,
303 "can't convert negative value to unsigned long");
304 return (unsigned long) -1;
305 }
306 return val;
307 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000308 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000309 return (unsigned long) -1;
310 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000311 v = (PyLongObject *)vv;
Guido van Rossum53756b11997-01-03 17:14:46 +0000312 i = v->ob_size;
313 x = 0;
314 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000315 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum53756b11997-01-03 17:14:46 +0000316 "can't convert negative value to unsigned long");
317 return (unsigned long) -1;
318 }
319 while (--i >= 0) {
320 prev = x;
321 x = (x << SHIFT) + v->ob_digit[i];
322 if ((x >> SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000323 PyErr_SetString(PyExc_OverflowError,
Fred Drake661ea262000-10-24 19:57:45 +0000324 "long int too large to convert");
Guido van Rossum53756b11997-01-03 17:14:46 +0000325 return (unsigned long) -1;
326 }
327 }
328 return x;
329}
330
Thomas Hellera4ea6032003-04-17 18:55:45 +0000331/* Get a C unsigned long int from a long int object, ignoring the high bits.
332 Returns -1 and sets an error condition if an error occurs. */
333
334unsigned long
335PyLong_AsUnsignedLongMask(PyObject *vv)
336{
337 register PyLongObject *v;
338 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000339 Py_ssize_t i;
340 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000341
342 if (vv == NULL || !PyLong_Check(vv)) {
Martin v. Löwis729d47d2004-09-20 06:17:46 +0000343 if (vv != NULL && PyInt_Check(vv))
344 return PyInt_AsUnsignedLongMask(vv);
Thomas Hellera4ea6032003-04-17 18:55:45 +0000345 PyErr_BadInternalCall();
346 return (unsigned long) -1;
347 }
348 v = (PyLongObject *)vv;
349 i = v->ob_size;
350 sign = 1;
351 x = 0;
352 if (i < 0) {
353 sign = -1;
354 i = -i;
355 }
356 while (--i >= 0) {
357 x = (x << SHIFT) + v->ob_digit[i];
358 }
359 return x * sign;
360}
361
Tim Peters5b8132f2003-01-31 15:52:05 +0000362int
363_PyLong_Sign(PyObject *vv)
364{
365 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000366
367 assert(v != NULL);
368 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000369
Tim Petersee1a53c2003-02-02 02:57:53 +0000370 return v->ob_size == 0 ? 0 : (v->ob_size < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000371}
372
Tim Petersbaefd9e2003-01-28 20:37:45 +0000373size_t
374_PyLong_NumBits(PyObject *vv)
375{
376 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000377 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000378 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000379
380 assert(v != NULL);
381 assert(PyLong_Check(v));
Guido van Rossum004a65c2003-02-03 15:28:19 +0000382 ndigits = ABS(v->ob_size);
Tim Petersbaefd9e2003-01-28 20:37:45 +0000383 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
384 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000385 digit msd = v->ob_digit[ndigits - 1];
386
Tim Peters5b8132f2003-01-31 15:52:05 +0000387 result = (ndigits - 1) * SHIFT;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000388 if (result / SHIFT != ndigits - 1)
Tim Petersbaefd9e2003-01-28 20:37:45 +0000389 goto Overflow;
390 do {
391 ++result;
392 if (result == 0)
393 goto Overflow;
394 msd >>= 1;
395 } while (msd);
396 }
397 return result;
398
399Overflow:
400 PyErr_SetString(PyExc_OverflowError, "long has too many bits "
401 "to express in a platform size_t");
402 return (size_t)-1;
403}
404
Tim Peters2a9b3672001-06-11 21:23:58 +0000405PyObject *
406_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
407 int little_endian, int is_signed)
408{
409 const unsigned char* pstartbyte;/* LSB of bytes */
410 int incr; /* direction to move pstartbyte */
411 const unsigned char* pendbyte; /* MSB of bytes */
412 size_t numsignificantbytes; /* number of bytes that matter */
413 size_t ndigits; /* number of Python long digits */
414 PyLongObject* v; /* result */
415 int idigit = 0; /* next free index in v->ob_digit */
416
417 if (n == 0)
418 return PyLong_FromLong(0L);
419
420 if (little_endian) {
421 pstartbyte = bytes;
422 pendbyte = bytes + n - 1;
423 incr = 1;
424 }
425 else {
426 pstartbyte = bytes + n - 1;
427 pendbyte = bytes;
428 incr = -1;
429 }
430
431 if (is_signed)
432 is_signed = *pendbyte >= 0x80;
433
434 /* Compute numsignificantbytes. This consists of finding the most
435 significant byte. Leading 0 bytes are insignficant if the number
436 is positive, and leading 0xff bytes if negative. */
437 {
438 size_t i;
439 const unsigned char* p = pendbyte;
440 const int pincr = -incr; /* search MSB to LSB */
441 const unsigned char insignficant = is_signed ? 0xff : 0x00;
442
443 for (i = 0; i < n; ++i, p += pincr) {
444 if (*p != insignficant)
445 break;
446 }
447 numsignificantbytes = n - i;
448 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
449 actually has 2 significant bytes. OTOH, 0xff0001 ==
450 -0x00ffff, so we wouldn't *need* to bump it there; but we
451 do for 0xffff = -0x0001. To be safe without bothering to
452 check every case, bump it regardless. */
453 if (is_signed && numsignificantbytes < n)
454 ++numsignificantbytes;
455 }
456
457 /* How many Python long digits do we need? We have
458 8*numsignificantbytes bits, and each Python long digit has SHIFT
459 bits, so it's the ceiling of the quotient. */
460 ndigits = (numsignificantbytes * 8 + SHIFT - 1) / SHIFT;
461 if (ndigits > (size_t)INT_MAX)
462 return PyErr_NoMemory();
463 v = _PyLong_New((int)ndigits);
464 if (v == NULL)
465 return NULL;
466
467 /* Copy the bits over. The tricky parts are computing 2's-comp on
468 the fly for signed numbers, and dealing with the mismatch between
469 8-bit bytes and (probably) 15-bit Python digits.*/
470 {
471 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000472 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000473 twodigits accum = 0; /* sliding register */
474 unsigned int accumbits = 0; /* number of bits in accum */
475 const unsigned char* p = pstartbyte;
476
477 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000478 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000479 /* Compute correction for 2's comp, if needed. */
480 if (is_signed) {
481 thisbyte = (0xff ^ thisbyte) + carry;
482 carry = thisbyte >> 8;
483 thisbyte &= 0xff;
484 }
485 /* Because we're going LSB to MSB, thisbyte is
486 more significant than what's already in accum,
487 so needs to be prepended to accum. */
488 accum |= thisbyte << accumbits;
489 accumbits += 8;
490 if (accumbits >= SHIFT) {
491 /* There's enough to fill a Python digit. */
492 assert(idigit < (int)ndigits);
493 v->ob_digit[idigit] = (digit)(accum & MASK);
494 ++idigit;
495 accum >>= SHIFT;
496 accumbits -= SHIFT;
497 assert(accumbits < SHIFT);
498 }
499 }
500 assert(accumbits < SHIFT);
501 if (accumbits) {
502 assert(idigit < (int)ndigits);
503 v->ob_digit[idigit] = (digit)accum;
504 ++idigit;
505 }
506 }
507
508 v->ob_size = is_signed ? -idigit : idigit;
509 return (PyObject *)long_normalize(v);
510}
511
512int
513_PyLong_AsByteArray(PyLongObject* v,
514 unsigned char* bytes, size_t n,
515 int little_endian, int is_signed)
516{
517 int i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000518 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000519 twodigits accum; /* sliding register */
520 unsigned int accumbits; /* # bits in accum */
521 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
522 twodigits carry; /* for computing 2's-comp */
523 size_t j; /* # bytes filled */
524 unsigned char* p; /* pointer to next byte in bytes */
525 int pincr; /* direction to move p */
526
527 assert(v != NULL && PyLong_Check(v));
528
529 if (v->ob_size < 0) {
530 ndigits = -(v->ob_size);
531 if (!is_signed) {
532 PyErr_SetString(PyExc_TypeError,
533 "can't convert negative long to unsigned");
534 return -1;
535 }
536 do_twos_comp = 1;
537 }
538 else {
539 ndigits = v->ob_size;
540 do_twos_comp = 0;
541 }
542
543 if (little_endian) {
544 p = bytes;
545 pincr = 1;
546 }
547 else {
548 p = bytes + n - 1;
549 pincr = -1;
550 }
551
Tim Peters898cf852001-06-13 20:50:08 +0000552 /* Copy over all the Python digits.
553 It's crucial that every Python digit except for the MSD contribute
554 exactly SHIFT bits to the total, so first assert that the long is
555 normalized. */
556 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000557 j = 0;
558 accum = 0;
559 accumbits = 0;
560 carry = do_twos_comp ? 1 : 0;
561 for (i = 0; i < ndigits; ++i) {
562 twodigits thisdigit = v->ob_digit[i];
563 if (do_twos_comp) {
564 thisdigit = (thisdigit ^ MASK) + carry;
565 carry = thisdigit >> SHIFT;
566 thisdigit &= MASK;
567 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000568 /* Because we're going LSB to MSB, thisdigit is more
569 significant than what's already in accum, so needs to be
570 prepended to accum. */
571 accum |= thisdigit << accumbits;
Tim Petersede05092001-06-14 08:53:38 +0000572 accumbits += SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000573
Tim Petersede05092001-06-14 08:53:38 +0000574 /* The most-significant digit may be (probably is) at least
575 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000576 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000577 /* Count # of sign bits -- they needn't be stored,
578 * although for signed conversion we need later to
579 * make sure at least one sign bit gets stored.
580 * First shift conceptual sign bit to real sign bit.
581 */
582 stwodigits s = (stwodigits)(thisdigit <<
583 (8*sizeof(stwodigits) - SHIFT));
Tim Peters7a3bfc32001-06-12 01:22:22 +0000584 unsigned int nsignbits = 0;
Tim Petersede05092001-06-14 08:53:38 +0000585 while ((s < 0) == do_twos_comp && nsignbits < SHIFT) {
Tim Peters7a3bfc32001-06-12 01:22:22 +0000586 ++nsignbits;
Tim Petersede05092001-06-14 08:53:38 +0000587 s <<= 1;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000588 }
Tim Petersede05092001-06-14 08:53:38 +0000589 accumbits -= nsignbits;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000590 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000591
Tim Peters2a9b3672001-06-11 21:23:58 +0000592 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000593 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000594 if (j >= n)
595 goto Overflow;
596 ++j;
597 *p = (unsigned char)(accum & 0xff);
598 p += pincr;
599 accumbits -= 8;
600 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000601 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000602 }
603
604 /* Store the straggler (if any). */
605 assert(accumbits < 8);
606 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000607 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000608 if (j >= n)
609 goto Overflow;
610 ++j;
611 if (do_twos_comp) {
612 /* Fill leading bits of the byte with sign bits
613 (appropriately pretending that the long had an
614 infinite supply of sign bits). */
615 accum |= (~(twodigits)0) << accumbits;
616 }
617 *p = (unsigned char)(accum & 0xff);
618 p += pincr;
619 }
Tim Peters05607ad2001-06-13 21:01:27 +0000620 else if (j == n && n > 0 && is_signed) {
621 /* The main loop filled the byte array exactly, so the code
622 just above didn't get to ensure there's a sign bit, and the
623 loop below wouldn't add one either. Make sure a sign bit
624 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000625 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000626 int sign_bit_set = msb >= 0x80;
627 assert(accumbits == 0);
628 if (sign_bit_set == do_twos_comp)
629 return 0;
630 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000631 goto Overflow;
632 }
Tim Peters05607ad2001-06-13 21:01:27 +0000633
634 /* Fill remaining bytes with copies of the sign bit. */
635 {
636 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
637 for ( ; j < n; ++j, p += pincr)
638 *p = signbyte;
639 }
640
Tim Peters2a9b3672001-06-11 21:23:58 +0000641 return 0;
642
643Overflow:
644 PyErr_SetString(PyExc_OverflowError, "long too big to convert");
645 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000646
Tim Peters2a9b3672001-06-11 21:23:58 +0000647}
648
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000649double
650_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
651{
652/* NBITS_WANTED should be > the number of bits in a double's precision,
653 but small enough so that 2**NBITS_WANTED is within the normal double
654 range. nbitsneeded is set to 1 less than that because the most-significant
655 Python digit contains at least 1 significant bit, but we don't want to
656 bother counting them (catering to the worst case cheaply).
657
658 57 is one more than VAX-D double precision; I (Tim) don't know of a double
659 format with more precision than that; it's 1 larger so that we add in at
660 least one round bit to stand in for the ignored least-significant bits.
661*/
662#define NBITS_WANTED 57
663 PyLongObject *v;
664 double x;
665 const double multiplier = (double)(1L << SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000666 Py_ssize_t i;
667 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000668 int nbitsneeded;
669
670 if (vv == NULL || !PyLong_Check(vv)) {
671 PyErr_BadInternalCall();
672 return -1;
673 }
674 v = (PyLongObject *)vv;
675 i = v->ob_size;
676 sign = 1;
677 if (i < 0) {
678 sign = -1;
679 i = -(i);
680 }
681 else if (i == 0) {
682 *exponent = 0;
683 return 0.0;
684 }
685 --i;
686 x = (double)v->ob_digit[i];
687 nbitsneeded = NBITS_WANTED - 1;
688 /* Invariant: i Python digits remain unaccounted for. */
689 while (i > 0 && nbitsneeded > 0) {
690 --i;
691 x = x * multiplier + (double)v->ob_digit[i];
692 nbitsneeded -= SHIFT;
693 }
694 /* There are i digits we didn't shift in. Pretending they're all
695 zeroes, the true value is x * 2**(i*SHIFT). */
696 *exponent = i;
697 assert(x > 0.0);
698 return x * sign;
699#undef NBITS_WANTED
700}
701
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000702/* Get a C double from a long int object. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000703
704double
Tim Peters9f688bf2000-07-07 15:53:28 +0000705PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000706{
Thomas Wouters553489a2006-02-01 21:32:04 +0000707 int e = -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000708 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000709
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000710 if (vv == NULL || !PyLong_Check(vv)) {
711 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000712 return -1;
713 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000714 x = _PyLong_AsScaledDouble(vv, &e);
715 if (x == -1.0 && PyErr_Occurred())
716 return -1.0;
Thomas Wouters553489a2006-02-01 21:32:04 +0000717 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
718 set correctly after a successful _PyLong_AsScaledDouble() call */
719 assert(e >= 0);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000720 if (e > INT_MAX / SHIFT)
721 goto overflow;
722 errno = 0;
723 x = ldexp(x, e * SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +0000724 if (Py_OVERFLOWED(x))
Tim Peters9fffa3e2001-09-04 05:14:19 +0000725 goto overflow;
726 return x;
727
728overflow:
729 PyErr_SetString(PyExc_OverflowError,
730 "long int too large to convert to float");
731 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000732}
733
Guido van Rossum78694d91998-09-18 14:14:13 +0000734/* Create a new long (or int) object from a C pointer */
735
736PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000737PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000738{
Tim Peters70128a12001-06-16 08:48:40 +0000739#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +0000740 return PyInt_FromLong((long)p);
741#else
Guido van Rossum78694d91998-09-18 14:14:13 +0000742
Tim Peters70128a12001-06-16 08:48:40 +0000743#ifndef HAVE_LONG_LONG
744# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
745#endif
746#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000747# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000748#endif
749 /* optimize null pointers */
750 if (p == NULL)
751 return PyInt_FromLong(0);
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000752 return PyLong_FromLongLong((PY_LONG_LONG)p);
Tim Peters70128a12001-06-16 08:48:40 +0000753
754#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000755}
756
757/* Get a C pointer from a long object (or an int object in some cases) */
758
759void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000760PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000761{
762 /* This function will allow int or long objects. If vv is neither,
763 then the PyLong_AsLong*() functions will raise the exception:
764 PyExc_SystemError, "bad argument to internal function"
765 */
Tim Peters70128a12001-06-16 08:48:40 +0000766#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +0000767 long x;
768
Tim Peters70128a12001-06-16 08:48:40 +0000769 if (PyInt_Check(vv))
Guido van Rossum78694d91998-09-18 14:14:13 +0000770 x = PyInt_AS_LONG(vv);
771 else
772 x = PyLong_AsLong(vv);
773#else
Tim Peters70128a12001-06-16 08:48:40 +0000774
775#ifndef HAVE_LONG_LONG
776# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
777#endif
778#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000779# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000780#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000781 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000782
Tim Peters70128a12001-06-16 08:48:40 +0000783 if (PyInt_Check(vv))
Guido van Rossum78694d91998-09-18 14:14:13 +0000784 x = PyInt_AS_LONG(vv);
785 else
786 x = PyLong_AsLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000787
788#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000789
790 if (x == -1 && PyErr_Occurred())
791 return NULL;
792 return (void *)x;
793}
794
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000795#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000796
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000797/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000798 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000799 */
800
Tim Peterscf37dfc2001-06-14 18:42:50 +0000801#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +0000802
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000803/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000804
805PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000806PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000807{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000808 PY_LONG_LONG bytes = ival;
Tim Petersd1a7da62001-06-13 00:35:57 +0000809 int one = 1;
810 return _PyLong_FromByteArray(
811 (unsigned char *)&bytes,
812 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000813}
814
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000815/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +0000816
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000817PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000818PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000819{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000820 unsigned PY_LONG_LONG bytes = ival;
Tim Petersd1a7da62001-06-13 00:35:57 +0000821 int one = 1;
822 return _PyLong_FromByteArray(
823 (unsigned char *)&bytes,
824 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000825}
826
Martin v. Löwis18e16552006-02-15 17:27:45 +0000827/* Create a new long int object from a C Py_ssize_t. */
828
829PyObject *
830_PyLong_FromSsize_t(Py_ssize_t ival)
831{
832 Py_ssize_t bytes = ival;
833 int one = 1;
834 return _PyLong_FromByteArray(
835 (unsigned char *)&bytes,
836 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
837}
838
839/* Create a new long int object from a C size_t. */
840
841PyObject *
842_PyLong_FromSize_t(size_t ival)
843{
844 size_t bytes = ival;
845 int one = 1;
846 return _PyLong_FromByteArray(
847 (unsigned char *)&bytes,
848 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
849}
850
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000851/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000852 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000853
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000854PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000855PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000856{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000857 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +0000858 int one = 1;
859 int res;
860
Tim Petersd38b1c72001-09-30 05:09:37 +0000861 if (vv == NULL) {
862 PyErr_BadInternalCall();
863 return -1;
864 }
865 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +0000866 PyNumberMethods *nb;
867 PyObject *io;
Tim Petersd38b1c72001-09-30 05:09:37 +0000868 if (PyInt_Check(vv))
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000869 return (PY_LONG_LONG)PyInt_AsLong(vv);
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +0000870 if ((nb = vv->ob_type->tp_as_number) == NULL ||
871 nb->nb_int == NULL) {
872 PyErr_SetString(PyExc_TypeError, "an integer is required");
873 return -1;
874 }
875 io = (*nb->nb_int) (vv);
876 if (io == NULL)
877 return -1;
878 if (PyInt_Check(io)) {
879 bytes = PyInt_AsLong(io);
880 Py_DECREF(io);
881 return bytes;
882 }
883 if (PyLong_Check(io)) {
884 bytes = PyLong_AsLongLong(io);
885 Py_DECREF(io);
886 return bytes;
887 }
888 Py_DECREF(io);
889 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000890 return -1;
891 }
892
Tim Petersd1a7da62001-06-13 00:35:57 +0000893 res = _PyLong_AsByteArray(
894 (PyLongObject *)vv, (unsigned char *)&bytes,
895 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000896
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000897 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000898 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000899 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000900 else
901 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000902}
903
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000904/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000905 Return -1 and set an error if overflow occurs. */
906
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000907unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000908PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000909{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000910 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +0000911 int one = 1;
912 int res;
913
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000914 if (vv == NULL || !PyLong_Check(vv)) {
915 PyErr_BadInternalCall();
Tim Petersd1a7da62001-06-13 00:35:57 +0000916 return -1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000917 }
918
Tim Petersd1a7da62001-06-13 00:35:57 +0000919 res = _PyLong_AsByteArray(
920 (PyLongObject *)vv, (unsigned char *)&bytes,
921 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000922
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000923 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000924 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000925 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000926 else
927 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000928}
Tim Petersd1a7da62001-06-13 00:35:57 +0000929
Thomas Hellera4ea6032003-04-17 18:55:45 +0000930/* Get a C unsigned long int from a long int object, ignoring the high bits.
931 Returns -1 and sets an error condition if an error occurs. */
932
933unsigned PY_LONG_LONG
934PyLong_AsUnsignedLongLongMask(PyObject *vv)
935{
936 register PyLongObject *v;
937 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000938 Py_ssize_t i;
939 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000940
941 if (vv == NULL || !PyLong_Check(vv)) {
942 PyErr_BadInternalCall();
943 return (unsigned long) -1;
944 }
945 v = (PyLongObject *)vv;
946 i = v->ob_size;
947 sign = 1;
948 x = 0;
949 if (i < 0) {
950 sign = -1;
951 i = -i;
952 }
953 while (--i >= 0) {
954 x = (x << SHIFT) + v->ob_digit[i];
955 }
956 return x * sign;
957}
Tim Petersd1a7da62001-06-13 00:35:57 +0000958#undef IS_LITTLE_ENDIAN
959
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000960#endif /* HAVE_LONG_LONG */
961
Neil Schemenauerba872e22001-01-04 01:46:03 +0000962
963static int
964convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) {
Tim Peters5af4e6c2002-08-12 02:31:19 +0000965 if (PyLong_Check(v)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +0000966 *a = (PyLongObject *) v;
967 Py_INCREF(v);
968 }
969 else if (PyInt_Check(v)) {
970 *a = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(v));
971 }
972 else {
973 return 0;
974 }
Tim Peters5af4e6c2002-08-12 02:31:19 +0000975 if (PyLong_Check(w)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +0000976 *b = (PyLongObject *) w;
977 Py_INCREF(w);
978 }
979 else if (PyInt_Check(w)) {
980 *b = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(w));
981 }
982 else {
983 Py_DECREF(*a);
984 return 0;
985 }
986 return 1;
987}
988
989#define CONVERT_BINOP(v, w, a, b) \
990 if (!convert_binop(v, w, a, b)) { \
991 Py_INCREF(Py_NotImplemented); \
992 return Py_NotImplemented; \
993 }
994
Tim Peters877a2122002-08-12 05:09:36 +0000995/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
996 * is modified in place, by adding y to it. Carries are propagated as far as
997 * x[m-1], and the remaining carry (0 or 1) is returned.
998 */
999static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001000v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001001{
1002 int i;
1003 digit carry = 0;
1004
1005 assert(m >= n);
1006 for (i = 0; i < n; ++i) {
1007 carry += x[i] + y[i];
1008 x[i] = carry & MASK;
1009 carry >>= SHIFT;
1010 assert((carry & 1) == carry);
1011 }
1012 for (; carry && i < m; ++i) {
1013 carry += x[i];
1014 x[i] = carry & MASK;
1015 carry >>= SHIFT;
1016 assert((carry & 1) == carry);
1017 }
1018 return carry;
1019}
1020
1021/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1022 * is modified in place, by subtracting y from it. Borrows are propagated as
1023 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1024 */
1025static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001026v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001027{
1028 int i;
1029 digit borrow = 0;
1030
1031 assert(m >= n);
1032 for (i = 0; i < n; ++i) {
1033 borrow = x[i] - y[i] - borrow;
1034 x[i] = borrow & MASK;
1035 borrow >>= SHIFT;
1036 borrow &= 1; /* keep only 1 sign bit */
1037 }
1038 for (; borrow && i < m; ++i) {
1039 borrow = x[i] - borrow;
1040 x[i] = borrow & MASK;
1041 borrow >>= SHIFT;
1042 borrow &= 1;
1043 }
1044 return borrow;
1045}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001046
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001047/* Multiply by a single digit, ignoring the sign. */
1048
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001049static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001050mul1(PyLongObject *a, wdigit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001051{
1052 return muladd1(a, n, (digit)0);
1053}
1054
1055/* Multiply by a single digit and add a single digit, ignoring the sign. */
1056
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001057static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001058muladd1(PyLongObject *a, wdigit n, wdigit extra)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001059{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001060 Py_ssize_t size_a = ABS(a->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001061 PyLongObject *z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001062 twodigits carry = extra;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001063 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001064
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001065 if (z == NULL)
1066 return NULL;
1067 for (i = 0; i < size_a; ++i) {
1068 carry += (twodigits)a->ob_digit[i] * n;
Guido van Rossum2095d241997-04-09 19:41:24 +00001069 z->ob_digit[i] = (digit) (carry & MASK);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001070 carry >>= SHIFT;
1071 }
Guido van Rossum2095d241997-04-09 19:41:24 +00001072 z->ob_digit[i] = (digit) carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001073 return long_normalize(z);
1074}
1075
Tim Peters212e6142001-07-14 12:23:19 +00001076/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1077 in pout, and returning the remainder. pin and pout point at the LSD.
1078 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
1079 long_format, but that should be done with great care since longs are
1080 immutable. */
1081
1082static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001083inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001084{
1085 twodigits rem = 0;
1086
1087 assert(n > 0 && n <= MASK);
1088 pin += size;
1089 pout += size;
1090 while (--size >= 0) {
1091 digit hi;
1092 rem = (rem << SHIFT) + *--pin;
1093 *--pout = hi = (digit)(rem / n);
1094 rem -= hi * n;
1095 }
1096 return (digit)rem;
1097}
1098
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001099/* Divide a long integer by a digit, returning both the quotient
1100 (as function result) and the remainder (through *prem).
1101 The sign of a is ignored; n should not be zero. */
1102
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001103static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001104divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001105{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001106 const Py_ssize_t size = ABS(a->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001107 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001108
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001109 assert(n > 0 && n <= MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001110 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001111 if (z == NULL)
1112 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001113 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001114 return long_normalize(z);
1115}
1116
1117/* Convert a long int object to a string, using a given conversion base.
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001118 Return a string object.
Fred Drake121ee271999-12-23 15:41:28 +00001119 If base is 8 or 16, add the proper prefix '0' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001120
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001121static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001122long_format(PyObject *aa, int base, int addL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001123{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001124 register PyLongObject *a = (PyLongObject *)aa;
1125 PyStringObject *str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001126 Py_ssize_t i;
1127 const Py_ssize_t size_a = ABS(a->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001128 char *p;
1129 int bits;
1130 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001131
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001132 if (a == NULL || !PyLong_Check(a)) {
1133 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001134 return NULL;
1135 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001136 assert(base >= 2 && base <= 36);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001137
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001138 /* Compute a rough upper bound for the length of the string */
1139 i = base;
1140 bits = 0;
1141 while (i > 1) {
1142 ++bits;
1143 i >>= 1;
1144 }
Fred Drake121ee271999-12-23 15:41:28 +00001145 i = 5 + (addL ? 1 : 0) + (size_a*SHIFT + bits-1) / bits;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001146 str = (PyStringObject *) PyString_FromStringAndSize((char *)0, i);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001147 if (str == NULL)
1148 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001149 p = PyString_AS_STRING(str) + i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001150 *p = '\0';
Fred Drake121ee271999-12-23 15:41:28 +00001151 if (addL)
1152 *--p = 'L';
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001153 if (a->ob_size < 0)
1154 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001155
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001156 if (a->ob_size == 0) {
1157 *--p = '0';
1158 }
1159 else if ((base & (base - 1)) == 0) {
1160 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001161 twodigits accum = 0;
1162 int accumbits = 0; /* # of bits in accum */
1163 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001164 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001165 while ((i >>= 1) > 1)
1166 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001167
1168 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001169 accum |= (twodigits)a->ob_digit[i] << accumbits;
Tim Peters586b2e32001-07-15 09:11:14 +00001170 accumbits += SHIFT;
1171 assert(accumbits >= basebits);
1172 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001173 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001174 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001175 assert(p > PyString_AS_STRING(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001176 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001177 accumbits -= basebits;
1178 accum >>= basebits;
1179 } while (i < size_a-1 ? accumbits >= basebits :
1180 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001181 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001182 }
1183 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001184 /* Not 0, and base not a power of 2. Divide repeatedly by
1185 base, but for speed use the highest power of base that
1186 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001187 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001188 digit *pin = a->ob_digit;
1189 PyLongObject *scratch;
1190 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001191 digit powbase = base; /* powbase == base ** power */
1192 int power = 1;
1193 for (;;) {
1194 unsigned long newpow = powbase * (unsigned long)base;
1195 if (newpow >> SHIFT) /* doesn't fit in a digit */
1196 break;
1197 powbase = (digit)newpow;
1198 ++power;
1199 }
Tim Peters212e6142001-07-14 12:23:19 +00001200
1201 /* Get a scratch area for repeated division. */
1202 scratch = _PyLong_New(size);
1203 if (scratch == NULL) {
1204 Py_DECREF(str);
1205 return NULL;
1206 }
1207
1208 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001209 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001210 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001211 digit rem = inplace_divrem1(scratch->ob_digit,
1212 pin, size, powbase);
1213 pin = scratch->ob_digit; /* no need to use a again */
1214 if (pin[size - 1] == 0)
1215 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001216 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001217 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001218 Py_DECREF(str);
1219 return NULL;
1220 })
Tim Peters212e6142001-07-14 12:23:19 +00001221
1222 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001223 assert(ntostore > 0);
1224 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001225 digit nextrem = (digit)(rem / base);
1226 char c = (char)(rem - nextrem * base);
1227 assert(p > PyString_AS_STRING(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001228 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001229 *--p = c;
1230 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001231 --ntostore;
1232 /* Termination is a bit delicate: must not
1233 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001234 remaining quotient and rem are both 0. */
1235 } while (ntostore && (size || rem));
1236 } while (size != 0);
1237 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001238 }
1239
Guido van Rossum2c475421992-08-14 15:13:07 +00001240 if (base == 8) {
1241 if (size_a != 0)
1242 *--p = '0';
1243 }
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001244 else if (base == 16) {
1245 *--p = 'x';
1246 *--p = '0';
1247 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001248 else if (base != 10) {
1249 *--p = '#';
1250 *--p = '0' + base%10;
1251 if (base > 10)
1252 *--p = '0' + base/10;
1253 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001254 if (sign)
1255 *--p = sign;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001256 if (p != PyString_AS_STRING(str)) {
1257 char *q = PyString_AS_STRING(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001258 assert(p > q);
1259 do {
1260 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001261 q--;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001262 _PyString_Resize((PyObject **)&str,
1263 (int) (q - PyString_AS_STRING(str)));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001264 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001265 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001266}
1267
Tim Petersbf2674b2003-02-02 07:51:32 +00001268/* *str points to the first digit in a string of base base digits. base
1269 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1270 * non-digit (which may be *str!). A normalized long is returned.
1271 * The point to this routine is that it takes time linear in the number of
1272 * string characters.
1273 */
1274static PyLongObject *
1275long_from_binary_base(char **str, int base)
1276{
1277 char *p = *str;
1278 char *start = p;
1279 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001280 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001281 PyLongObject *z;
1282 twodigits accum;
1283 int bits_in_accum;
1284 digit *pdigit;
1285
1286 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1287 n = base;
1288 for (bits_per_char = -1; n; ++bits_per_char)
1289 n >>= 1;
1290 /* n <- total # of bits needed, while setting p to end-of-string */
1291 n = 0;
1292 for (;;) {
1293 int k = -1;
1294 char ch = *p;
1295
1296 if (ch <= '9')
1297 k = ch - '0';
1298 else if (ch >= 'a')
1299 k = ch - 'a' + 10;
1300 else if (ch >= 'A')
1301 k = ch - 'A' + 10;
1302 if (k < 0 || k >= base)
1303 break;
Tim Petersbf2674b2003-02-02 07:51:32 +00001304 ++p;
1305 }
1306 *str = p;
Tim Peters1a3b19a2003-02-02 17:33:53 +00001307 n = (p - start) * bits_per_char;
1308 if (n / bits_per_char != p - start) {
1309 PyErr_SetString(PyExc_ValueError,
1310 "long string too large to convert");
1311 return NULL;
1312 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001313 /* n <- # of Python digits needed, = ceiling(n/SHIFT). */
1314 n = (n + SHIFT - 1) / SHIFT;
1315 z = _PyLong_New(n);
1316 if (z == NULL)
1317 return NULL;
1318 /* Read string from right, and fill in long from left; i.e.,
1319 * from least to most significant in both.
1320 */
1321 accum = 0;
1322 bits_in_accum = 0;
1323 pdigit = z->ob_digit;
1324 while (--p >= start) {
Tim Petersc7bc0b92003-05-05 20:39:43 +00001325 int k;
1326 char ch = *p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001327
1328 if (ch <= '9')
1329 k = ch - '0';
1330 else if (ch >= 'a')
1331 k = ch - 'a' + 10;
1332 else {
1333 assert(ch >= 'A');
1334 k = ch - 'A' + 10;
1335 }
Tim Petersc7bc0b92003-05-05 20:39:43 +00001336 assert(k >= 0 && k < base);
1337 accum |= (twodigits)(k << bits_in_accum);
Tim Petersbf2674b2003-02-02 07:51:32 +00001338 bits_in_accum += bits_per_char;
1339 if (bits_in_accum >= SHIFT) {
1340 *pdigit++ = (digit)(accum & MASK);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001341 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001342 accum >>= SHIFT;
1343 bits_in_accum -= SHIFT;
1344 assert(bits_in_accum < SHIFT);
1345 }
1346 }
1347 if (bits_in_accum) {
1348 assert(bits_in_accum <= SHIFT);
1349 *pdigit++ = (digit)accum;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001350 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001351 }
1352 while (pdigit - z->ob_digit < n)
1353 *pdigit++ = 0;
1354 return long_normalize(z);
1355}
1356
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001357PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001358PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001359{
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001360 int sign = 1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001361 char *start, *orig_str = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001362 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001363
Guido van Rossum472c04f1996-12-05 21:57:21 +00001364 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001365 PyErr_SetString(PyExc_ValueError,
Fred Drake661ea262000-10-24 19:57:45 +00001366 "long() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001367 return NULL;
1368 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001369 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001370 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001371 if (*str == '+')
1372 ++str;
1373 else if (*str == '-') {
1374 ++str;
1375 sign = -1;
1376 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001377 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001378 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001379 if (base == 0) {
1380 if (str[0] != '0')
1381 base = 10;
1382 else if (str[1] == 'x' || str[1] == 'X')
1383 base = 16;
1384 else
1385 base = 8;
1386 }
1387 if (base == 16 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
1388 str += 2;
Guido van Rossume6762971998-06-22 03:54:46 +00001389 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001390 if ((base & (base - 1)) == 0)
1391 z = long_from_binary_base(&str, base);
1392 else {
1393 z = _PyLong_New(0);
1394 for ( ; z != NULL; ++str) {
1395 int k = -1;
1396 PyLongObject *temp;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001397
Tim Petersbf2674b2003-02-02 07:51:32 +00001398 if (*str <= '9')
1399 k = *str - '0';
1400 else if (*str >= 'a')
1401 k = *str - 'a' + 10;
1402 else if (*str >= 'A')
1403 k = *str - 'A' + 10;
1404 if (k < 0 || k >= base)
1405 break;
1406 temp = muladd1(z, (digit)base, (digit)k);
1407 Py_DECREF(z);
1408 z = temp;
1409 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001410 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001411 if (z == NULL)
1412 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001413 if (str == start)
1414 goto onError;
Guido van Rossumc6913e71991-11-19 20:26:46 +00001415 if (sign < 0 && z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001416 z->ob_size = -(z->ob_size);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001417 if (*str == 'L' || *str == 'l')
1418 str++;
1419 while (*str && isspace(Py_CHARMASK(*str)))
1420 str++;
1421 if (*str != '\0')
1422 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001423 if (pend)
1424 *pend = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001425 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001426
1427 onError:
Tim Peters5af4e6c2002-08-12 02:31:19 +00001428 PyErr_Format(PyExc_ValueError,
Guido van Rossum9e896b32000-04-05 20:11:21 +00001429 "invalid literal for long(): %.200s", orig_str);
1430 Py_XDECREF(z);
1431 return NULL;
1432}
1433
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001434#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +00001435PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001436PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001437{
Walter Dörwald07e14762002-11-06 16:15:14 +00001438 PyObject *result;
1439 char *buffer = PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001440
Walter Dörwald07e14762002-11-06 16:15:14 +00001441 if (buffer == NULL)
1442 return NULL;
1443
1444 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1445 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001446 return NULL;
1447 }
Walter Dörwald07e14762002-11-06 16:15:14 +00001448 result = PyLong_FromString(buffer, NULL, base);
1449 PyMem_FREE(buffer);
1450 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001451}
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001452#endif
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001453
Tim Peters9f688bf2000-07-07 15:53:28 +00001454/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001455static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00001456 (PyLongObject *, PyLongObject *, PyLongObject **);
1457static PyObject *long_pos(PyLongObject *);
1458static int long_divrem(PyLongObject *, PyLongObject *,
1459 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001460
1461/* Long division with remainder, top-level routine */
1462
Guido van Rossume32e0141992-01-19 16:31:05 +00001463static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001464long_divrem(PyLongObject *a, PyLongObject *b,
1465 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001466{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001467 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001468 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001469
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001470 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001471 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +00001472 "long division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00001473 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001474 }
1475 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00001476 (size_a == size_b &&
1477 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001478 /* |a| < |b|. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001479 *pdiv = _PyLong_New(0);
1480 Py_INCREF(a);
1481 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00001482 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001483 }
1484 if (size_b == 1) {
1485 digit rem = 0;
1486 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001487 if (z == NULL)
1488 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001489 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001490 }
Guido van Rossume32e0141992-01-19 16:31:05 +00001491 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001492 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001493 if (z == NULL)
1494 return -1;
1495 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001496 /* Set the signs.
1497 The quotient z has the sign of a*b;
1498 the remainder r has the sign of a,
1499 so a = b*z + r. */
Guido van Rossume32e0141992-01-19 16:31:05 +00001500 if ((a->ob_size < 0) != (b->ob_size < 0))
1501 z->ob_size = -(z->ob_size);
1502 if (a->ob_size < 0 && (*prem)->ob_size != 0)
1503 (*prem)->ob_size = -((*prem)->ob_size);
1504 *pdiv = z;
1505 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001506}
1507
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001508/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001509
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001510static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001511x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001512{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001513 Py_ssize_t size_v = ABS(v1->ob_size), size_w = ABS(w1->ob_size);
Guido van Rossum2095d241997-04-09 19:41:24 +00001514 digit d = (digit) ((twodigits)BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001515 PyLongObject *v = mul1(v1, d);
1516 PyLongObject *w = mul1(w1, d);
1517 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001518 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001519
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001520 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001521 Py_XDECREF(v);
1522 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001523 return NULL;
1524 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001525
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001526 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001527 assert(v->ob_refcnt == 1); /* Since v will be used as accumulator! */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001528 assert(size_w == ABS(w->ob_size)); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00001529
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001530 size_v = ABS(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001531 a = _PyLong_New(size_v - size_w + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001532
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001533 for (j = size_v, k = a->ob_size-1; a != NULL && k >= 0; --j, --k) {
1534 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
1535 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001536 stwodigits carry = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001537 int i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001538
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001539 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001540 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001541 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001542 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001543 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001544 if (vj == w->ob_digit[size_w-1])
1545 q = MASK;
1546 else
1547 q = (((twodigits)vj << SHIFT) + v->ob_digit[j-1]) /
1548 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00001549
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001550 while (w->ob_digit[size_w-2]*q >
1551 ((
1552 ((twodigits)vj << SHIFT)
1553 + v->ob_digit[j-1]
1554 - q*w->ob_digit[size_w-1]
1555 ) << SHIFT)
1556 + v->ob_digit[j-2])
1557 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001558
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001559 for (i = 0; i < size_w && i+k < size_v; ++i) {
1560 twodigits z = w->ob_digit[i] * q;
Guido van Rossum2095d241997-04-09 19:41:24 +00001561 digit zz = (digit) (z >> SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001562 carry += v->ob_digit[i+k] - z
1563 + ((twodigits)zz << SHIFT);
Jeremy Hyltonfc61f9a2003-05-01 21:31:53 +00001564 v->ob_digit[i+k] = (digit)(carry & MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00001565 carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
1566 carry, SHIFT);
1567 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001568 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001569
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001570 if (i+k < size_v) {
1571 carry += v->ob_digit[i+k];
1572 v->ob_digit[i+k] = 0;
1573 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001574
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001575 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00001576 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001577 else {
1578 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00001579 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001580 carry = 0;
1581 for (i = 0; i < size_w && i+k < size_v; ++i) {
1582 carry += v->ob_digit[i+k] + w->ob_digit[i];
Jeremy Hyltonfc61f9a2003-05-01 21:31:53 +00001583 v->ob_digit[i+k] = (digit)(carry & MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00001584 carry = Py_ARITHMETIC_RIGHT_SHIFT(
1585 BASE_TWODIGITS_TYPE,
1586 carry, SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001587 }
1588 }
1589 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00001590
Guido van Rossumc206c761995-01-10 15:23:19 +00001591 if (a == NULL)
1592 *prem = NULL;
1593 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00001594 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00001595 *prem = divrem1(v, d, &d);
1596 /* d receives the (unused) remainder */
1597 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001598 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00001599 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00001600 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001601 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001602 Py_DECREF(v);
1603 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001604 return a;
1605}
1606
1607/* Methods */
1608
1609static void
Tim Peters9f688bf2000-07-07 15:53:28 +00001610long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001611{
Guido van Rossum9475a232001-10-05 20:51:39 +00001612 v->ob_type->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001613}
1614
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001615static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001616long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001617{
Fred Drake121ee271999-12-23 15:41:28 +00001618 return long_format(v, 10, 1);
1619}
1620
1621static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001622long_str(PyObject *v)
Fred Drake121ee271999-12-23 15:41:28 +00001623{
1624 return long_format(v, 10, 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001625}
1626
1627static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001628long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001629{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001630 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001631
Guido van Rossumc6913e71991-11-19 20:26:46 +00001632 if (a->ob_size != b->ob_size) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001633 if (ABS(a->ob_size) == 0 && ABS(b->ob_size) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00001634 sign = 0;
1635 else
1636 sign = a->ob_size - b->ob_size;
1637 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001638 else {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001639 Py_ssize_t i = ABS(a->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001640 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
1641 ;
1642 if (i < 0)
1643 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00001644 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001645 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00001646 if (a->ob_size < 0)
1647 sign = -sign;
1648 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001649 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001650 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001651}
1652
Guido van Rossum9bfef441993-03-29 10:43:31 +00001653static long
Tim Peters9f688bf2000-07-07 15:53:28 +00001654long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001655{
1656 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001657 Py_ssize_t i;
1658 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001659
1660 /* This is designed so that Python ints and longs with the
1661 same value hash to the same value, otherwise comparisons
1662 of mapping keys will turn out weird */
1663 i = v->ob_size;
1664 sign = 1;
1665 x = 0;
1666 if (i < 0) {
1667 sign = -1;
1668 i = -(i);
1669 }
Neal Norwitzd5a65a72003-02-23 23:11:41 +00001670#define LONG_BIT_SHIFT (8*sizeof(long) - SHIFT)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001671 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00001672 /* Force a native long #-bits (32 or 64) circular shift */
1673 x = ((x << SHIFT) & ~MASK) | ((x >> LONG_BIT_SHIFT) & MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001674 x += v->ob_digit[i];
1675 }
Neal Norwitzd5a65a72003-02-23 23:11:41 +00001676#undef LONG_BIT_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00001677 x = x * sign;
1678 if (x == -1)
1679 x = -2;
1680 return x;
1681}
1682
1683
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001684/* Add the absolute values of two long integers. */
1685
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001686static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001687x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001688{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001689 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001690 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001691 int i;
1692 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00001693
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001694 /* Ensure a is the larger of the two: */
1695 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001696 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00001697 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001698 size_a = size_b;
1699 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001700 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001701 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001702 if (z == NULL)
1703 return NULL;
1704 for (i = 0; i < size_b; ++i) {
1705 carry += a->ob_digit[i] + b->ob_digit[i];
1706 z->ob_digit[i] = carry & MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001707 carry >>= SHIFT;
1708 }
1709 for (; i < size_a; ++i) {
1710 carry += a->ob_digit[i];
1711 z->ob_digit[i] = carry & MASK;
1712 carry >>= SHIFT;
1713 }
1714 z->ob_digit[i] = carry;
1715 return long_normalize(z);
1716}
1717
1718/* Subtract the absolute values of two integers. */
1719
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001720static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001721x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001722{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001723 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001724 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001725 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001726 int sign = 1;
1727 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00001728
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001729 /* Ensure a is the larger of the two: */
1730 if (size_a < size_b) {
1731 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001732 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00001733 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001734 size_a = size_b;
1735 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001736 }
1737 else if (size_a == size_b) {
1738 /* Find highest digit where a and b differ: */
1739 i = size_a;
1740 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
1741 ;
1742 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001743 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001744 if (a->ob_digit[i] < b->ob_digit[i]) {
1745 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001746 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001747 }
1748 size_a = size_b = i+1;
1749 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001750 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001751 if (z == NULL)
1752 return NULL;
1753 for (i = 0; i < size_b; ++i) {
1754 /* The following assumes unsigned arithmetic
1755 works module 2**N for some N>SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001756 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001757 z->ob_digit[i] = borrow & MASK;
1758 borrow >>= SHIFT;
1759 borrow &= 1; /* Keep only one sign bit */
1760 }
1761 for (; i < size_a; ++i) {
1762 borrow = a->ob_digit[i] - borrow;
1763 z->ob_digit[i] = borrow & MASK;
1764 borrow >>= SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00001765 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001766 }
1767 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00001768 if (sign < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001769 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001770 return long_normalize(z);
1771}
1772
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001773static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00001774long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001775{
Neil Schemenauerba872e22001-01-04 01:46:03 +00001776 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00001777
Neil Schemenauerba872e22001-01-04 01:46:03 +00001778 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
1779
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001780 if (a->ob_size < 0) {
1781 if (b->ob_size < 0) {
1782 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00001783 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001784 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001785 }
1786 else
1787 z = x_sub(b, a);
1788 }
1789 else {
1790 if (b->ob_size < 0)
1791 z = x_sub(a, b);
1792 else
1793 z = x_add(a, b);
1794 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00001795 Py_DECREF(a);
1796 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001797 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001798}
1799
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001800static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00001801long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001802{
Neil Schemenauerba872e22001-01-04 01:46:03 +00001803 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001804
Neil Schemenauerba872e22001-01-04 01:46:03 +00001805 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
1806
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001807 if (a->ob_size < 0) {
1808 if (b->ob_size < 0)
1809 z = x_sub(a, b);
1810 else
1811 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00001812 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001813 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001814 }
1815 else {
1816 if (b->ob_size < 0)
1817 z = x_add(a, b);
1818 else
1819 z = x_sub(a, b);
1820 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00001821 Py_DECREF(a);
1822 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001823 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001824}
1825
Tim Peters5af4e6c2002-08-12 02:31:19 +00001826/* Grade school multiplication, ignoring the signs.
1827 * Returns the absolute value of the product, or NULL if error.
1828 */
1829static PyLongObject *
1830x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001831{
Tim Peters5af4e6c2002-08-12 02:31:19 +00001832 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001833 Py_ssize_t size_a = ABS(a->ob_size);
1834 Py_ssize_t size_b = ABS(b->ob_size);
1835 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00001836
Tim Peters5af4e6c2002-08-12 02:31:19 +00001837 z = _PyLong_New(size_a + size_b);
1838 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001839 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001840
1841 memset(z->ob_digit, 0, z->ob_size * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00001842 if (a == b) {
1843 /* Efficient squaring per HAC, Algorithm 14.16:
1844 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
1845 * Gives slightly less than a 2x speedup when a == b,
1846 * via exploiting that each entry in the multiplication
1847 * pyramid appears twice (except for the size_a squares).
1848 */
1849 for (i = 0; i < size_a; ++i) {
1850 twodigits carry;
1851 twodigits f = a->ob_digit[i];
1852 digit *pz = z->ob_digit + (i << 1);
1853 digit *pa = a->ob_digit + i + 1;
1854 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001855
Tim Peters0973b992004-08-29 22:16:50 +00001856 SIGCHECK({
1857 Py_DECREF(z);
1858 return NULL;
1859 })
1860
1861 carry = *pz + f * f;
1862 *pz++ = (digit)(carry & MASK);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001863 carry >>= SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00001864 assert(carry <= MASK);
1865
1866 /* Now f is added in twice in each column of the
1867 * pyramid it appears. Same as adding f<<1 once.
1868 */
1869 f <<= 1;
1870 while (pa < paend) {
1871 carry += *pz + *pa++ * f;
1872 *pz++ = (digit)(carry & MASK);
1873 carry >>= SHIFT;
1874 assert(carry <= (MASK << 1));
1875 }
1876 if (carry) {
1877 carry += *pz;
1878 *pz++ = (digit)(carry & MASK);
1879 carry >>= SHIFT;
1880 }
1881 if (carry)
1882 *pz += (digit)(carry & MASK);
1883 assert((carry >> SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001884 }
Tim Peters0973b992004-08-29 22:16:50 +00001885 }
1886 else { /* a is not the same as b -- gradeschool long mult */
1887 for (i = 0; i < size_a; ++i) {
1888 twodigits carry = 0;
1889 twodigits f = a->ob_digit[i];
1890 digit *pz = z->ob_digit + i;
1891 digit *pb = b->ob_digit;
1892 digit *pbend = b->ob_digit + size_b;
1893
1894 SIGCHECK({
1895 Py_DECREF(z);
1896 return NULL;
1897 })
1898
1899 while (pb < pbend) {
1900 carry += *pz + *pb++ * f;
1901 *pz++ = (digit)(carry & MASK);
1902 carry >>= SHIFT;
1903 assert(carry <= MASK);
1904 }
1905 if (carry)
1906 *pz += (digit)(carry & MASK);
1907 assert((carry >> SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001908 }
1909 }
Tim Peters44121a62002-08-12 06:17:58 +00001910 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001911}
1912
1913/* A helper for Karatsuba multiplication (k_mul).
1914 Takes a long "n" and an integer "size" representing the place to
1915 split, and sets low and high such that abs(n) == (high << size) + low,
1916 viewing the shift as being by digits. The sign bit is ignored, and
1917 the return values are >= 0.
1918 Returns 0 on success, -1 on failure.
1919*/
1920static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001921kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00001922{
1923 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001924 Py_ssize_t size_lo, size_hi;
1925 const Py_ssize_t size_n = ABS(n->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001926
1927 size_lo = MIN(size_n, size);
1928 size_hi = size_n - size_lo;
1929
1930 if ((hi = _PyLong_New(size_hi)) == NULL)
1931 return -1;
1932 if ((lo = _PyLong_New(size_lo)) == NULL) {
1933 Py_DECREF(hi);
1934 return -1;
1935 }
1936
1937 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
1938 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
1939
1940 *high = long_normalize(hi);
1941 *low = long_normalize(lo);
1942 return 0;
1943}
1944
Tim Peters60004642002-08-12 22:01:34 +00001945static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
1946
Tim Peters5af4e6c2002-08-12 02:31:19 +00001947/* Karatsuba multiplication. Ignores the input signs, and returns the
1948 * absolute value of the product (or NULL if error).
1949 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
1950 */
1951static PyLongObject *
1952k_mul(PyLongObject *a, PyLongObject *b)
1953{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001954 Py_ssize_t asize = ABS(a->ob_size);
1955 Py_ssize_t bsize = ABS(b->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001956 PyLongObject *ah = NULL;
1957 PyLongObject *al = NULL;
1958 PyLongObject *bh = NULL;
1959 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001960 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00001961 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001962 Py_ssize_t shift; /* the number of digits we split off */
1963 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00001964
Tim Peters5af4e6c2002-08-12 02:31:19 +00001965 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
1966 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
1967 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00001968 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00001969 * By picking X to be a power of 2, "*X" is just shifting, and it's
1970 * been reduced to 3 multiplies on numbers half the size.
1971 */
1972
Tim Petersfc07e562002-08-12 02:54:10 +00001973 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00001974 * is largest.
1975 */
Tim Peters738eda72002-08-12 15:08:20 +00001976 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00001977 t1 = a;
1978 a = b;
1979 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00001980
1981 i = asize;
1982 asize = bsize;
1983 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001984 }
1985
1986 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00001987 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
1988 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00001989 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00001990 return _PyLong_New(0);
1991 else
1992 return x_mul(a, b);
1993 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001994
Tim Peters60004642002-08-12 22:01:34 +00001995 /* If a is small compared to b, splitting on b gives a degenerate
1996 * case with ah==0, and Karatsuba may be (even much) less efficient
1997 * than "grade school" then. However, we can still win, by viewing
1998 * b as a string of "big digits", each of width a->ob_size. That
1999 * leads to a sequence of balanced calls to k_mul.
2000 */
2001 if (2 * asize <= bsize)
2002 return k_lopsided_mul(a, b);
2003
Tim Petersd6974a52002-08-13 20:37:51 +00002004 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002005 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002006 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Tim Petersd6974a52002-08-13 20:37:51 +00002007 assert(ah->ob_size > 0); /* the split isn't degenerate */
2008
Tim Peters0973b992004-08-29 22:16:50 +00002009 if (a == b) {
2010 bh = ah;
2011 bl = al;
2012 Py_INCREF(bh);
2013 Py_INCREF(bl);
2014 }
2015 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002016
Tim Petersd64c1de2002-08-12 17:36:03 +00002017 /* The plan:
2018 * 1. Allocate result space (asize + bsize digits: that's always
2019 * enough).
2020 * 2. Compute ah*bh, and copy into result at 2*shift.
2021 * 3. Compute al*bl, and copy into result at 0. Note that this
2022 * can't overlap with #2.
2023 * 4. Subtract al*bl from the result, starting at shift. This may
2024 * underflow (borrow out of the high digit), but we don't care:
2025 * we're effectively doing unsigned arithmetic mod
2026 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2027 * borrows and carries out of the high digit can be ignored.
2028 * 5. Subtract ah*bh from the result, starting at shift.
2029 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2030 * at shift.
2031 */
2032
2033 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002034 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002035 if (ret == NULL) goto fail;
2036#ifdef Py_DEBUG
2037 /* Fill with trash, to catch reference to uninitialized digits. */
2038 memset(ret->ob_digit, 0xDF, ret->ob_size * sizeof(digit));
2039#endif
Tim Peters44121a62002-08-12 06:17:58 +00002040
Tim Petersd64c1de2002-08-12 17:36:03 +00002041 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002042 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
2043 assert(t1->ob_size >= 0);
2044 assert(2*shift + t1->ob_size <= ret->ob_size);
2045 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
2046 t1->ob_size * sizeof(digit));
2047
2048 /* Zero-out the digits higher than the ah*bh copy. */
2049 i = ret->ob_size - 2*shift - t1->ob_size;
Tim Peters44121a62002-08-12 06:17:58 +00002050 if (i)
Tim Peters738eda72002-08-12 15:08:20 +00002051 memset(ret->ob_digit + 2*shift + t1->ob_size, 0,
Tim Peters44121a62002-08-12 06:17:58 +00002052 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002053
Tim Petersd64c1de2002-08-12 17:36:03 +00002054 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002055 if ((t2 = k_mul(al, bl)) == NULL) {
2056 Py_DECREF(t1);
2057 goto fail;
2058 }
2059 assert(t2->ob_size >= 0);
2060 assert(t2->ob_size <= 2*shift); /* no overlap with high digits */
2061 memcpy(ret->ob_digit, t2->ob_digit, t2->ob_size * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002062
2063 /* Zero out remaining digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002064 i = 2*shift - t2->ob_size; /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002065 if (i)
Tim Peters738eda72002-08-12 15:08:20 +00002066 memset(ret->ob_digit + t2->ob_size, 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002067
Tim Petersd64c1de2002-08-12 17:36:03 +00002068 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2069 * because it's fresher in cache.
2070 */
Tim Peters738eda72002-08-12 15:08:20 +00002071 i = ret->ob_size - shift; /* # digits after shift */
Tim Petersd64c1de2002-08-12 17:36:03 +00002072 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, t2->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002073 Py_DECREF(t2);
2074
Tim Petersd64c1de2002-08-12 17:36:03 +00002075 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, t1->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002076 Py_DECREF(t1);
2077
Tim Petersd64c1de2002-08-12 17:36:03 +00002078 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002079 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2080 Py_DECREF(ah);
2081 Py_DECREF(al);
2082 ah = al = NULL;
2083
Tim Peters0973b992004-08-29 22:16:50 +00002084 if (a == b) {
2085 t2 = t1;
2086 Py_INCREF(t2);
2087 }
2088 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002089 Py_DECREF(t1);
2090 goto fail;
2091 }
2092 Py_DECREF(bh);
2093 Py_DECREF(bl);
2094 bh = bl = NULL;
2095
Tim Peters738eda72002-08-12 15:08:20 +00002096 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002097 Py_DECREF(t1);
2098 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002099 if (t3 == NULL) goto fail;
Tim Peters547607c2002-08-12 19:43:49 +00002100 assert(t3->ob_size >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002101
Tim Petersd6974a52002-08-13 20:37:51 +00002102 /* Add t3. It's not obvious why we can't run out of room here.
2103 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002104 */
Tim Petersd64c1de2002-08-12 17:36:03 +00002105 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, t3->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002106 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002107
Tim Peters5af4e6c2002-08-12 02:31:19 +00002108 return long_normalize(ret);
2109
2110 fail:
2111 Py_XDECREF(ret);
2112 Py_XDECREF(ah);
2113 Py_XDECREF(al);
2114 Py_XDECREF(bh);
2115 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002116 return NULL;
2117}
2118
Tim Petersd6974a52002-08-13 20:37:51 +00002119/* (*) Why adding t3 can't "run out of room" above.
2120
Tim Petersab86c2b2002-08-15 20:06:00 +00002121Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2122to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002123
Tim Petersab86c2b2002-08-15 20:06:00 +000021241. For any integer i, i = c(i/2) + f(i/2). In particular,
2125 bsize = c(bsize/2) + f(bsize/2).
21262. shift = f(bsize/2)
21273. asize <= bsize
21284. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2129 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002130
Tim Petersab86c2b2002-08-15 20:06:00 +00002131We allocated asize + bsize result digits, and add t3 into them at an offset
2132of shift. This leaves asize+bsize-shift allocated digit positions for t3
2133to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2134asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002135
Tim Petersab86c2b2002-08-15 20:06:00 +00002136bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2137at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002138
Tim Petersab86c2b2002-08-15 20:06:00 +00002139If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2140digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2141most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002142
Tim Petersab86c2b2002-08-15 20:06:00 +00002143The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002144
Tim Petersab86c2b2002-08-15 20:06:00 +00002145 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002146
Tim Petersab86c2b2002-08-15 20:06:00 +00002147and we have asize + c(bsize/2) available digit positions. We need to show
2148this is always enough. An instance of c(bsize/2) cancels out in both, so
2149the question reduces to whether asize digits is enough to hold
2150(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2151then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2152asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
2153digit is enough to hold 2 bits. This is so since SHIFT=15 >= 2. If
2154asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002155c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2156is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2157bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002158
Tim Peters48d52c02002-08-14 17:07:32 +00002159Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2160clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2161ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002162*/
2163
Tim Peters60004642002-08-12 22:01:34 +00002164/* b has at least twice the digits of a, and a is big enough that Karatsuba
2165 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2166 * of slices, each with a->ob_size digits, and multiply the slices by a,
2167 * one at a time. This gives k_mul balanced inputs to work with, and is
2168 * also cache-friendly (we compute one double-width slice of the result
2169 * at a time, then move on, never bactracking except for the helpful
2170 * single-width slice overlap between successive partial sums).
2171 */
2172static PyLongObject *
2173k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2174{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002175 const Py_ssize_t asize = ABS(a->ob_size);
2176 Py_ssize_t bsize = ABS(b->ob_size);
2177 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002178 PyLongObject *ret;
2179 PyLongObject *bslice = NULL;
2180
2181 assert(asize > KARATSUBA_CUTOFF);
2182 assert(2 * asize <= bsize);
2183
2184 /* Allocate result space, and zero it out. */
2185 ret = _PyLong_New(asize + bsize);
2186 if (ret == NULL)
2187 return NULL;
2188 memset(ret->ob_digit, 0, ret->ob_size * sizeof(digit));
2189
2190 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002191 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002192 if (bslice == NULL)
2193 goto fail;
2194
2195 nbdone = 0;
2196 while (bsize > 0) {
2197 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002198 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002199
2200 /* Multiply the next slice of b by a. */
2201 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2202 nbtouse * sizeof(digit));
2203 bslice->ob_size = nbtouse;
2204 product = k_mul(a, bslice);
2205 if (product == NULL)
2206 goto fail;
2207
2208 /* Add into result. */
2209 (void)v_iadd(ret->ob_digit + nbdone, ret->ob_size - nbdone,
2210 product->ob_digit, product->ob_size);
2211 Py_DECREF(product);
2212
2213 bsize -= nbtouse;
2214 nbdone += nbtouse;
2215 }
2216
2217 Py_DECREF(bslice);
2218 return long_normalize(ret);
2219
2220 fail:
2221 Py_DECREF(ret);
2222 Py_XDECREF(bslice);
2223 return NULL;
2224}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002225
2226static PyObject *
2227long_mul(PyLongObject *v, PyLongObject *w)
2228{
2229 PyLongObject *a, *b, *z;
2230
2231 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002232 Py_INCREF(Py_NotImplemented);
2233 return Py_NotImplemented;
2234 }
2235
Tim Petersd64c1de2002-08-12 17:36:03 +00002236 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002237 /* Negate if exactly one of the inputs is negative. */
2238 if (((a->ob_size ^ b->ob_size) < 0) && z)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002239 z->ob_size = -(z->ob_size);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002240 Py_DECREF(a);
2241 Py_DECREF(b);
Tim Peters9973d742002-08-15 19:41:06 +00002242 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002243}
2244
Guido van Rossume32e0141992-01-19 16:31:05 +00002245/* The / and % operators are now defined in terms of divmod().
2246 The expression a mod b has the value a - b*floor(a/b).
2247 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002248 |a| by |b|, with the sign of a. This is also expressed
2249 as a - b*trunc(a/b), if trunc truncates towards zero.
2250 Some examples:
2251 a b a rem b a mod b
2252 13 10 3 3
2253 -13 10 -3 7
2254 13 -10 3 -7
2255 -13 -10 -3 -3
2256 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002257 have different signs. We then subtract one from the 'div'
2258 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002259
Tim Peters47e52ee2004-08-30 02:44:38 +00002260/* Compute
2261 * *pdiv, *pmod = divmod(v, w)
2262 * NULL can be passed for pdiv or pmod, in which case that part of
2263 * the result is simply thrown away. The caller owns a reference to
2264 * each of these it requests (does not pass NULL for).
2265 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002266static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002267l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002268 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002269{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002270 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002271
Guido van Rossume32e0141992-01-19 16:31:05 +00002272 if (long_divrem(v, w, &div, &mod) < 0)
2273 return -1;
Guido van Rossum472c04f1996-12-05 21:57:21 +00002274 if ((mod->ob_size < 0 && w->ob_size > 0) ||
2275 (mod->ob_size > 0 && w->ob_size < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002276 PyLongObject *temp;
2277 PyLongObject *one;
2278 temp = (PyLongObject *) long_add(mod, w);
2279 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002280 mod = temp;
2281 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002282 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002283 return -1;
2284 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002285 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002286 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002287 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2288 Py_DECREF(mod);
2289 Py_DECREF(div);
2290 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002291 return -1;
2292 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002293 Py_DECREF(one);
2294 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002295 div = temp;
2296 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002297 if (pdiv != NULL)
2298 *pdiv = div;
2299 else
2300 Py_DECREF(div);
2301
2302 if (pmod != NULL)
2303 *pmod = mod;
2304 else
2305 Py_DECREF(mod);
2306
Guido van Rossume32e0141992-01-19 16:31:05 +00002307 return 0;
2308}
2309
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002310static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002311long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002312{
Tim Peters47e52ee2004-08-30 02:44:38 +00002313 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002314
2315 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002316 if (l_divmod(a, b, &div, NULL) < 0)
2317 div = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002318 Py_DECREF(a);
2319 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002320 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002321}
2322
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002323static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +00002324long_classic_div(PyObject *v, PyObject *w)
2325{
Tim Peters47e52ee2004-08-30 02:44:38 +00002326 PyLongObject *a, *b, *div;
Guido van Rossum393661d2001-08-31 17:40:15 +00002327
2328 CONVERT_BINOP(v, w, &a, &b);
Guido van Rossum393661d2001-08-31 17:40:15 +00002329 if (Py_DivisionWarningFlag &&
2330 PyErr_Warn(PyExc_DeprecationWarning, "classic long division") < 0)
2331 div = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00002332 else if (l_divmod(a, b, &div, NULL) < 0)
Guido van Rossum393661d2001-08-31 17:40:15 +00002333 div = NULL;
Guido van Rossum393661d2001-08-31 17:40:15 +00002334 Py_DECREF(a);
2335 Py_DECREF(b);
2336 return (PyObject *)div;
2337}
2338
2339static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00002340long_true_divide(PyObject *v, PyObject *w)
2341{
Tim Peterse2a60002001-09-04 06:17:36 +00002342 PyLongObject *a, *b;
2343 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002344 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002345
2346 CONVERT_BINOP(v, w, &a, &b);
2347 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2348 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002349 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
2350 Py_DECREF(a);
2351 Py_DECREF(b);
2352 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002353 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002354 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2355 but should really be set correctly after sucessful calls to
2356 _PyLong_AsScaledDouble() */
2357 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002358
2359 if (bd == 0.0) {
2360 PyErr_SetString(PyExc_ZeroDivisionError,
2361 "long division or modulo by zero");
2362 return NULL;
2363 }
2364
2365 /* True value is very close to ad/bd * 2**(SHIFT*(aexp-bexp)) */
2366 ad /= bd; /* overflow/underflow impossible here */
2367 aexp -= bexp;
2368 if (aexp > INT_MAX / SHIFT)
2369 goto overflow;
Tim Peterse56ed9b2001-09-06 21:59:14 +00002370 else if (aexp < -(INT_MAX / SHIFT))
2371 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002372 errno = 0;
2373 ad = ldexp(ad, aexp * SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002374 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002375 goto overflow;
2376 return PyFloat_FromDouble(ad);
2377
2378overflow:
2379 PyErr_SetString(PyExc_OverflowError,
2380 "long/long too large for a float");
2381 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002382
Tim Peters20dab9f2001-09-04 05:31:47 +00002383}
2384
2385static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002386long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002387{
Tim Peters47e52ee2004-08-30 02:44:38 +00002388 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002389
2390 CONVERT_BINOP(v, w, &a, &b);
2391
Tim Peters47e52ee2004-08-30 02:44:38 +00002392 if (l_divmod(a, b, NULL, &mod) < 0)
2393 mod = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002394 Py_DECREF(a);
2395 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002396 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002397}
2398
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002399static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002400long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002401{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002402 PyLongObject *a, *b, *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002403 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002404
2405 CONVERT_BINOP(v, w, &a, &b);
2406
2407 if (l_divmod(a, b, &div, &mod) < 0) {
2408 Py_DECREF(a);
2409 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002410 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002411 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002412 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002413 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002414 PyTuple_SetItem(z, 0, (PyObject *) div);
2415 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002416 }
2417 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002418 Py_DECREF(div);
2419 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002420 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002421 Py_DECREF(a);
2422 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002423 return z;
2424}
2425
Tim Peters47e52ee2004-08-30 02:44:38 +00002426/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002427static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002428long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002429{
Tim Peters47e52ee2004-08-30 02:44:38 +00002430 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
2431 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002432
Tim Peters47e52ee2004-08-30 02:44:38 +00002433 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002434 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00002435 PyLongObject *temp = NULL;
2436
2437 /* 5-ary values. If the exponent is large enough, table is
2438 * precomputed so that table[i] == a**i % c for i in range(32).
2439 */
2440 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2441 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2442
2443 /* a, b, c = v, w, x */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002444 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002445 if (PyLong_Check(x)) {
2446 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002447 Py_INCREF(x);
2448 }
Tim Petersde7990b2005-07-17 23:45:23 +00002449 else if (PyInt_Check(x)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002450 c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x));
Tim Petersde7990b2005-07-17 23:45:23 +00002451 if (c == NULL)
2452 goto Error;
2453 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002454 else if (x == Py_None)
2455 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002456 else {
2457 Py_DECREF(a);
2458 Py_DECREF(b);
2459 Py_INCREF(Py_NotImplemented);
2460 return Py_NotImplemented;
2461 }
Tim Peters4c483c42001-09-05 06:24:58 +00002462
Tim Peters47e52ee2004-08-30 02:44:38 +00002463 if (b->ob_size < 0) { /* if exponent is negative */
2464 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00002465 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00002466 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00002467 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00002468 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002469 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00002470 /* else return a float. This works because we know
2471 that this calls float_pow() which converts its
2472 arguments to double. */
2473 Py_DECREF(a);
2474 Py_DECREF(b);
2475 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002476 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002477 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002478
2479 if (c) {
2480 /* if modulus == 0:
2481 raise ValueError() */
2482 if (c->ob_size == 0) {
2483 PyErr_SetString(PyExc_ValueError,
2484 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00002485 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002486 }
2487
2488 /* if modulus < 0:
2489 negativeOutput = True
2490 modulus = -modulus */
2491 if (c->ob_size < 0) {
2492 negativeOutput = 1;
2493 temp = (PyLongObject *)_PyLong_Copy(c);
2494 if (temp == NULL)
2495 goto Error;
2496 Py_DECREF(c);
2497 c = temp;
2498 temp = NULL;
2499 c->ob_size = - c->ob_size;
2500 }
2501
2502 /* if modulus == 1:
2503 return 0 */
2504 if ((c->ob_size == 1) && (c->ob_digit[0] == 1)) {
2505 z = (PyLongObject *)PyLong_FromLong(0L);
2506 goto Done;
2507 }
2508
2509 /* if base < 0:
2510 base = base % modulus
2511 Having the base positive just makes things easier. */
2512 if (a->ob_size < 0) {
2513 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00002514 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002515 Py_DECREF(a);
2516 a = temp;
2517 temp = NULL;
2518 }
2519 }
2520
2521 /* At this point a, b, and c are guaranteed non-negative UNLESS
2522 c is NULL, in which case a may be negative. */
2523
2524 z = (PyLongObject *)PyLong_FromLong(1L);
2525 if (z == NULL)
2526 goto Error;
2527
2528 /* Perform a modular reduction, X = X % c, but leave X alone if c
2529 * is NULL.
2530 */
2531#define REDUCE(X) \
2532 if (c != NULL) { \
2533 if (l_divmod(X, c, NULL, &temp) < 0) \
2534 goto Error; \
2535 Py_XDECREF(X); \
2536 X = temp; \
2537 temp = NULL; \
2538 }
2539
2540 /* Multiply two values, then reduce the result:
2541 result = X*Y % c. If c is NULL, skip the mod. */
2542#define MULT(X, Y, result) \
2543{ \
2544 temp = (PyLongObject *)long_mul(X, Y); \
2545 if (temp == NULL) \
2546 goto Error; \
2547 Py_XDECREF(result); \
2548 result = temp; \
2549 temp = NULL; \
2550 REDUCE(result) \
2551}
2552
2553 if (b->ob_size <= FIVEARY_CUTOFF) {
2554 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
2555 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
2556 for (i = b->ob_size - 1; i >= 0; --i) {
2557 digit bi = b->ob_digit[i];
2558
2559 for (j = 1 << (SHIFT-1); j != 0; j >>= 1) {
2560 MULT(z, z, z)
2561 if (bi & j)
2562 MULT(z, a, z)
2563 }
2564 }
2565 }
2566 else {
2567 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
2568 Py_INCREF(z); /* still holds 1L */
2569 table[0] = z;
2570 for (i = 1; i < 32; ++i)
2571 MULT(table[i-1], a, table[i])
2572
2573 for (i = b->ob_size - 1; i >= 0; --i) {
2574 const digit bi = b->ob_digit[i];
2575
2576 for (j = SHIFT - 5; j >= 0; j -= 5) {
2577 const int index = (bi >> j) & 0x1f;
2578 for (k = 0; k < 5; ++k)
2579 MULT(z, z, z)
2580 if (index)
2581 MULT(z, table[index], z)
2582 }
2583 }
2584 }
2585
2586 if (negativeOutput && (z->ob_size != 0)) {
2587 temp = (PyLongObject *)long_sub(z, c);
2588 if (temp == NULL)
2589 goto Error;
2590 Py_DECREF(z);
2591 z = temp;
2592 temp = NULL;
2593 }
2594 goto Done;
2595
2596 Error:
2597 if (z != NULL) {
2598 Py_DECREF(z);
2599 z = NULL;
2600 }
2601 /* fall through */
2602 Done:
Tim Peters47e52ee2004-08-30 02:44:38 +00002603 if (b->ob_size > FIVEARY_CUTOFF) {
2604 for (i = 0; i < 32; ++i)
2605 Py_XDECREF(table[i]);
2606 }
Tim Petersde7990b2005-07-17 23:45:23 +00002607 Py_DECREF(a);
2608 Py_DECREF(b);
2609 Py_XDECREF(c);
2610 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002611 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002612}
2613
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002614static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002615long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002616{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002617 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002618 PyLongObject *x;
2619 PyLongObject *w;
2620 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002621 if (w == NULL)
2622 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002623 x = (PyLongObject *) long_add(v, w);
2624 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002625 if (x == NULL)
2626 return NULL;
Tim Peters40c397d2001-09-11 23:24:22 +00002627 x->ob_size = -(x->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002628 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002629}
2630
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002631static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002632long_pos(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002633{
Tim Peters69c2de32001-09-11 22:31:33 +00002634 if (PyLong_CheckExact(v)) {
2635 Py_INCREF(v);
2636 return (PyObject *)v;
2637 }
2638 else
2639 return _PyLong_Copy(v);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002640}
2641
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002642static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002643long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002644{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002645 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002646 if (v->ob_size == 0 && PyLong_CheckExact(v)) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002647 /* -0 == 0 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002648 Py_INCREF(v);
2649 return (PyObject *) v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002650 }
Tim Peters69c2de32001-09-11 22:31:33 +00002651 z = (PyLongObject *)_PyLong_Copy(v);
2652 if (z != NULL)
2653 z->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002654 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002655}
2656
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002657static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002658long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002659{
2660 if (v->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002661 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00002662 else
2663 return long_pos(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002664}
2665
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002666static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002667long_nonzero(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002668{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002669 return ABS(v->ob_size) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002670}
2671
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002672static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002673long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002674{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002675 PyLongObject *a, *b;
2676 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002677 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002678 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002679 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002680
Neil Schemenauerba872e22001-01-04 01:46:03 +00002681 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2682
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002683 if (a->ob_size < 0) {
2684 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002685 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002686 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002687 if (a1 == NULL)
2688 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002689 a2 = (PyLongObject *) long_rshift(a1, b);
2690 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002691 if (a2 == NULL)
2692 goto rshift_error;
2693 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002694 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002695 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002696 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002697
Neil Schemenauerba872e22001-01-04 01:46:03 +00002698 shiftby = PyLong_AsLong((PyObject *)b);
2699 if (shiftby == -1L && PyErr_Occurred())
2700 goto rshift_error;
2701 if (shiftby < 0) {
2702 PyErr_SetString(PyExc_ValueError,
2703 "negative shift count");
2704 goto rshift_error;
2705 }
2706 wordshift = shiftby / SHIFT;
2707 newsize = ABS(a->ob_size) - wordshift;
2708 if (newsize <= 0) {
2709 z = _PyLong_New(0);
2710 Py_DECREF(a);
2711 Py_DECREF(b);
2712 return (PyObject *)z;
2713 }
2714 loshift = shiftby % SHIFT;
2715 hishift = SHIFT - loshift;
2716 lomask = ((digit)1 << hishift) - 1;
2717 himask = MASK ^ lomask;
2718 z = _PyLong_New(newsize);
2719 if (z == NULL)
2720 goto rshift_error;
2721 if (a->ob_size < 0)
2722 z->ob_size = -(z->ob_size);
2723 for (i = 0, j = wordshift; i < newsize; i++, j++) {
2724 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
2725 if (i+1 < newsize)
2726 z->ob_digit[i] |=
2727 (a->ob_digit[j+1] << hishift) & himask;
2728 }
2729 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002730 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002731rshift_error:
2732 Py_DECREF(a);
2733 Py_DECREF(b);
2734 return (PyObject *) z;
2735
Guido van Rossumc6913e71991-11-19 20:26:46 +00002736}
2737
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002738static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002739long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002740{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002741 /* This version due to Tim Peters */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002742 PyLongObject *a, *b;
2743 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002744 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002745 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002746 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002747
Neil Schemenauerba872e22001-01-04 01:46:03 +00002748 CONVERT_BINOP(v, w, &a, &b);
2749
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002750 shiftby = PyLong_AsLong((PyObject *)b);
2751 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00002752 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002753 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002754 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00002755 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002756 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002757 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002758 PyErr_SetString(PyExc_ValueError,
2759 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00002760 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002761 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002762 /* wordshift, remshift = divmod(shiftby, SHIFT) */
2763 wordshift = (int)shiftby / SHIFT;
2764 remshift = (int)shiftby - wordshift * SHIFT;
2765
2766 oldsize = ABS(a->ob_size);
2767 newsize = oldsize + wordshift;
2768 if (remshift)
2769 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002770 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002771 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002772 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002773 if (a->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002774 z->ob_size = -(z->ob_size);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002775 for (i = 0; i < wordshift; i++)
2776 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002777 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002778 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00002779 accum |= (twodigits)a->ob_digit[j] << remshift;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002780 z->ob_digit[i] = (digit)(accum & MASK);
2781 accum >>= SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002782 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002783 if (remshift)
2784 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002785 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002786 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002787 z = long_normalize(z);
2788lshift_error:
2789 Py_DECREF(a);
2790 Py_DECREF(b);
2791 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002792}
2793
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002794
2795/* Bitwise and/xor/or operations */
2796
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002797static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002798long_bitwise(PyLongObject *a,
2799 int op, /* '&', '|', '^' */
2800 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002801{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002802 digit maska, maskb; /* 0 or MASK */
2803 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002804 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002805 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002806 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00002807 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002808 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002809
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002810 if (a->ob_size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002811 a = (PyLongObject *) long_invert(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002812 maska = MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002813 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002814 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002815 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002816 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00002817 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002818 if (b->ob_size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002819 b = (PyLongObject *) long_invert(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002820 maskb = MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002821 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002822 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002823 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002824 maskb = 0;
2825 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002826
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002827 negz = 0;
2828 switch (op) {
2829 case '^':
2830 if (maska != maskb) {
2831 maska ^= MASK;
2832 negz = -1;
2833 }
2834 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002835 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002836 if (maska && maskb) {
2837 op = '|';
2838 maska ^= MASK;
2839 maskb ^= MASK;
2840 negz = -1;
2841 }
2842 break;
2843 case '|':
2844 if (maska || maskb) {
2845 op = '&';
2846 maska ^= MASK;
2847 maskb ^= MASK;
2848 negz = -1;
2849 }
2850 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002851 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002852
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002853 /* JRH: The original logic here was to allocate the result value (z)
2854 as the longer of the two operands. However, there are some cases
2855 where the result is guaranteed to be shorter than that: AND of two
2856 positives, OR of two negatives: use the shorter number. AND with
2857 mixed signs: use the positive number. OR with mixed signs: use the
2858 negative number. After the transformations above, op will be '&'
2859 iff one of these cases applies, and mask will be non-0 for operands
2860 whose length should be ignored.
2861 */
2862
2863 size_a = a->ob_size;
2864 size_b = b->ob_size;
2865 size_z = op == '&'
2866 ? (maska
2867 ? size_b
2868 : (maskb ? size_a : MIN(size_a, size_b)))
2869 : MAX(size_a, size_b);
2870 z = _PyLong_New(size_z);
2871 if (a == NULL || b == NULL || z == NULL) {
2872 Py_XDECREF(a);
2873 Py_XDECREF(b);
2874 Py_XDECREF(z);
2875 return NULL;
2876 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002877
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002878 for (i = 0; i < size_z; ++i) {
2879 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
2880 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
2881 switch (op) {
2882 case '&': z->ob_digit[i] = diga & digb; break;
2883 case '|': z->ob_digit[i] = diga | digb; break;
2884 case '^': z->ob_digit[i] = diga ^ digb; break;
2885 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00002886 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002887
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002888 Py_DECREF(a);
2889 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002890 z = long_normalize(z);
2891 if (negz == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002892 return (PyObject *) z;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002893 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002894 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002895 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002896}
2897
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002898static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002899long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002900{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002901 PyLongObject *a, *b;
2902 PyObject *c;
2903 CONVERT_BINOP(v, w, &a, &b);
2904 c = long_bitwise(a, '&', b);
2905 Py_DECREF(a);
2906 Py_DECREF(b);
2907 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002908}
2909
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002910static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002911long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002912{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002913 PyLongObject *a, *b;
2914 PyObject *c;
2915 CONVERT_BINOP(v, w, &a, &b);
2916 c = long_bitwise(a, '^', b);
2917 Py_DECREF(a);
2918 Py_DECREF(b);
2919 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002920}
2921
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002922static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002923long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002924{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002925 PyLongObject *a, *b;
2926 PyObject *c;
2927 CONVERT_BINOP(v, w, &a, &b);
2928 c = long_bitwise(a, '|', b);
2929 Py_DECREF(a);
2930 Py_DECREF(b);
2931 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002932}
2933
Guido van Rossum234f9421993-06-17 12:35:49 +00002934static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002935long_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00002936{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002937 if (PyInt_Check(*pw)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00002938 *pw = PyLong_FromLong(PyInt_AS_LONG(*pw));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002939 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00002940 return 0;
2941 }
Guido van Rossum1952e382001-09-19 01:25:16 +00002942 else if (PyLong_Check(*pw)) {
2943 Py_INCREF(*pv);
2944 Py_INCREF(*pw);
2945 return 0;
2946 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00002947 return 1; /* Can't do it */
2948}
2949
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002950static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002951long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00002952{
Brett Cannonc3647ac2005-04-26 03:45:26 +00002953 if (PyLong_CheckExact(v))
2954 Py_INCREF(v);
2955 else
2956 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00002957 return v;
2958}
2959
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002960static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00002961long_int(PyObject *v)
2962{
2963 long x;
2964 x = PyLong_AsLong(v);
2965 if (PyErr_Occurred()) {
2966 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
2967 PyErr_Clear();
2968 if (PyLong_CheckExact(v)) {
2969 Py_INCREF(v);
2970 return v;
2971 }
2972 else
2973 return _PyLong_Copy((PyLongObject *)v);
2974 }
2975 else
2976 return NULL;
2977 }
2978 return PyInt_FromLong(x);
2979}
2980
2981static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002982long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00002983{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00002984 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002985 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00002986 if (result == -1.0 && PyErr_Occurred())
2987 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002988 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00002989}
2990
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002991static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002992long_oct(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00002993{
Fred Drake121ee271999-12-23 15:41:28 +00002994 return long_format(v, 8, 1);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00002995}
2996
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002997static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002998long_hex(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00002999{
Fred Drake121ee271999-12-23 15:41:28 +00003000 return long_format(v, 16, 1);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003001}
Jeremy Hylton938ace62002-07-17 16:30:39 +00003002
3003static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003004long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003005
Tim Peters6d6c1a32001-08-02 04:15:00 +00003006static PyObject *
3007long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3008{
3009 PyObject *x = NULL;
3010 int base = -909; /* unlikely! */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00003011 static const char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003012
Guido van Rossumbef14172001-08-29 15:47:46 +00003013 if (type != &PyLong_Type)
3014 return long_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003015 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist,
3016 &x, &base))
3017 return NULL;
3018 if (x == NULL)
3019 return PyLong_FromLong(0L);
3020 if (base == -909)
3021 return PyNumber_Long(x);
3022 else if (PyString_Check(x))
3023 return PyLong_FromString(PyString_AS_STRING(x), NULL, base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003024#ifdef Py_USING_UNICODE
Tim Peters6d6c1a32001-08-02 04:15:00 +00003025 else if (PyUnicode_Check(x))
3026 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3027 PyUnicode_GET_SIZE(x),
3028 base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003029#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +00003030 else {
3031 PyErr_SetString(PyExc_TypeError,
3032 "long() can't convert non-string with explicit base");
3033 return NULL;
3034 }
3035}
3036
Guido van Rossumbef14172001-08-29 15:47:46 +00003037/* Wimpy, slow approach to tp_new calls for subtypes of long:
3038 first create a regular long from whatever arguments we got,
3039 then allocate a subtype instance and initialize it from
3040 the regular long. The regular long is then thrown away.
3041*/
3042static PyObject *
3043long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3044{
3045 PyLongObject *tmp, *new;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003046 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003047
3048 assert(PyType_IsSubtype(type, &PyLong_Type));
3049 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3050 if (tmp == NULL)
3051 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003052 assert(PyLong_CheckExact(tmp));
Guido van Rossumbef14172001-08-29 15:47:46 +00003053 n = tmp->ob_size;
3054 if (n < 0)
3055 n = -n;
3056 new = (PyLongObject *)type->tp_alloc(type, n);
Raymond Hettingerf4667932003-06-28 20:04:25 +00003057 if (new == NULL) {
3058 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003059 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003060 }
Guido van Rossumbef14172001-08-29 15:47:46 +00003061 assert(PyLong_Check(new));
Guido van Rossum13228a62001-08-30 15:54:44 +00003062 new->ob_size = tmp->ob_size;
Guido van Rossumbef14172001-08-29 15:47:46 +00003063 for (i = 0; i < n; i++)
3064 new->ob_digit[i] = tmp->ob_digit[i];
3065 Py_DECREF(tmp);
3066 return (PyObject *)new;
3067}
3068
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003069static PyObject *
3070long_getnewargs(PyLongObject *v)
3071{
3072 return Py_BuildValue("(N)", _PyLong_Copy(v));
3073}
3074
3075static PyMethodDef long_methods[] = {
3076 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
3077 {NULL, NULL} /* sentinel */
3078};
3079
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003080PyDoc_STRVAR(long_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003081"long(x[, base]) -> integer\n\
3082\n\
3083Convert a string or number to a long integer, if possible. A floating\n\
3084point argument will be truncated towards zero (this does not include a\n\
3085string representation of a floating point number!) When converting a\n\
3086string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003087converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003088
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003089static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003090 (binaryfunc) long_add, /*nb_add*/
3091 (binaryfunc) long_sub, /*nb_subtract*/
3092 (binaryfunc) long_mul, /*nb_multiply*/
Guido van Rossum393661d2001-08-31 17:40:15 +00003093 (binaryfunc) long_classic_div, /*nb_divide*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003094 (binaryfunc) long_mod, /*nb_remainder*/
3095 (binaryfunc) long_divmod, /*nb_divmod*/
3096 (ternaryfunc) long_pow, /*nb_power*/
3097 (unaryfunc) long_neg, /*nb_negative*/
3098 (unaryfunc) long_pos, /*tp_positive*/
3099 (unaryfunc) long_abs, /*tp_absolute*/
3100 (inquiry) long_nonzero, /*tp_nonzero*/
3101 (unaryfunc) long_invert, /*nb_invert*/
3102 (binaryfunc) long_lshift, /*nb_lshift*/
3103 (binaryfunc) long_rshift, /*nb_rshift*/
3104 (binaryfunc) long_and, /*nb_and*/
3105 (binaryfunc) long_xor, /*nb_xor*/
3106 (binaryfunc) long_or, /*nb_or*/
Tim Peters9ace6bc2000-07-08 00:32:04 +00003107 (coercion) long_coerce, /*nb_coerce*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003108 (unaryfunc) long_int, /*nb_int*/
3109 (unaryfunc) long_long, /*nb_long*/
3110 (unaryfunc) long_float, /*nb_float*/
3111 (unaryfunc) long_oct, /*nb_oct*/
3112 (unaryfunc) long_hex, /*nb_hex*/
Guido van Rossum4668b002001-08-08 05:00:18 +00003113 0, /* nb_inplace_add */
3114 0, /* nb_inplace_subtract */
3115 0, /* nb_inplace_multiply */
3116 0, /* nb_inplace_divide */
3117 0, /* nb_inplace_remainder */
3118 0, /* nb_inplace_power */
3119 0, /* nb_inplace_lshift */
3120 0, /* nb_inplace_rshift */
3121 0, /* nb_inplace_and */
3122 0, /* nb_inplace_xor */
3123 0, /* nb_inplace_or */
3124 (binaryfunc)long_div, /* nb_floor_divide */
3125 long_true_divide, /* nb_true_divide */
3126 0, /* nb_inplace_floor_divide */
3127 0, /* nb_inplace_true_divide */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003128};
3129
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003130PyTypeObject PyLong_Type = {
3131 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003132 0, /* ob_size */
3133 "long", /* tp_name */
3134 sizeof(PyLongObject) - sizeof(digit), /* tp_basicsize */
3135 sizeof(digit), /* tp_itemsize */
3136 (destructor)long_dealloc, /* tp_dealloc */
3137 0, /* tp_print */
3138 0, /* tp_getattr */
3139 0, /* tp_setattr */
3140 (cmpfunc)long_compare, /* tp_compare */
3141 (reprfunc)long_repr, /* tp_repr */
3142 &long_as_number, /* tp_as_number */
3143 0, /* tp_as_sequence */
3144 0, /* tp_as_mapping */
3145 (hashfunc)long_hash, /* tp_hash */
3146 0, /* tp_call */
3147 (reprfunc)long_str, /* tp_str */
3148 PyObject_GenericGetAttr, /* tp_getattro */
3149 0, /* tp_setattro */
3150 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00003151 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3152 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003153 long_doc, /* tp_doc */
3154 0, /* tp_traverse */
3155 0, /* tp_clear */
3156 0, /* tp_richcompare */
3157 0, /* tp_weaklistoffset */
3158 0, /* tp_iter */
3159 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003160 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003161 0, /* tp_members */
3162 0, /* tp_getset */
3163 0, /* tp_base */
3164 0, /* tp_dict */
3165 0, /* tp_descr_get */
3166 0, /* tp_descr_set */
3167 0, /* tp_dictoffset */
3168 0, /* tp_init */
3169 0, /* tp_alloc */
3170 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003171 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003172};