blob: e04699e2700473e240f6c735d97aa01c2cc92454 [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{
Neal Norwitzc6a989a2006-05-10 06:57:58 +000069 if (size > PY_SSIZE_T_MAX) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000070 PyErr_NoMemory();
71 return NULL;
72 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +000073 return PyObject_NEW_VAR(PyLongObject, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +000074}
75
Tim Peters64b5ce32001-09-10 20:52:51 +000076PyObject *
77_PyLong_Copy(PyLongObject *src)
78{
79 PyLongObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +000080 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +000081
82 assert(src != NULL);
83 i = src->ob_size;
84 if (i < 0)
85 i = -(i);
86 result = _PyLong_New(i);
87 if (result != NULL) {
Tim Peters5329cdb2002-03-02 04:18:04 +000088 result->ob_size = src->ob_size;
Tim Peters64b5ce32001-09-10 20:52:51 +000089 while (--i >= 0)
90 result->ob_digit[i] = src->ob_digit[i];
91 }
92 return (PyObject *)result;
93}
94
Guido van Rossumedcc38a1991-05-05 20:09:44 +000095/* Create a new long int object from a C long int */
96
Guido van Rossumc0b618a1997-05-02 03:12:38 +000097PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +000098PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +000099{
Tim Petersce9de2f2001-06-14 04:56:19 +0000100 PyLongObject *v;
101 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
102 int ndigits = 0;
103 int negative = 0;
104
105 if (ival < 0) {
106 ival = -ival;
107 negative = 1;
108 }
109
110 /* Count the number of Python digits.
111 We used to pick 5 ("big enough for anything"), but that's a
112 waste of time and space given that 5*15 = 75 bits are rarely
113 needed. */
114 t = (unsigned long)ival;
115 while (t) {
116 ++ndigits;
117 t >>= SHIFT;
118 }
119 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000120 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000121 digit *p = v->ob_digit;
122 v->ob_size = negative ? -ndigits : ndigits;
123 t = (unsigned long)ival;
124 while (t) {
125 *p++ = (digit)(t & MASK);
Guido van Rossum472c04f1996-12-05 21:57:21 +0000126 t >>= SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000127 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000128 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000129 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000130}
131
Guido van Rossum53756b11997-01-03 17:14:46 +0000132/* Create a new long int object from a C unsigned long int */
133
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000134PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000135PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000136{
Tim Petersce9de2f2001-06-14 04:56:19 +0000137 PyLongObject *v;
138 unsigned long t;
139 int ndigits = 0;
140
141 /* Count the number of Python digits. */
142 t = (unsigned long)ival;
143 while (t) {
144 ++ndigits;
145 t >>= SHIFT;
146 }
147 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000148 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000149 digit *p = v->ob_digit;
150 v->ob_size = ndigits;
151 while (ival) {
152 *p++ = (digit)(ival & MASK);
153 ival >>= SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000154 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000155 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000156 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000157}
158
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000159/* Create a new long int object from a C double */
160
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000161PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000162PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000163{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000164 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000165 double frac;
166 int i, ndig, expo, neg;
167 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000168 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000169 PyErr_SetString(PyExc_OverflowError,
170 "cannot convert float infinity to long");
171 return NULL;
172 }
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000173 if (dval < 0.0) {
174 neg = 1;
175 dval = -dval;
176 }
177 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
178 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000179 return PyLong_FromLong(0L);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000180 ndig = (expo-1) / SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000181 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000182 if (v == NULL)
183 return NULL;
184 frac = ldexp(frac, (expo-1) % SHIFT + 1);
185 for (i = ndig; --i >= 0; ) {
186 long bits = (long)frac;
Guido van Rossum2095d241997-04-09 19:41:24 +0000187 v->ob_digit[i] = (digit) bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000188 frac = frac - (double)bits;
189 frac = ldexp(frac, SHIFT);
190 }
191 if (neg)
Guido van Rossum4c260ff1992-01-14 18:36:43 +0000192 v->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000193 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000194}
195
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000196/* Get a C long int from a long int object.
197 Returns -1 and sets an error condition if overflow occurs. */
198
199long
Tim Peters9f688bf2000-07-07 15:53:28 +0000200PyLong_AsLong(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000201{
Guido van Rossumf7531811998-05-26 14:33:37 +0000202 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000203 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000204 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000205 Py_ssize_t i;
206 int sign;
Guido van Rossumf7531811998-05-26 14:33:37 +0000207
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000208 if (vv == NULL || !PyLong_Check(vv)) {
Guido van Rossum7e35d572001-09-15 03:14:32 +0000209 if (vv != NULL && PyInt_Check(vv))
210 return PyInt_AsLong(vv);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000211 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000212 return -1;
213 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000214 v = (PyLongObject *)vv;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000215 i = v->ob_size;
216 sign = 1;
217 x = 0;
218 if (i < 0) {
219 sign = -1;
Guido van Rossum4c260ff1992-01-14 18:36:43 +0000220 i = -(i);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000221 }
222 while (--i >= 0) {
223 prev = x;
224 x = (x << SHIFT) + v->ob_digit[i];
Guido van Rossumf7531811998-05-26 14:33:37 +0000225 if ((x >> SHIFT) != prev)
226 goto overflow;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000227 }
Guido van Rossumf7531811998-05-26 14:33:37 +0000228 /* Haven't lost any bits, but if the sign bit is set we're in
229 * trouble *unless* this is the min negative number. So,
230 * trouble iff sign bit set && (positive || some bit set other
231 * than the sign bit).
232 */
233 if ((long)x < 0 && (sign > 0 || (x << 1) != 0))
234 goto overflow;
235 return (long)x * sign;
236
237 overflow:
238 PyErr_SetString(PyExc_OverflowError,
Skip Montanarobafedec2001-09-13 19:05:30 +0000239 "long int too large to convert to int");
Guido van Rossumf7531811998-05-26 14:33:37 +0000240 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000241}
242
Guido van Rossum38fff8c2006-03-07 18:50:55 +0000243static Py_ssize_t
244_long_as_ssize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000245 register PyLongObject *v;
246 size_t x, prev;
247 Py_ssize_t i;
248 int sign;
249
250 if (vv == NULL || !PyLong_Check(vv)) {
251 PyErr_BadInternalCall();
252 return -1;
253 }
254 v = (PyLongObject *)vv;
255 i = v->ob_size;
256 sign = 1;
257 x = 0;
258 if (i < 0) {
259 sign = -1;
260 i = -(i);
261 }
262 while (--i >= 0) {
263 prev = x;
264 x = (x << SHIFT) + v->ob_digit[i];
265 if ((x >> SHIFT) != prev)
266 goto overflow;
267 }
268 /* Haven't lost any bits, but if the sign bit is set we're in
269 * trouble *unless* this is the min negative number. So,
270 * trouble iff sign bit set && (positive || some bit set other
271 * than the sign bit).
272 */
273 if ((Py_ssize_t)x < 0 && (sign > 0 || (x << 1) != 0))
274 goto overflow;
275 return (Py_ssize_t)x * sign;
276
277 overflow:
278 PyErr_SetString(PyExc_OverflowError,
279 "long int too large to convert to int");
Guido van Rossum38fff8c2006-03-07 18:50:55 +0000280 if (sign > 0)
281 return PY_SSIZE_T_MAX;
282 else
Martin v. Löwisc48c8db2006-04-05 18:21:17 +0000283 return PY_SSIZE_T_MIN;
Guido van Rossum38fff8c2006-03-07 18:50:55 +0000284}
285
286/* Get a Py_ssize_t from a long int object.
287 Returns -1 and sets an error condition if overflow occurs. */
288
289Py_ssize_t
290_PyLong_AsSsize_t(PyObject *vv)
291{
292 Py_ssize_t x;
293
294 x = _long_as_ssize_t(vv);
295 if (PyErr_Occurred()) return -1;
296 return x;
297}
298
299
300/* Get a Py_ssize_t from a long int object.
301 Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX,
302 and silently boost values less than -PY_SSIZE_T_MAX-1 to -PY_SSIZE_T_MAX-1.
Armin Rigo12bec1b2006-03-28 19:27:56 +0000303 On error, return -1 with an exception set.
Guido van Rossum38fff8c2006-03-07 18:50:55 +0000304*/
305
306static Py_ssize_t
307long_index(PyObject *vv)
308{
309 Py_ssize_t x;
310
311 x = _long_as_ssize_t(vv);
312 if (PyErr_Occurred()) {
313 /* If overflow error, ignore the error */
314 if (x != -1) {
315 PyErr_Clear();
316 }
317 }
318 return x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000319}
320
Guido van Rossumd8c80482002-08-13 00:24:58 +0000321/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000322 Returns -1 and sets an error condition if overflow occurs. */
323
324unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000325PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000326{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000327 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000328 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000329 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000330
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000331 if (vv == NULL || !PyLong_Check(vv)) {
Martin v. Löwis729d47d2004-09-20 06:17:46 +0000332 if (vv != NULL && PyInt_Check(vv)) {
333 long val = PyInt_AsLong(vv);
334 if (val < 0) {
335 PyErr_SetString(PyExc_OverflowError,
336 "can't convert negative value to unsigned long");
337 return (unsigned long) -1;
338 }
339 return val;
340 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000341 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000342 return (unsigned long) -1;
343 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000344 v = (PyLongObject *)vv;
Guido van Rossum53756b11997-01-03 17:14:46 +0000345 i = v->ob_size;
346 x = 0;
347 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000348 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum53756b11997-01-03 17:14:46 +0000349 "can't convert negative value to unsigned long");
350 return (unsigned long) -1;
351 }
352 while (--i >= 0) {
353 prev = x;
354 x = (x << SHIFT) + v->ob_digit[i];
355 if ((x >> SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000356 PyErr_SetString(PyExc_OverflowError,
Fred Drake661ea262000-10-24 19:57:45 +0000357 "long int too large to convert");
Guido van Rossum53756b11997-01-03 17:14:46 +0000358 return (unsigned long) -1;
359 }
360 }
361 return x;
362}
363
Thomas Hellera4ea6032003-04-17 18:55:45 +0000364/* Get a C unsigned long int from a long int object, ignoring the high bits.
365 Returns -1 and sets an error condition if an error occurs. */
366
367unsigned long
368PyLong_AsUnsignedLongMask(PyObject *vv)
369{
370 register PyLongObject *v;
371 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000372 Py_ssize_t i;
373 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000374
375 if (vv == NULL || !PyLong_Check(vv)) {
Martin v. Löwis729d47d2004-09-20 06:17:46 +0000376 if (vv != NULL && PyInt_Check(vv))
377 return PyInt_AsUnsignedLongMask(vv);
Thomas Hellera4ea6032003-04-17 18:55:45 +0000378 PyErr_BadInternalCall();
379 return (unsigned long) -1;
380 }
381 v = (PyLongObject *)vv;
382 i = v->ob_size;
383 sign = 1;
384 x = 0;
385 if (i < 0) {
386 sign = -1;
387 i = -i;
388 }
389 while (--i >= 0) {
390 x = (x << SHIFT) + v->ob_digit[i];
391 }
392 return x * sign;
393}
394
Tim Peters5b8132f2003-01-31 15:52:05 +0000395int
396_PyLong_Sign(PyObject *vv)
397{
398 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000399
400 assert(v != NULL);
401 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000402
Tim Petersee1a53c2003-02-02 02:57:53 +0000403 return v->ob_size == 0 ? 0 : (v->ob_size < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000404}
405
Tim Petersbaefd9e2003-01-28 20:37:45 +0000406size_t
407_PyLong_NumBits(PyObject *vv)
408{
409 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000410 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000411 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000412
413 assert(v != NULL);
414 assert(PyLong_Check(v));
Guido van Rossum004a65c2003-02-03 15:28:19 +0000415 ndigits = ABS(v->ob_size);
Tim Petersbaefd9e2003-01-28 20:37:45 +0000416 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
417 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000418 digit msd = v->ob_digit[ndigits - 1];
419
Tim Peters5b8132f2003-01-31 15:52:05 +0000420 result = (ndigits - 1) * SHIFT;
Skip Montanaro429433b2006-04-18 00:35:43 +0000421 if (result / SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000422 goto Overflow;
423 do {
424 ++result;
425 if (result == 0)
426 goto Overflow;
427 msd >>= 1;
428 } while (msd);
429 }
430 return result;
431
432Overflow:
433 PyErr_SetString(PyExc_OverflowError, "long has too many bits "
434 "to express in a platform size_t");
435 return (size_t)-1;
436}
437
Tim Peters2a9b3672001-06-11 21:23:58 +0000438PyObject *
439_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
440 int little_endian, int is_signed)
441{
442 const unsigned char* pstartbyte;/* LSB of bytes */
443 int incr; /* direction to move pstartbyte */
444 const unsigned char* pendbyte; /* MSB of bytes */
445 size_t numsignificantbytes; /* number of bytes that matter */
446 size_t ndigits; /* number of Python long digits */
447 PyLongObject* v; /* result */
448 int idigit = 0; /* next free index in v->ob_digit */
449
450 if (n == 0)
451 return PyLong_FromLong(0L);
452
453 if (little_endian) {
454 pstartbyte = bytes;
455 pendbyte = bytes + n - 1;
456 incr = 1;
457 }
458 else {
459 pstartbyte = bytes + n - 1;
460 pendbyte = bytes;
461 incr = -1;
462 }
463
464 if (is_signed)
465 is_signed = *pendbyte >= 0x80;
466
467 /* Compute numsignificantbytes. This consists of finding the most
468 significant byte. Leading 0 bytes are insignficant if the number
469 is positive, and leading 0xff bytes if negative. */
470 {
471 size_t i;
472 const unsigned char* p = pendbyte;
473 const int pincr = -incr; /* search MSB to LSB */
474 const unsigned char insignficant = is_signed ? 0xff : 0x00;
475
476 for (i = 0; i < n; ++i, p += pincr) {
477 if (*p != insignficant)
478 break;
479 }
480 numsignificantbytes = n - i;
481 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
482 actually has 2 significant bytes. OTOH, 0xff0001 ==
483 -0x00ffff, so we wouldn't *need* to bump it there; but we
484 do for 0xffff = -0x0001. To be safe without bothering to
485 check every case, bump it regardless. */
486 if (is_signed && numsignificantbytes < n)
487 ++numsignificantbytes;
488 }
489
490 /* How many Python long digits do we need? We have
491 8*numsignificantbytes bits, and each Python long digit has SHIFT
492 bits, so it's the ceiling of the quotient. */
493 ndigits = (numsignificantbytes * 8 + SHIFT - 1) / SHIFT;
494 if (ndigits > (size_t)INT_MAX)
495 return PyErr_NoMemory();
496 v = _PyLong_New((int)ndigits);
497 if (v == NULL)
498 return NULL;
499
500 /* Copy the bits over. The tricky parts are computing 2's-comp on
501 the fly for signed numbers, and dealing with the mismatch between
502 8-bit bytes and (probably) 15-bit Python digits.*/
503 {
504 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000505 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000506 twodigits accum = 0; /* sliding register */
507 unsigned int accumbits = 0; /* number of bits in accum */
508 const unsigned char* p = pstartbyte;
509
510 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000511 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000512 /* Compute correction for 2's comp, if needed. */
513 if (is_signed) {
514 thisbyte = (0xff ^ thisbyte) + carry;
515 carry = thisbyte >> 8;
516 thisbyte &= 0xff;
517 }
518 /* Because we're going LSB to MSB, thisbyte is
519 more significant than what's already in accum,
520 so needs to be prepended to accum. */
521 accum |= thisbyte << accumbits;
522 accumbits += 8;
523 if (accumbits >= SHIFT) {
524 /* There's enough to fill a Python digit. */
525 assert(idigit < (int)ndigits);
526 v->ob_digit[idigit] = (digit)(accum & MASK);
527 ++idigit;
528 accum >>= SHIFT;
529 accumbits -= SHIFT;
530 assert(accumbits < SHIFT);
531 }
532 }
533 assert(accumbits < SHIFT);
534 if (accumbits) {
535 assert(idigit < (int)ndigits);
536 v->ob_digit[idigit] = (digit)accum;
537 ++idigit;
538 }
539 }
540
541 v->ob_size = is_signed ? -idigit : idigit;
542 return (PyObject *)long_normalize(v);
543}
544
545int
546_PyLong_AsByteArray(PyLongObject* v,
547 unsigned char* bytes, size_t n,
548 int little_endian, int is_signed)
549{
550 int i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000551 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000552 twodigits accum; /* sliding register */
553 unsigned int accumbits; /* # bits in accum */
554 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
555 twodigits carry; /* for computing 2's-comp */
556 size_t j; /* # bytes filled */
557 unsigned char* p; /* pointer to next byte in bytes */
558 int pincr; /* direction to move p */
559
560 assert(v != NULL && PyLong_Check(v));
561
562 if (v->ob_size < 0) {
563 ndigits = -(v->ob_size);
564 if (!is_signed) {
565 PyErr_SetString(PyExc_TypeError,
566 "can't convert negative long to unsigned");
567 return -1;
568 }
569 do_twos_comp = 1;
570 }
571 else {
572 ndigits = v->ob_size;
573 do_twos_comp = 0;
574 }
575
576 if (little_endian) {
577 p = bytes;
578 pincr = 1;
579 }
580 else {
581 p = bytes + n - 1;
582 pincr = -1;
583 }
584
Tim Peters898cf852001-06-13 20:50:08 +0000585 /* Copy over all the Python digits.
586 It's crucial that every Python digit except for the MSD contribute
587 exactly SHIFT bits to the total, so first assert that the long is
588 normalized. */
589 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000590 j = 0;
591 accum = 0;
592 accumbits = 0;
593 carry = do_twos_comp ? 1 : 0;
594 for (i = 0; i < ndigits; ++i) {
595 twodigits thisdigit = v->ob_digit[i];
596 if (do_twos_comp) {
597 thisdigit = (thisdigit ^ MASK) + carry;
598 carry = thisdigit >> SHIFT;
599 thisdigit &= MASK;
600 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000601 /* Because we're going LSB to MSB, thisdigit is more
602 significant than what's already in accum, so needs to be
603 prepended to accum. */
604 accum |= thisdigit << accumbits;
Tim Petersede05092001-06-14 08:53:38 +0000605 accumbits += SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000606
Tim Petersede05092001-06-14 08:53:38 +0000607 /* The most-significant digit may be (probably is) at least
608 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000609 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000610 /* Count # of sign bits -- they needn't be stored,
611 * although for signed conversion we need later to
612 * make sure at least one sign bit gets stored.
613 * First shift conceptual sign bit to real sign bit.
614 */
615 stwodigits s = (stwodigits)(thisdigit <<
616 (8*sizeof(stwodigits) - SHIFT));
Tim Peters7a3bfc32001-06-12 01:22:22 +0000617 unsigned int nsignbits = 0;
Tim Petersede05092001-06-14 08:53:38 +0000618 while ((s < 0) == do_twos_comp && nsignbits < SHIFT) {
Tim Peters7a3bfc32001-06-12 01:22:22 +0000619 ++nsignbits;
Tim Petersede05092001-06-14 08:53:38 +0000620 s <<= 1;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000621 }
Tim Petersede05092001-06-14 08:53:38 +0000622 accumbits -= nsignbits;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000623 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000624
Tim Peters2a9b3672001-06-11 21:23:58 +0000625 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000626 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000627 if (j >= n)
628 goto Overflow;
629 ++j;
630 *p = (unsigned char)(accum & 0xff);
631 p += pincr;
632 accumbits -= 8;
633 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000634 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000635 }
636
637 /* Store the straggler (if any). */
638 assert(accumbits < 8);
639 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000640 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000641 if (j >= n)
642 goto Overflow;
643 ++j;
644 if (do_twos_comp) {
645 /* Fill leading bits of the byte with sign bits
646 (appropriately pretending that the long had an
647 infinite supply of sign bits). */
648 accum |= (~(twodigits)0) << accumbits;
649 }
650 *p = (unsigned char)(accum & 0xff);
651 p += pincr;
652 }
Tim Peters05607ad2001-06-13 21:01:27 +0000653 else if (j == n && n > 0 && is_signed) {
654 /* The main loop filled the byte array exactly, so the code
655 just above didn't get to ensure there's a sign bit, and the
656 loop below wouldn't add one either. Make sure a sign bit
657 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000658 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000659 int sign_bit_set = msb >= 0x80;
660 assert(accumbits == 0);
661 if (sign_bit_set == do_twos_comp)
662 return 0;
663 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000664 goto Overflow;
665 }
Tim Peters05607ad2001-06-13 21:01:27 +0000666
667 /* Fill remaining bytes with copies of the sign bit. */
668 {
669 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
670 for ( ; j < n; ++j, p += pincr)
671 *p = signbyte;
672 }
673
Tim Peters2a9b3672001-06-11 21:23:58 +0000674 return 0;
675
676Overflow:
677 PyErr_SetString(PyExc_OverflowError, "long too big to convert");
678 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000679
Tim Peters2a9b3672001-06-11 21:23:58 +0000680}
681
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000682double
683_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
684{
685/* NBITS_WANTED should be > the number of bits in a double's precision,
686 but small enough so that 2**NBITS_WANTED is within the normal double
687 range. nbitsneeded is set to 1 less than that because the most-significant
688 Python digit contains at least 1 significant bit, but we don't want to
689 bother counting them (catering to the worst case cheaply).
690
691 57 is one more than VAX-D double precision; I (Tim) don't know of a double
692 format with more precision than that; it's 1 larger so that we add in at
693 least one round bit to stand in for the ignored least-significant bits.
694*/
695#define NBITS_WANTED 57
696 PyLongObject *v;
697 double x;
698 const double multiplier = (double)(1L << SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000699 Py_ssize_t i;
700 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000701 int nbitsneeded;
702
703 if (vv == NULL || !PyLong_Check(vv)) {
704 PyErr_BadInternalCall();
705 return -1;
706 }
707 v = (PyLongObject *)vv;
708 i = v->ob_size;
709 sign = 1;
710 if (i < 0) {
711 sign = -1;
712 i = -(i);
713 }
714 else if (i == 0) {
715 *exponent = 0;
716 return 0.0;
717 }
718 --i;
719 x = (double)v->ob_digit[i];
720 nbitsneeded = NBITS_WANTED - 1;
721 /* Invariant: i Python digits remain unaccounted for. */
722 while (i > 0 && nbitsneeded > 0) {
723 --i;
724 x = x * multiplier + (double)v->ob_digit[i];
725 nbitsneeded -= SHIFT;
726 }
727 /* There are i digits we didn't shift in. Pretending they're all
728 zeroes, the true value is x * 2**(i*SHIFT). */
729 *exponent = i;
730 assert(x > 0.0);
731 return x * sign;
732#undef NBITS_WANTED
733}
734
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000735/* Get a C double from a long int object. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000736
737double
Tim Peters9f688bf2000-07-07 15:53:28 +0000738PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000739{
Thomas Wouters553489a2006-02-01 21:32:04 +0000740 int e = -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000741 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000742
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000743 if (vv == NULL || !PyLong_Check(vv)) {
744 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000745 return -1;
746 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000747 x = _PyLong_AsScaledDouble(vv, &e);
748 if (x == -1.0 && PyErr_Occurred())
749 return -1.0;
Thomas Wouters553489a2006-02-01 21:32:04 +0000750 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
751 set correctly after a successful _PyLong_AsScaledDouble() call */
752 assert(e >= 0);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000753 if (e > INT_MAX / SHIFT)
754 goto overflow;
755 errno = 0;
756 x = ldexp(x, e * SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +0000757 if (Py_OVERFLOWED(x))
Tim Peters9fffa3e2001-09-04 05:14:19 +0000758 goto overflow;
759 return x;
760
761overflow:
762 PyErr_SetString(PyExc_OverflowError,
763 "long int too large to convert to float");
764 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000765}
766
Guido van Rossum78694d91998-09-18 14:14:13 +0000767/* Create a new long (or int) object from a C pointer */
768
769PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000770PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000771{
Tim Peters70128a12001-06-16 08:48:40 +0000772#if SIZEOF_VOID_P <= SIZEOF_LONG
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000773 if ((long)p < 0)
774 return PyLong_FromUnsignedLong((unsigned long)p);
Guido van Rossum78694d91998-09-18 14:14:13 +0000775 return PyInt_FromLong((long)p);
776#else
Guido van Rossum78694d91998-09-18 14:14:13 +0000777
Tim Peters70128a12001-06-16 08:48:40 +0000778#ifndef HAVE_LONG_LONG
779# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
780#endif
781#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000782# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000783#endif
784 /* optimize null pointers */
785 if (p == NULL)
786 return PyInt_FromLong(0);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000787 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)p);
Tim Peters70128a12001-06-16 08:48:40 +0000788
789#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000790}
791
792/* Get a C pointer from a long object (or an int object in some cases) */
793
794void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000795PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000796{
797 /* This function will allow int or long objects. If vv is neither,
798 then the PyLong_AsLong*() functions will raise the exception:
799 PyExc_SystemError, "bad argument to internal function"
800 */
Tim Peters70128a12001-06-16 08:48:40 +0000801#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +0000802 long x;
803
Tim Peters70128a12001-06-16 08:48:40 +0000804 if (PyInt_Check(vv))
Guido van Rossum78694d91998-09-18 14:14:13 +0000805 x = PyInt_AS_LONG(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000806 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000807 x = PyLong_AsLong(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000808 else
809 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000810#else
Tim Peters70128a12001-06-16 08:48:40 +0000811
812#ifndef HAVE_LONG_LONG
813# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
814#endif
815#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000816# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000817#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000818 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000819
Tim Peters70128a12001-06-16 08:48:40 +0000820 if (PyInt_Check(vv))
Guido van Rossum78694d91998-09-18 14:14:13 +0000821 x = PyInt_AS_LONG(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000822 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000823 x = PyLong_AsLongLong(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000824 else
825 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000826
827#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000828
829 if (x == -1 && PyErr_Occurred())
830 return NULL;
831 return (void *)x;
832}
833
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000834#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000835
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000836/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000837 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000838 */
839
Tim Peterscf37dfc2001-06-14 18:42:50 +0000840#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +0000841
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000842/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000843
844PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000845PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000846{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000847 PY_LONG_LONG bytes = ival;
Tim Petersd1a7da62001-06-13 00:35:57 +0000848 int one = 1;
849 return _PyLong_FromByteArray(
850 (unsigned char *)&bytes,
851 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000852}
853
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000854/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +0000855
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000856PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000857PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000858{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000859 unsigned PY_LONG_LONG bytes = ival;
Tim Petersd1a7da62001-06-13 00:35:57 +0000860 int one = 1;
861 return _PyLong_FromByteArray(
862 (unsigned char *)&bytes,
863 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000864}
865
Martin v. Löwis18e16552006-02-15 17:27:45 +0000866/* Create a new long int object from a C Py_ssize_t. */
867
868PyObject *
869_PyLong_FromSsize_t(Py_ssize_t ival)
870{
871 Py_ssize_t bytes = ival;
872 int one = 1;
873 return _PyLong_FromByteArray(
874 (unsigned char *)&bytes,
875 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
876}
877
878/* Create a new long int object from a C size_t. */
879
880PyObject *
881_PyLong_FromSize_t(size_t ival)
882{
883 size_t bytes = ival;
884 int one = 1;
885 return _PyLong_FromByteArray(
886 (unsigned char *)&bytes,
887 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
888}
889
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000890/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000891 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000892
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000893PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000894PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000895{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000896 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +0000897 int one = 1;
898 int res;
899
Tim Petersd38b1c72001-09-30 05:09:37 +0000900 if (vv == NULL) {
901 PyErr_BadInternalCall();
902 return -1;
903 }
904 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +0000905 PyNumberMethods *nb;
906 PyObject *io;
Tim Petersd38b1c72001-09-30 05:09:37 +0000907 if (PyInt_Check(vv))
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000908 return (PY_LONG_LONG)PyInt_AsLong(vv);
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +0000909 if ((nb = vv->ob_type->tp_as_number) == NULL ||
910 nb->nb_int == NULL) {
911 PyErr_SetString(PyExc_TypeError, "an integer is required");
912 return -1;
913 }
914 io = (*nb->nb_int) (vv);
915 if (io == NULL)
916 return -1;
917 if (PyInt_Check(io)) {
918 bytes = PyInt_AsLong(io);
919 Py_DECREF(io);
920 return bytes;
921 }
922 if (PyLong_Check(io)) {
923 bytes = PyLong_AsLongLong(io);
924 Py_DECREF(io);
925 return bytes;
926 }
927 Py_DECREF(io);
928 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000929 return -1;
930 }
931
Tim Petersd1a7da62001-06-13 00:35:57 +0000932 res = _PyLong_AsByteArray(
933 (PyLongObject *)vv, (unsigned char *)&bytes,
934 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000935
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000936 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000937 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000938 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000939 else
940 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000941}
942
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000943/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000944 Return -1 and set an error if overflow occurs. */
945
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000946unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000947PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000948{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000949 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +0000950 int one = 1;
951 int res;
952
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000953 if (vv == NULL || !PyLong_Check(vv)) {
954 PyErr_BadInternalCall();
Skip Montanaro429433b2006-04-18 00:35:43 +0000955 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000956 }
957
Tim Petersd1a7da62001-06-13 00:35:57 +0000958 res = _PyLong_AsByteArray(
959 (PyLongObject *)vv, (unsigned char *)&bytes,
960 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000961
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000962 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000963 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000964 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000965 else
966 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000967}
Tim Petersd1a7da62001-06-13 00:35:57 +0000968
Thomas Hellera4ea6032003-04-17 18:55:45 +0000969/* Get a C unsigned long int from a long int object, ignoring the high bits.
970 Returns -1 and sets an error condition if an error occurs. */
971
972unsigned PY_LONG_LONG
973PyLong_AsUnsignedLongLongMask(PyObject *vv)
974{
975 register PyLongObject *v;
976 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000977 Py_ssize_t i;
978 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000979
980 if (vv == NULL || !PyLong_Check(vv)) {
981 PyErr_BadInternalCall();
982 return (unsigned long) -1;
983 }
984 v = (PyLongObject *)vv;
985 i = v->ob_size;
986 sign = 1;
987 x = 0;
988 if (i < 0) {
989 sign = -1;
990 i = -i;
991 }
992 while (--i >= 0) {
993 x = (x << SHIFT) + v->ob_digit[i];
994 }
995 return x * sign;
996}
Tim Petersd1a7da62001-06-13 00:35:57 +0000997#undef IS_LITTLE_ENDIAN
998
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000999#endif /* HAVE_LONG_LONG */
1000
Neil Schemenauerba872e22001-01-04 01:46:03 +00001001
1002static int
1003convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00001004 if (PyLong_Check(v)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001005 *a = (PyLongObject *) v;
1006 Py_INCREF(v);
1007 }
1008 else if (PyInt_Check(v)) {
1009 *a = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(v));
1010 }
1011 else {
1012 return 0;
1013 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001014 if (PyLong_Check(w)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001015 *b = (PyLongObject *) w;
1016 Py_INCREF(w);
1017 }
1018 else if (PyInt_Check(w)) {
1019 *b = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(w));
1020 }
1021 else {
1022 Py_DECREF(*a);
1023 return 0;
1024 }
1025 return 1;
1026}
1027
1028#define CONVERT_BINOP(v, w, a, b) \
1029 if (!convert_binop(v, w, a, b)) { \
1030 Py_INCREF(Py_NotImplemented); \
1031 return Py_NotImplemented; \
1032 }
1033
Tim Peters877a2122002-08-12 05:09:36 +00001034/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1035 * is modified in place, by adding y to it. Carries are propagated as far as
1036 * x[m-1], and the remaining carry (0 or 1) is returned.
1037 */
1038static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001039v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001040{
1041 int i;
1042 digit carry = 0;
1043
1044 assert(m >= n);
1045 for (i = 0; i < n; ++i) {
1046 carry += x[i] + y[i];
1047 x[i] = carry & MASK;
1048 carry >>= SHIFT;
1049 assert((carry & 1) == carry);
1050 }
1051 for (; carry && i < m; ++i) {
1052 carry += x[i];
1053 x[i] = carry & MASK;
1054 carry >>= SHIFT;
1055 assert((carry & 1) == carry);
1056 }
1057 return carry;
1058}
1059
1060/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1061 * is modified in place, by subtracting y from it. Borrows are propagated as
1062 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1063 */
1064static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001065v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001066{
1067 int i;
1068 digit borrow = 0;
1069
1070 assert(m >= n);
1071 for (i = 0; i < n; ++i) {
1072 borrow = x[i] - y[i] - borrow;
1073 x[i] = borrow & MASK;
1074 borrow >>= SHIFT;
1075 borrow &= 1; /* keep only 1 sign bit */
1076 }
1077 for (; borrow && i < m; ++i) {
1078 borrow = x[i] - borrow;
1079 x[i] = borrow & MASK;
1080 borrow >>= SHIFT;
1081 borrow &= 1;
1082 }
1083 return borrow;
1084}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001085
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001086/* Multiply by a single digit, ignoring the sign. */
1087
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001088static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001089mul1(PyLongObject *a, wdigit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001090{
1091 return muladd1(a, n, (digit)0);
1092}
1093
1094/* Multiply by a single digit and add a single digit, ignoring the sign. */
1095
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001096static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001097muladd1(PyLongObject *a, wdigit n, wdigit extra)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001098{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001099 Py_ssize_t size_a = ABS(a->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001100 PyLongObject *z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001101 twodigits carry = extra;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001102 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001103
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001104 if (z == NULL)
1105 return NULL;
1106 for (i = 0; i < size_a; ++i) {
1107 carry += (twodigits)a->ob_digit[i] * n;
Guido van Rossum2095d241997-04-09 19:41:24 +00001108 z->ob_digit[i] = (digit) (carry & MASK);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001109 carry >>= SHIFT;
1110 }
Guido van Rossum2095d241997-04-09 19:41:24 +00001111 z->ob_digit[i] = (digit) carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001112 return long_normalize(z);
1113}
1114
Tim Peters212e6142001-07-14 12:23:19 +00001115/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1116 in pout, and returning the remainder. pin and pout point at the LSD.
1117 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
1118 long_format, but that should be done with great care since longs are
1119 immutable. */
1120
1121static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001122inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001123{
1124 twodigits rem = 0;
1125
1126 assert(n > 0 && n <= MASK);
1127 pin += size;
1128 pout += size;
1129 while (--size >= 0) {
1130 digit hi;
1131 rem = (rem << SHIFT) + *--pin;
1132 *--pout = hi = (digit)(rem / n);
1133 rem -= hi * n;
1134 }
1135 return (digit)rem;
1136}
1137
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001138/* Divide a long integer by a digit, returning both the quotient
1139 (as function result) and the remainder (through *prem).
1140 The sign of a is ignored; n should not be zero. */
1141
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001142static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001143divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001144{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001145 const Py_ssize_t size = ABS(a->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001146 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001147
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001148 assert(n > 0 && n <= MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001149 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001150 if (z == NULL)
1151 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001152 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001153 return long_normalize(z);
1154}
1155
1156/* Convert a long int object to a string, using a given conversion base.
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001157 Return a string object.
Fred Drake121ee271999-12-23 15:41:28 +00001158 If base is 8 or 16, add the proper prefix '0' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001159
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001160static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001161long_format(PyObject *aa, int base, int addL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001162{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001163 register PyLongObject *a = (PyLongObject *)aa;
1164 PyStringObject *str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001165 Py_ssize_t i;
1166 const Py_ssize_t size_a = ABS(a->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001167 char *p;
1168 int bits;
1169 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001170
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001171 if (a == NULL || !PyLong_Check(a)) {
1172 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001173 return NULL;
1174 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001175 assert(base >= 2 && base <= 36);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001176
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001177 /* Compute a rough upper bound for the length of the string */
1178 i = base;
1179 bits = 0;
1180 while (i > 1) {
1181 ++bits;
1182 i >>= 1;
1183 }
Fred Drake121ee271999-12-23 15:41:28 +00001184 i = 5 + (addL ? 1 : 0) + (size_a*SHIFT + bits-1) / bits;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001185 str = (PyStringObject *) PyString_FromStringAndSize((char *)0, i);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001186 if (str == NULL)
1187 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001188 p = PyString_AS_STRING(str) + i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001189 *p = '\0';
Fred Drake121ee271999-12-23 15:41:28 +00001190 if (addL)
1191 *--p = 'L';
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001192 if (a->ob_size < 0)
1193 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001194
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001195 if (a->ob_size == 0) {
1196 *--p = '0';
1197 }
1198 else if ((base & (base - 1)) == 0) {
1199 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001200 twodigits accum = 0;
1201 int accumbits = 0; /* # of bits in accum */
1202 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001203 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001204 while ((i >>= 1) > 1)
1205 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001206
1207 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001208 accum |= (twodigits)a->ob_digit[i] << accumbits;
Tim Peters586b2e32001-07-15 09:11:14 +00001209 accumbits += SHIFT;
1210 assert(accumbits >= basebits);
1211 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001212 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001213 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001214 assert(p > PyString_AS_STRING(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001215 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001216 accumbits -= basebits;
1217 accum >>= basebits;
1218 } while (i < size_a-1 ? accumbits >= basebits :
1219 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001220 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001221 }
1222 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001223 /* Not 0, and base not a power of 2. Divide repeatedly by
1224 base, but for speed use the highest power of base that
1225 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001226 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001227 digit *pin = a->ob_digit;
1228 PyLongObject *scratch;
1229 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001230 digit powbase = base; /* powbase == base ** power */
1231 int power = 1;
1232 for (;;) {
1233 unsigned long newpow = powbase * (unsigned long)base;
1234 if (newpow >> SHIFT) /* doesn't fit in a digit */
1235 break;
1236 powbase = (digit)newpow;
1237 ++power;
1238 }
Tim Peters212e6142001-07-14 12:23:19 +00001239
1240 /* Get a scratch area for repeated division. */
1241 scratch = _PyLong_New(size);
1242 if (scratch == NULL) {
1243 Py_DECREF(str);
1244 return NULL;
1245 }
1246
1247 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001248 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001249 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001250 digit rem = inplace_divrem1(scratch->ob_digit,
1251 pin, size, powbase);
1252 pin = scratch->ob_digit; /* no need to use a again */
1253 if (pin[size - 1] == 0)
1254 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001255 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001256 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001257 Py_DECREF(str);
1258 return NULL;
1259 })
Tim Peters212e6142001-07-14 12:23:19 +00001260
1261 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001262 assert(ntostore > 0);
1263 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001264 digit nextrem = (digit)(rem / base);
1265 char c = (char)(rem - nextrem * base);
1266 assert(p > PyString_AS_STRING(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001267 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001268 *--p = c;
1269 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001270 --ntostore;
1271 /* Termination is a bit delicate: must not
1272 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001273 remaining quotient and rem are both 0. */
1274 } while (ntostore && (size || rem));
1275 } while (size != 0);
1276 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001277 }
1278
Guido van Rossum2c475421992-08-14 15:13:07 +00001279 if (base == 8) {
1280 if (size_a != 0)
1281 *--p = '0';
1282 }
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001283 else if (base == 16) {
1284 *--p = 'x';
1285 *--p = '0';
1286 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001287 else if (base != 10) {
1288 *--p = '#';
1289 *--p = '0' + base%10;
1290 if (base > 10)
1291 *--p = '0' + base/10;
1292 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001293 if (sign)
1294 *--p = sign;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001295 if (p != PyString_AS_STRING(str)) {
1296 char *q = PyString_AS_STRING(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001297 assert(p > q);
1298 do {
1299 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001300 q--;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001301 _PyString_Resize((PyObject **)&str,
1302 (int) (q - PyString_AS_STRING(str)));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001303 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001304 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001305}
1306
Tim Petersbf2674b2003-02-02 07:51:32 +00001307/* *str points to the first digit in a string of base base digits. base
1308 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1309 * non-digit (which may be *str!). A normalized long is returned.
1310 * The point to this routine is that it takes time linear in the number of
1311 * string characters.
1312 */
1313static PyLongObject *
1314long_from_binary_base(char **str, int base)
1315{
1316 char *p = *str;
1317 char *start = p;
1318 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001319 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001320 PyLongObject *z;
1321 twodigits accum;
1322 int bits_in_accum;
1323 digit *pdigit;
1324
1325 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1326 n = base;
1327 for (bits_per_char = -1; n; ++bits_per_char)
1328 n >>= 1;
1329 /* n <- total # of bits needed, while setting p to end-of-string */
1330 n = 0;
1331 for (;;) {
1332 int k = -1;
1333 char ch = *p;
1334
1335 if (ch <= '9')
1336 k = ch - '0';
1337 else if (ch >= 'a')
1338 k = ch - 'a' + 10;
1339 else if (ch >= 'A')
1340 k = ch - 'A' + 10;
1341 if (k < 0 || k >= base)
1342 break;
Tim Petersbf2674b2003-02-02 07:51:32 +00001343 ++p;
1344 }
1345 *str = p;
Tim Peters1a3b19a2003-02-02 17:33:53 +00001346 n = (p - start) * bits_per_char;
1347 if (n / bits_per_char != p - start) {
1348 PyErr_SetString(PyExc_ValueError,
1349 "long string too large to convert");
1350 return NULL;
1351 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001352 /* n <- # of Python digits needed, = ceiling(n/SHIFT). */
1353 n = (n + SHIFT - 1) / SHIFT;
1354 z = _PyLong_New(n);
1355 if (z == NULL)
1356 return NULL;
1357 /* Read string from right, and fill in long from left; i.e.,
1358 * from least to most significant in both.
1359 */
1360 accum = 0;
1361 bits_in_accum = 0;
1362 pdigit = z->ob_digit;
1363 while (--p >= start) {
Tim Petersc7bc0b92003-05-05 20:39:43 +00001364 int k;
1365 char ch = *p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001366
1367 if (ch <= '9')
1368 k = ch - '0';
1369 else if (ch >= 'a')
1370 k = ch - 'a' + 10;
1371 else {
1372 assert(ch >= 'A');
1373 k = ch - 'A' + 10;
1374 }
Tim Petersc7bc0b92003-05-05 20:39:43 +00001375 assert(k >= 0 && k < base);
1376 accum |= (twodigits)(k << bits_in_accum);
Tim Petersbf2674b2003-02-02 07:51:32 +00001377 bits_in_accum += bits_per_char;
1378 if (bits_in_accum >= SHIFT) {
1379 *pdigit++ = (digit)(accum & MASK);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001380 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001381 accum >>= SHIFT;
1382 bits_in_accum -= SHIFT;
1383 assert(bits_in_accum < SHIFT);
1384 }
1385 }
1386 if (bits_in_accum) {
1387 assert(bits_in_accum <= SHIFT);
1388 *pdigit++ = (digit)accum;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001389 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001390 }
1391 while (pdigit - z->ob_digit < n)
1392 *pdigit++ = 0;
1393 return long_normalize(z);
1394}
1395
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001396PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001397PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001398{
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001399 int sign = 1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001400 char *start, *orig_str = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001401 PyLongObject *z;
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001402 PyObject *strobj, *strrepr;
1403 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001404
Guido van Rossum472c04f1996-12-05 21:57:21 +00001405 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001406 PyErr_SetString(PyExc_ValueError,
Fred Drake661ea262000-10-24 19:57:45 +00001407 "long() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001408 return NULL;
1409 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001410 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001411 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001412 if (*str == '+')
1413 ++str;
1414 else if (*str == '-') {
1415 ++str;
1416 sign = -1;
1417 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001418 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001419 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001420 if (base == 0) {
1421 if (str[0] != '0')
1422 base = 10;
1423 else if (str[1] == 'x' || str[1] == 'X')
1424 base = 16;
1425 else
1426 base = 8;
1427 }
1428 if (base == 16 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
1429 str += 2;
Guido van Rossume6762971998-06-22 03:54:46 +00001430 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001431 if ((base & (base - 1)) == 0)
1432 z = long_from_binary_base(&str, base);
1433 else {
1434 z = _PyLong_New(0);
1435 for ( ; z != NULL; ++str) {
1436 int k = -1;
1437 PyLongObject *temp;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001438
Tim Petersbf2674b2003-02-02 07:51:32 +00001439 if (*str <= '9')
1440 k = *str - '0';
1441 else if (*str >= 'a')
1442 k = *str - 'a' + 10;
1443 else if (*str >= 'A')
1444 k = *str - 'A' + 10;
1445 if (k < 0 || k >= base)
1446 break;
1447 temp = muladd1(z, (digit)base, (digit)k);
1448 Py_DECREF(z);
1449 z = temp;
1450 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001451 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001452 if (z == NULL)
1453 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001454 if (str == start)
1455 goto onError;
Guido van Rossumc6913e71991-11-19 20:26:46 +00001456 if (sign < 0 && z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001457 z->ob_size = -(z->ob_size);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001458 if (*str == 'L' || *str == 'l')
1459 str++;
1460 while (*str && isspace(Py_CHARMASK(*str)))
1461 str++;
1462 if (*str != '\0')
1463 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001464 if (pend)
1465 *pend = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001466 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001467
1468 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00001469 Py_XDECREF(z);
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001470 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
1471 strobj = PyString_FromStringAndSize(orig_str, slen);
1472 if (strobj == NULL)
1473 return NULL;
1474 strrepr = PyObject_Repr(strobj);
1475 Py_DECREF(strobj);
1476 if (strrepr == NULL)
1477 return NULL;
1478 PyErr_Format(PyExc_ValueError,
1479 "invalid literal for long() with base %d: %s",
1480 base, PyString_AS_STRING(strrepr));
1481 Py_DECREF(strrepr);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001482 return NULL;
1483}
1484
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001485#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +00001486PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001487PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001488{
Walter Dörwald07e14762002-11-06 16:15:14 +00001489 PyObject *result;
Anthony Baxter377be112006-04-11 06:54:30 +00001490 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001491
Walter Dörwald07e14762002-11-06 16:15:14 +00001492 if (buffer == NULL)
1493 return NULL;
1494
1495 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1496 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001497 return NULL;
1498 }
Walter Dörwald07e14762002-11-06 16:15:14 +00001499 result = PyLong_FromString(buffer, NULL, base);
1500 PyMem_FREE(buffer);
1501 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001502}
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001503#endif
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001504
Tim Peters9f688bf2000-07-07 15:53:28 +00001505/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001506static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00001507 (PyLongObject *, PyLongObject *, PyLongObject **);
1508static PyObject *long_pos(PyLongObject *);
1509static int long_divrem(PyLongObject *, PyLongObject *,
1510 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001511
1512/* Long division with remainder, top-level routine */
1513
Guido van Rossume32e0141992-01-19 16:31:05 +00001514static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001515long_divrem(PyLongObject *a, PyLongObject *b,
1516 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001517{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001518 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001519 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001520
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001521 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001522 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +00001523 "long division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00001524 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001525 }
1526 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00001527 (size_a == size_b &&
1528 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001529 /* |a| < |b|. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001530 *pdiv = _PyLong_New(0);
1531 Py_INCREF(a);
1532 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00001533 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001534 }
1535 if (size_b == 1) {
1536 digit rem = 0;
1537 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001538 if (z == NULL)
1539 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001540 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001541 }
Guido van Rossume32e0141992-01-19 16:31:05 +00001542 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001543 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001544 if (z == NULL)
1545 return -1;
1546 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001547 /* Set the signs.
1548 The quotient z has the sign of a*b;
1549 the remainder r has the sign of a,
1550 so a = b*z + r. */
Guido van Rossume32e0141992-01-19 16:31:05 +00001551 if ((a->ob_size < 0) != (b->ob_size < 0))
1552 z->ob_size = -(z->ob_size);
1553 if (a->ob_size < 0 && (*prem)->ob_size != 0)
1554 (*prem)->ob_size = -((*prem)->ob_size);
1555 *pdiv = z;
1556 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001557}
1558
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001559/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001560
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001561static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001562x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001563{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001564 Py_ssize_t size_v = ABS(v1->ob_size), size_w = ABS(w1->ob_size);
Guido van Rossum2095d241997-04-09 19:41:24 +00001565 digit d = (digit) ((twodigits)BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001566 PyLongObject *v = mul1(v1, d);
1567 PyLongObject *w = mul1(w1, d);
1568 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001569 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001570
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001571 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001572 Py_XDECREF(v);
1573 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001574 return NULL;
1575 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001576
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001577 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001578 assert(v->ob_refcnt == 1); /* Since v will be used as accumulator! */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001579 assert(size_w == ABS(w->ob_size)); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00001580
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001581 size_v = ABS(v->ob_size);
Neal Norwitzc6a989a2006-05-10 06:57:58 +00001582 k = size_v - size_w;
1583 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001584
Neal Norwitzc6a989a2006-05-10 06:57:58 +00001585 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001586 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
1587 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001588 stwodigits carry = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001589 int i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001590
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001591 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001592 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001593 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001594 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001595 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001596 if (vj == w->ob_digit[size_w-1])
1597 q = MASK;
1598 else
1599 q = (((twodigits)vj << SHIFT) + v->ob_digit[j-1]) /
1600 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00001601
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001602 while (w->ob_digit[size_w-2]*q >
1603 ((
1604 ((twodigits)vj << SHIFT)
1605 + v->ob_digit[j-1]
1606 - q*w->ob_digit[size_w-1]
1607 ) << SHIFT)
1608 + v->ob_digit[j-2])
1609 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001610
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001611 for (i = 0; i < size_w && i+k < size_v; ++i) {
1612 twodigits z = w->ob_digit[i] * q;
Guido van Rossum2095d241997-04-09 19:41:24 +00001613 digit zz = (digit) (z >> SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001614 carry += v->ob_digit[i+k] - z
1615 + ((twodigits)zz << SHIFT);
Jeremy Hyltonfc61f9a2003-05-01 21:31:53 +00001616 v->ob_digit[i+k] = (digit)(carry & MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00001617 carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
1618 carry, SHIFT);
1619 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001620 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001621
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001622 if (i+k < size_v) {
1623 carry += v->ob_digit[i+k];
1624 v->ob_digit[i+k] = 0;
1625 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001626
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001627 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00001628 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001629 else {
1630 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00001631 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001632 carry = 0;
1633 for (i = 0; i < size_w && i+k < size_v; ++i) {
1634 carry += v->ob_digit[i+k] + w->ob_digit[i];
Jeremy Hyltonfc61f9a2003-05-01 21:31:53 +00001635 v->ob_digit[i+k] = (digit)(carry & MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00001636 carry = Py_ARITHMETIC_RIGHT_SHIFT(
1637 BASE_TWODIGITS_TYPE,
1638 carry, SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001639 }
1640 }
1641 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00001642
Guido van Rossumc206c761995-01-10 15:23:19 +00001643 if (a == NULL)
1644 *prem = NULL;
1645 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00001646 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00001647 *prem = divrem1(v, d, &d);
1648 /* d receives the (unused) remainder */
1649 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001650 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00001651 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00001652 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001653 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001654 Py_DECREF(v);
1655 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001656 return a;
1657}
1658
1659/* Methods */
1660
1661static void
Tim Peters9f688bf2000-07-07 15:53:28 +00001662long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001663{
Guido van Rossum9475a232001-10-05 20:51:39 +00001664 v->ob_type->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001665}
1666
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001667static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001668long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001669{
Fred Drake121ee271999-12-23 15:41:28 +00001670 return long_format(v, 10, 1);
1671}
1672
1673static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001674long_str(PyObject *v)
Fred Drake121ee271999-12-23 15:41:28 +00001675{
1676 return long_format(v, 10, 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001677}
1678
1679static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001680long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001681{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001682 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001683
Guido van Rossumc6913e71991-11-19 20:26:46 +00001684 if (a->ob_size != b->ob_size) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001685 if (ABS(a->ob_size) == 0 && ABS(b->ob_size) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00001686 sign = 0;
1687 else
1688 sign = a->ob_size - b->ob_size;
1689 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001690 else {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001691 Py_ssize_t i = ABS(a->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001692 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
1693 ;
1694 if (i < 0)
1695 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00001696 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001697 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00001698 if (a->ob_size < 0)
1699 sign = -sign;
1700 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001701 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001702 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001703}
1704
Guido van Rossum9bfef441993-03-29 10:43:31 +00001705static long
Tim Peters9f688bf2000-07-07 15:53:28 +00001706long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001707{
1708 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001709 Py_ssize_t i;
1710 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001711
1712 /* This is designed so that Python ints and longs with the
1713 same value hash to the same value, otherwise comparisons
1714 of mapping keys will turn out weird */
1715 i = v->ob_size;
1716 sign = 1;
1717 x = 0;
1718 if (i < 0) {
1719 sign = -1;
1720 i = -(i);
1721 }
Neal Norwitzd5a65a72003-02-23 23:11:41 +00001722#define LONG_BIT_SHIFT (8*sizeof(long) - SHIFT)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001723 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00001724 /* Force a native long #-bits (32 or 64) circular shift */
1725 x = ((x << SHIFT) & ~MASK) | ((x >> LONG_BIT_SHIFT) & MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001726 x += v->ob_digit[i];
1727 }
Neal Norwitzd5a65a72003-02-23 23:11:41 +00001728#undef LONG_BIT_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00001729 x = x * sign;
1730 if (x == -1)
1731 x = -2;
1732 return x;
1733}
1734
1735
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001736/* Add the absolute values of two long integers. */
1737
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001738static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001739x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001740{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001741 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001742 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001743 int i;
1744 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00001745
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001746 /* Ensure a is the larger of the two: */
1747 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001748 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00001749 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001750 size_a = size_b;
1751 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001752 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001753 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001754 if (z == NULL)
1755 return NULL;
1756 for (i = 0; i < size_b; ++i) {
1757 carry += a->ob_digit[i] + b->ob_digit[i];
1758 z->ob_digit[i] = carry & MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001759 carry >>= SHIFT;
1760 }
1761 for (; i < size_a; ++i) {
1762 carry += a->ob_digit[i];
1763 z->ob_digit[i] = carry & MASK;
1764 carry >>= SHIFT;
1765 }
1766 z->ob_digit[i] = carry;
1767 return long_normalize(z);
1768}
1769
1770/* Subtract the absolute values of two integers. */
1771
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001772static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001773x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001774{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001775 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001776 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001777 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001778 int sign = 1;
1779 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00001780
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001781 /* Ensure a is the larger of the two: */
1782 if (size_a < size_b) {
1783 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001784 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00001785 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001786 size_a = size_b;
1787 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001788 }
1789 else if (size_a == size_b) {
1790 /* Find highest digit where a and b differ: */
1791 i = size_a;
1792 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
1793 ;
1794 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001795 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001796 if (a->ob_digit[i] < b->ob_digit[i]) {
1797 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001798 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001799 }
1800 size_a = size_b = i+1;
1801 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001802 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001803 if (z == NULL)
1804 return NULL;
1805 for (i = 0; i < size_b; ++i) {
1806 /* The following assumes unsigned arithmetic
1807 works module 2**N for some N>SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001808 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001809 z->ob_digit[i] = borrow & MASK;
1810 borrow >>= SHIFT;
1811 borrow &= 1; /* Keep only one sign bit */
1812 }
1813 for (; i < size_a; ++i) {
1814 borrow = a->ob_digit[i] - borrow;
1815 z->ob_digit[i] = borrow & MASK;
1816 borrow >>= SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00001817 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001818 }
1819 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00001820 if (sign < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001821 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001822 return long_normalize(z);
1823}
1824
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001825static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00001826long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001827{
Neil Schemenauerba872e22001-01-04 01:46:03 +00001828 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00001829
Neil Schemenauerba872e22001-01-04 01:46:03 +00001830 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
1831
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001832 if (a->ob_size < 0) {
1833 if (b->ob_size < 0) {
1834 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00001835 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001836 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001837 }
1838 else
1839 z = x_sub(b, a);
1840 }
1841 else {
1842 if (b->ob_size < 0)
1843 z = x_sub(a, b);
1844 else
1845 z = x_add(a, b);
1846 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00001847 Py_DECREF(a);
1848 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001849 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001850}
1851
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001852static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00001853long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001854{
Neil Schemenauerba872e22001-01-04 01:46:03 +00001855 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001856
Neil Schemenauerba872e22001-01-04 01:46:03 +00001857 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
1858
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001859 if (a->ob_size < 0) {
1860 if (b->ob_size < 0)
1861 z = x_sub(a, b);
1862 else
1863 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00001864 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001865 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001866 }
1867 else {
1868 if (b->ob_size < 0)
1869 z = x_add(a, b);
1870 else
1871 z = x_sub(a, b);
1872 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00001873 Py_DECREF(a);
1874 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001875 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001876}
1877
Tim Peters5af4e6c2002-08-12 02:31:19 +00001878/* Grade school multiplication, ignoring the signs.
1879 * Returns the absolute value of the product, or NULL if error.
1880 */
1881static PyLongObject *
1882x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001883{
Tim Peters5af4e6c2002-08-12 02:31:19 +00001884 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001885 Py_ssize_t size_a = ABS(a->ob_size);
1886 Py_ssize_t size_b = ABS(b->ob_size);
1887 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00001888
Tim Peters5af4e6c2002-08-12 02:31:19 +00001889 z = _PyLong_New(size_a + size_b);
1890 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001891 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001892
1893 memset(z->ob_digit, 0, z->ob_size * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00001894 if (a == b) {
1895 /* Efficient squaring per HAC, Algorithm 14.16:
1896 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
1897 * Gives slightly less than a 2x speedup when a == b,
1898 * via exploiting that each entry in the multiplication
1899 * pyramid appears twice (except for the size_a squares).
1900 */
1901 for (i = 0; i < size_a; ++i) {
1902 twodigits carry;
1903 twodigits f = a->ob_digit[i];
1904 digit *pz = z->ob_digit + (i << 1);
1905 digit *pa = a->ob_digit + i + 1;
1906 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001907
Tim Peters0973b992004-08-29 22:16:50 +00001908 SIGCHECK({
1909 Py_DECREF(z);
1910 return NULL;
1911 })
1912
1913 carry = *pz + f * f;
1914 *pz++ = (digit)(carry & MASK);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001915 carry >>= SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00001916 assert(carry <= MASK);
1917
1918 /* Now f is added in twice in each column of the
1919 * pyramid it appears. Same as adding f<<1 once.
1920 */
1921 f <<= 1;
1922 while (pa < paend) {
1923 carry += *pz + *pa++ * f;
1924 *pz++ = (digit)(carry & MASK);
1925 carry >>= SHIFT;
1926 assert(carry <= (MASK << 1));
1927 }
1928 if (carry) {
1929 carry += *pz;
1930 *pz++ = (digit)(carry & MASK);
1931 carry >>= SHIFT;
1932 }
1933 if (carry)
1934 *pz += (digit)(carry & MASK);
1935 assert((carry >> SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001936 }
Tim Peters0973b992004-08-29 22:16:50 +00001937 }
1938 else { /* a is not the same as b -- gradeschool long mult */
1939 for (i = 0; i < size_a; ++i) {
1940 twodigits carry = 0;
1941 twodigits f = a->ob_digit[i];
1942 digit *pz = z->ob_digit + i;
1943 digit *pb = b->ob_digit;
1944 digit *pbend = b->ob_digit + size_b;
1945
1946 SIGCHECK({
1947 Py_DECREF(z);
1948 return NULL;
1949 })
1950
1951 while (pb < pbend) {
1952 carry += *pz + *pb++ * f;
1953 *pz++ = (digit)(carry & MASK);
1954 carry >>= SHIFT;
1955 assert(carry <= MASK);
1956 }
1957 if (carry)
1958 *pz += (digit)(carry & MASK);
1959 assert((carry >> SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001960 }
1961 }
Tim Peters44121a62002-08-12 06:17:58 +00001962 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001963}
1964
1965/* A helper for Karatsuba multiplication (k_mul).
1966 Takes a long "n" and an integer "size" representing the place to
1967 split, and sets low and high such that abs(n) == (high << size) + low,
1968 viewing the shift as being by digits. The sign bit is ignored, and
1969 the return values are >= 0.
1970 Returns 0 on success, -1 on failure.
1971*/
1972static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001973kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00001974{
1975 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001976 Py_ssize_t size_lo, size_hi;
1977 const Py_ssize_t size_n = ABS(n->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001978
1979 size_lo = MIN(size_n, size);
1980 size_hi = size_n - size_lo;
1981
1982 if ((hi = _PyLong_New(size_hi)) == NULL)
1983 return -1;
1984 if ((lo = _PyLong_New(size_lo)) == NULL) {
1985 Py_DECREF(hi);
1986 return -1;
1987 }
1988
1989 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
1990 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
1991
1992 *high = long_normalize(hi);
1993 *low = long_normalize(lo);
1994 return 0;
1995}
1996
Tim Peters60004642002-08-12 22:01:34 +00001997static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
1998
Tim Peters5af4e6c2002-08-12 02:31:19 +00001999/* Karatsuba multiplication. Ignores the input signs, and returns the
2000 * absolute value of the product (or NULL if error).
2001 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2002 */
2003static PyLongObject *
2004k_mul(PyLongObject *a, PyLongObject *b)
2005{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002006 Py_ssize_t asize = ABS(a->ob_size);
2007 Py_ssize_t bsize = ABS(b->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002008 PyLongObject *ah = NULL;
2009 PyLongObject *al = NULL;
2010 PyLongObject *bh = NULL;
2011 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002012 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002013 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002014 Py_ssize_t shift; /* the number of digits we split off */
2015 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002016
Tim Peters5af4e6c2002-08-12 02:31:19 +00002017 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2018 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2019 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002020 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002021 * By picking X to be a power of 2, "*X" is just shifting, and it's
2022 * been reduced to 3 multiplies on numbers half the size.
2023 */
2024
Tim Petersfc07e562002-08-12 02:54:10 +00002025 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002026 * is largest.
2027 */
Tim Peters738eda72002-08-12 15:08:20 +00002028 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002029 t1 = a;
2030 a = b;
2031 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002032
2033 i = asize;
2034 asize = bsize;
2035 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002036 }
2037
2038 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002039 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2040 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002041 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002042 return _PyLong_New(0);
2043 else
2044 return x_mul(a, b);
2045 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002046
Tim Peters60004642002-08-12 22:01:34 +00002047 /* If a is small compared to b, splitting on b gives a degenerate
2048 * case with ah==0, and Karatsuba may be (even much) less efficient
2049 * than "grade school" then. However, we can still win, by viewing
2050 * b as a string of "big digits", each of width a->ob_size. That
2051 * leads to a sequence of balanced calls to k_mul.
2052 */
2053 if (2 * asize <= bsize)
2054 return k_lopsided_mul(a, b);
2055
Tim Petersd6974a52002-08-13 20:37:51 +00002056 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002057 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002058 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Tim Petersd6974a52002-08-13 20:37:51 +00002059 assert(ah->ob_size > 0); /* the split isn't degenerate */
2060
Tim Peters0973b992004-08-29 22:16:50 +00002061 if (a == b) {
2062 bh = ah;
2063 bl = al;
2064 Py_INCREF(bh);
2065 Py_INCREF(bl);
2066 }
2067 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002068
Tim Petersd64c1de2002-08-12 17:36:03 +00002069 /* The plan:
2070 * 1. Allocate result space (asize + bsize digits: that's always
2071 * enough).
2072 * 2. Compute ah*bh, and copy into result at 2*shift.
2073 * 3. Compute al*bl, and copy into result at 0. Note that this
2074 * can't overlap with #2.
2075 * 4. Subtract al*bl from the result, starting at shift. This may
2076 * underflow (borrow out of the high digit), but we don't care:
2077 * we're effectively doing unsigned arithmetic mod
2078 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2079 * borrows and carries out of the high digit can be ignored.
2080 * 5. Subtract ah*bh from the result, starting at shift.
2081 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2082 * at shift.
2083 */
2084
2085 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002086 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002087 if (ret == NULL) goto fail;
2088#ifdef Py_DEBUG
2089 /* Fill with trash, to catch reference to uninitialized digits. */
2090 memset(ret->ob_digit, 0xDF, ret->ob_size * sizeof(digit));
2091#endif
Tim Peters44121a62002-08-12 06:17:58 +00002092
Tim Petersd64c1de2002-08-12 17:36:03 +00002093 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002094 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
2095 assert(t1->ob_size >= 0);
2096 assert(2*shift + t1->ob_size <= ret->ob_size);
2097 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
2098 t1->ob_size * sizeof(digit));
2099
2100 /* Zero-out the digits higher than the ah*bh copy. */
2101 i = ret->ob_size - 2*shift - t1->ob_size;
Tim Peters44121a62002-08-12 06:17:58 +00002102 if (i)
Tim Peters738eda72002-08-12 15:08:20 +00002103 memset(ret->ob_digit + 2*shift + t1->ob_size, 0,
Tim Peters44121a62002-08-12 06:17:58 +00002104 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002105
Tim Petersd64c1de2002-08-12 17:36:03 +00002106 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002107 if ((t2 = k_mul(al, bl)) == NULL) {
2108 Py_DECREF(t1);
2109 goto fail;
2110 }
2111 assert(t2->ob_size >= 0);
2112 assert(t2->ob_size <= 2*shift); /* no overlap with high digits */
2113 memcpy(ret->ob_digit, t2->ob_digit, t2->ob_size * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002114
2115 /* Zero out remaining digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002116 i = 2*shift - t2->ob_size; /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002117 if (i)
Tim Peters738eda72002-08-12 15:08:20 +00002118 memset(ret->ob_digit + t2->ob_size, 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002119
Tim Petersd64c1de2002-08-12 17:36:03 +00002120 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2121 * because it's fresher in cache.
2122 */
Tim Peters738eda72002-08-12 15:08:20 +00002123 i = ret->ob_size - shift; /* # digits after shift */
Tim Petersd64c1de2002-08-12 17:36:03 +00002124 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, t2->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002125 Py_DECREF(t2);
2126
Tim Petersd64c1de2002-08-12 17:36:03 +00002127 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, t1->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002128 Py_DECREF(t1);
2129
Tim Petersd64c1de2002-08-12 17:36:03 +00002130 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002131 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2132 Py_DECREF(ah);
2133 Py_DECREF(al);
2134 ah = al = NULL;
2135
Tim Peters0973b992004-08-29 22:16:50 +00002136 if (a == b) {
2137 t2 = t1;
2138 Py_INCREF(t2);
2139 }
2140 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002141 Py_DECREF(t1);
2142 goto fail;
2143 }
2144 Py_DECREF(bh);
2145 Py_DECREF(bl);
2146 bh = bl = NULL;
2147
Tim Peters738eda72002-08-12 15:08:20 +00002148 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002149 Py_DECREF(t1);
2150 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002151 if (t3 == NULL) goto fail;
Tim Peters547607c2002-08-12 19:43:49 +00002152 assert(t3->ob_size >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002153
Tim Petersd6974a52002-08-13 20:37:51 +00002154 /* Add t3. It's not obvious why we can't run out of room here.
2155 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002156 */
Tim Petersd64c1de2002-08-12 17:36:03 +00002157 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, t3->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002158 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002159
Tim Peters5af4e6c2002-08-12 02:31:19 +00002160 return long_normalize(ret);
2161
2162 fail:
2163 Py_XDECREF(ret);
2164 Py_XDECREF(ah);
2165 Py_XDECREF(al);
2166 Py_XDECREF(bh);
2167 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002168 return NULL;
2169}
2170
Tim Petersd6974a52002-08-13 20:37:51 +00002171/* (*) Why adding t3 can't "run out of room" above.
2172
Tim Petersab86c2b2002-08-15 20:06:00 +00002173Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2174to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002175
Tim Petersab86c2b2002-08-15 20:06:00 +000021761. For any integer i, i = c(i/2) + f(i/2). In particular,
2177 bsize = c(bsize/2) + f(bsize/2).
21782. shift = f(bsize/2)
21793. asize <= bsize
21804. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2181 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002182
Tim Petersab86c2b2002-08-15 20:06:00 +00002183We allocated asize + bsize result digits, and add t3 into them at an offset
2184of shift. This leaves asize+bsize-shift allocated digit positions for t3
2185to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2186asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002187
Tim Petersab86c2b2002-08-15 20:06:00 +00002188bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2189at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002190
Tim Petersab86c2b2002-08-15 20:06:00 +00002191If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2192digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2193most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002194
Tim Petersab86c2b2002-08-15 20:06:00 +00002195The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002196
Tim Petersab86c2b2002-08-15 20:06:00 +00002197 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002198
Tim Petersab86c2b2002-08-15 20:06:00 +00002199and we have asize + c(bsize/2) available digit positions. We need to show
2200this is always enough. An instance of c(bsize/2) cancels out in both, so
2201the question reduces to whether asize digits is enough to hold
2202(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2203then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2204asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
2205digit is enough to hold 2 bits. This is so since SHIFT=15 >= 2. If
2206asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002207c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2208is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2209bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002210
Tim Peters48d52c02002-08-14 17:07:32 +00002211Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2212clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2213ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002214*/
2215
Tim Peters60004642002-08-12 22:01:34 +00002216/* b has at least twice the digits of a, and a is big enough that Karatsuba
2217 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2218 * of slices, each with a->ob_size digits, and multiply the slices by a,
2219 * one at a time. This gives k_mul balanced inputs to work with, and is
2220 * also cache-friendly (we compute one double-width slice of the result
2221 * at a time, then move on, never bactracking except for the helpful
2222 * single-width slice overlap between successive partial sums).
2223 */
2224static PyLongObject *
2225k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2226{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002227 const Py_ssize_t asize = ABS(a->ob_size);
2228 Py_ssize_t bsize = ABS(b->ob_size);
2229 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002230 PyLongObject *ret;
2231 PyLongObject *bslice = NULL;
2232
2233 assert(asize > KARATSUBA_CUTOFF);
2234 assert(2 * asize <= bsize);
2235
2236 /* Allocate result space, and zero it out. */
2237 ret = _PyLong_New(asize + bsize);
2238 if (ret == NULL)
2239 return NULL;
2240 memset(ret->ob_digit, 0, ret->ob_size * sizeof(digit));
2241
2242 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002243 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002244 if (bslice == NULL)
2245 goto fail;
2246
2247 nbdone = 0;
2248 while (bsize > 0) {
2249 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002250 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002251
2252 /* Multiply the next slice of b by a. */
2253 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2254 nbtouse * sizeof(digit));
2255 bslice->ob_size = nbtouse;
2256 product = k_mul(a, bslice);
2257 if (product == NULL)
2258 goto fail;
2259
2260 /* Add into result. */
2261 (void)v_iadd(ret->ob_digit + nbdone, ret->ob_size - nbdone,
2262 product->ob_digit, product->ob_size);
2263 Py_DECREF(product);
2264
2265 bsize -= nbtouse;
2266 nbdone += nbtouse;
2267 }
2268
2269 Py_DECREF(bslice);
2270 return long_normalize(ret);
2271
2272 fail:
2273 Py_DECREF(ret);
2274 Py_XDECREF(bslice);
2275 return NULL;
2276}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002277
2278static PyObject *
2279long_mul(PyLongObject *v, PyLongObject *w)
2280{
2281 PyLongObject *a, *b, *z;
2282
2283 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002284 Py_INCREF(Py_NotImplemented);
2285 return Py_NotImplemented;
2286 }
2287
Tim Petersd64c1de2002-08-12 17:36:03 +00002288 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002289 /* Negate if exactly one of the inputs is negative. */
2290 if (((a->ob_size ^ b->ob_size) < 0) && z)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002291 z->ob_size = -(z->ob_size);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002292 Py_DECREF(a);
2293 Py_DECREF(b);
Tim Peters9973d742002-08-15 19:41:06 +00002294 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002295}
2296
Guido van Rossume32e0141992-01-19 16:31:05 +00002297/* The / and % operators are now defined in terms of divmod().
2298 The expression a mod b has the value a - b*floor(a/b).
2299 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002300 |a| by |b|, with the sign of a. This is also expressed
2301 as a - b*trunc(a/b), if trunc truncates towards zero.
2302 Some examples:
2303 a b a rem b a mod b
2304 13 10 3 3
2305 -13 10 -3 7
2306 13 -10 3 -7
2307 -13 -10 -3 -3
2308 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002309 have different signs. We then subtract one from the 'div'
2310 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002311
Tim Peters47e52ee2004-08-30 02:44:38 +00002312/* Compute
2313 * *pdiv, *pmod = divmod(v, w)
2314 * NULL can be passed for pdiv or pmod, in which case that part of
2315 * the result is simply thrown away. The caller owns a reference to
2316 * each of these it requests (does not pass NULL for).
2317 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002318static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002319l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002320 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002321{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002322 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002323
Guido van Rossume32e0141992-01-19 16:31:05 +00002324 if (long_divrem(v, w, &div, &mod) < 0)
2325 return -1;
Guido van Rossum472c04f1996-12-05 21:57:21 +00002326 if ((mod->ob_size < 0 && w->ob_size > 0) ||
2327 (mod->ob_size > 0 && w->ob_size < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002328 PyLongObject *temp;
2329 PyLongObject *one;
2330 temp = (PyLongObject *) long_add(mod, w);
2331 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002332 mod = temp;
2333 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002334 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002335 return -1;
2336 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002337 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002338 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002339 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2340 Py_DECREF(mod);
2341 Py_DECREF(div);
2342 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002343 return -1;
2344 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002345 Py_DECREF(one);
2346 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002347 div = temp;
2348 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002349 if (pdiv != NULL)
2350 *pdiv = div;
2351 else
2352 Py_DECREF(div);
2353
2354 if (pmod != NULL)
2355 *pmod = mod;
2356 else
2357 Py_DECREF(mod);
2358
Guido van Rossume32e0141992-01-19 16:31:05 +00002359 return 0;
2360}
2361
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002362static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002363long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002364{
Tim Peters47e52ee2004-08-30 02:44:38 +00002365 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002366
2367 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002368 if (l_divmod(a, b, &div, NULL) < 0)
2369 div = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002370 Py_DECREF(a);
2371 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002372 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002373}
2374
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002375static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +00002376long_classic_div(PyObject *v, PyObject *w)
2377{
Tim Peters47e52ee2004-08-30 02:44:38 +00002378 PyLongObject *a, *b, *div;
Guido van Rossum393661d2001-08-31 17:40:15 +00002379
2380 CONVERT_BINOP(v, w, &a, &b);
Guido van Rossum393661d2001-08-31 17:40:15 +00002381 if (Py_DivisionWarningFlag &&
2382 PyErr_Warn(PyExc_DeprecationWarning, "classic long division") < 0)
2383 div = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00002384 else if (l_divmod(a, b, &div, NULL) < 0)
Guido van Rossum393661d2001-08-31 17:40:15 +00002385 div = NULL;
Guido van Rossum393661d2001-08-31 17:40:15 +00002386 Py_DECREF(a);
2387 Py_DECREF(b);
2388 return (PyObject *)div;
2389}
2390
2391static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00002392long_true_divide(PyObject *v, PyObject *w)
2393{
Tim Peterse2a60002001-09-04 06:17:36 +00002394 PyLongObject *a, *b;
2395 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002396 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002397
2398 CONVERT_BINOP(v, w, &a, &b);
2399 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2400 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002401 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
2402 Py_DECREF(a);
2403 Py_DECREF(b);
2404 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002405 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002406 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2407 but should really be set correctly after sucessful calls to
2408 _PyLong_AsScaledDouble() */
2409 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002410
2411 if (bd == 0.0) {
2412 PyErr_SetString(PyExc_ZeroDivisionError,
2413 "long division or modulo by zero");
2414 return NULL;
2415 }
2416
2417 /* True value is very close to ad/bd * 2**(SHIFT*(aexp-bexp)) */
2418 ad /= bd; /* overflow/underflow impossible here */
2419 aexp -= bexp;
2420 if (aexp > INT_MAX / SHIFT)
2421 goto overflow;
Tim Peterse56ed9b2001-09-06 21:59:14 +00002422 else if (aexp < -(INT_MAX / SHIFT))
2423 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002424 errno = 0;
2425 ad = ldexp(ad, aexp * SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002426 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002427 goto overflow;
2428 return PyFloat_FromDouble(ad);
2429
2430overflow:
2431 PyErr_SetString(PyExc_OverflowError,
2432 "long/long too large for a float");
2433 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002434
Tim Peters20dab9f2001-09-04 05:31:47 +00002435}
2436
2437static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002438long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002439{
Tim Peters47e52ee2004-08-30 02:44:38 +00002440 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002441
2442 CONVERT_BINOP(v, w, &a, &b);
2443
Tim Peters47e52ee2004-08-30 02:44:38 +00002444 if (l_divmod(a, b, NULL, &mod) < 0)
2445 mod = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002446 Py_DECREF(a);
2447 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002448 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002449}
2450
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002451static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002452long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002453{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002454 PyLongObject *a, *b, *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002455 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002456
2457 CONVERT_BINOP(v, w, &a, &b);
2458
2459 if (l_divmod(a, b, &div, &mod) < 0) {
2460 Py_DECREF(a);
2461 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002462 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002463 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002464 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002465 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002466 PyTuple_SetItem(z, 0, (PyObject *) div);
2467 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002468 }
2469 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002470 Py_DECREF(div);
2471 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002472 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002473 Py_DECREF(a);
2474 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002475 return z;
2476}
2477
Tim Peters47e52ee2004-08-30 02:44:38 +00002478/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002479static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002480long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002481{
Tim Peters47e52ee2004-08-30 02:44:38 +00002482 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
2483 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002484
Tim Peters47e52ee2004-08-30 02:44:38 +00002485 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002486 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00002487 PyLongObject *temp = NULL;
2488
2489 /* 5-ary values. If the exponent is large enough, table is
2490 * precomputed so that table[i] == a**i % c for i in range(32).
2491 */
2492 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2493 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2494
2495 /* a, b, c = v, w, x */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002496 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002497 if (PyLong_Check(x)) {
2498 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002499 Py_INCREF(x);
2500 }
Tim Petersde7990b2005-07-17 23:45:23 +00002501 else if (PyInt_Check(x)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002502 c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x));
Tim Petersde7990b2005-07-17 23:45:23 +00002503 if (c == NULL)
2504 goto Error;
2505 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002506 else if (x == Py_None)
2507 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002508 else {
2509 Py_DECREF(a);
2510 Py_DECREF(b);
2511 Py_INCREF(Py_NotImplemented);
2512 return Py_NotImplemented;
2513 }
Tim Peters4c483c42001-09-05 06:24:58 +00002514
Tim Peters47e52ee2004-08-30 02:44:38 +00002515 if (b->ob_size < 0) { /* if exponent is negative */
2516 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00002517 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00002518 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00002519 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00002520 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002521 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00002522 /* else return a float. This works because we know
2523 that this calls float_pow() which converts its
2524 arguments to double. */
2525 Py_DECREF(a);
2526 Py_DECREF(b);
2527 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002528 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002529 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002530
2531 if (c) {
2532 /* if modulus == 0:
2533 raise ValueError() */
2534 if (c->ob_size == 0) {
2535 PyErr_SetString(PyExc_ValueError,
2536 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00002537 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002538 }
2539
2540 /* if modulus < 0:
2541 negativeOutput = True
2542 modulus = -modulus */
2543 if (c->ob_size < 0) {
2544 negativeOutput = 1;
2545 temp = (PyLongObject *)_PyLong_Copy(c);
2546 if (temp == NULL)
2547 goto Error;
2548 Py_DECREF(c);
2549 c = temp;
2550 temp = NULL;
2551 c->ob_size = - c->ob_size;
2552 }
2553
2554 /* if modulus == 1:
2555 return 0 */
2556 if ((c->ob_size == 1) && (c->ob_digit[0] == 1)) {
2557 z = (PyLongObject *)PyLong_FromLong(0L);
2558 goto Done;
2559 }
2560
2561 /* if base < 0:
2562 base = base % modulus
2563 Having the base positive just makes things easier. */
2564 if (a->ob_size < 0) {
2565 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00002566 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002567 Py_DECREF(a);
2568 a = temp;
2569 temp = NULL;
2570 }
2571 }
2572
2573 /* At this point a, b, and c are guaranteed non-negative UNLESS
2574 c is NULL, in which case a may be negative. */
2575
2576 z = (PyLongObject *)PyLong_FromLong(1L);
2577 if (z == NULL)
2578 goto Error;
2579
2580 /* Perform a modular reduction, X = X % c, but leave X alone if c
2581 * is NULL.
2582 */
2583#define REDUCE(X) \
2584 if (c != NULL) { \
2585 if (l_divmod(X, c, NULL, &temp) < 0) \
2586 goto Error; \
2587 Py_XDECREF(X); \
2588 X = temp; \
2589 temp = NULL; \
2590 }
2591
2592 /* Multiply two values, then reduce the result:
2593 result = X*Y % c. If c is NULL, skip the mod. */
2594#define MULT(X, Y, result) \
2595{ \
2596 temp = (PyLongObject *)long_mul(X, Y); \
2597 if (temp == NULL) \
2598 goto Error; \
2599 Py_XDECREF(result); \
2600 result = temp; \
2601 temp = NULL; \
2602 REDUCE(result) \
2603}
2604
2605 if (b->ob_size <= FIVEARY_CUTOFF) {
2606 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
2607 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
2608 for (i = b->ob_size - 1; i >= 0; --i) {
2609 digit bi = b->ob_digit[i];
2610
2611 for (j = 1 << (SHIFT-1); j != 0; j >>= 1) {
2612 MULT(z, z, z)
2613 if (bi & j)
2614 MULT(z, a, z)
2615 }
2616 }
2617 }
2618 else {
2619 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
2620 Py_INCREF(z); /* still holds 1L */
2621 table[0] = z;
2622 for (i = 1; i < 32; ++i)
2623 MULT(table[i-1], a, table[i])
2624
2625 for (i = b->ob_size - 1; i >= 0; --i) {
2626 const digit bi = b->ob_digit[i];
2627
2628 for (j = SHIFT - 5; j >= 0; j -= 5) {
2629 const int index = (bi >> j) & 0x1f;
2630 for (k = 0; k < 5; ++k)
2631 MULT(z, z, z)
2632 if (index)
2633 MULT(z, table[index], z)
2634 }
2635 }
2636 }
2637
2638 if (negativeOutput && (z->ob_size != 0)) {
2639 temp = (PyLongObject *)long_sub(z, c);
2640 if (temp == NULL)
2641 goto Error;
2642 Py_DECREF(z);
2643 z = temp;
2644 temp = NULL;
2645 }
2646 goto Done;
2647
2648 Error:
2649 if (z != NULL) {
2650 Py_DECREF(z);
2651 z = NULL;
2652 }
2653 /* fall through */
2654 Done:
Tim Peters47e52ee2004-08-30 02:44:38 +00002655 if (b->ob_size > FIVEARY_CUTOFF) {
2656 for (i = 0; i < 32; ++i)
2657 Py_XDECREF(table[i]);
2658 }
Tim Petersde7990b2005-07-17 23:45:23 +00002659 Py_DECREF(a);
2660 Py_DECREF(b);
2661 Py_XDECREF(c);
2662 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002663 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002664}
2665
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002666static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002667long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002668{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002669 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002670 PyLongObject *x;
2671 PyLongObject *w;
2672 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002673 if (w == NULL)
2674 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002675 x = (PyLongObject *) long_add(v, w);
2676 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002677 if (x == NULL)
2678 return NULL;
Tim Peters40c397d2001-09-11 23:24:22 +00002679 x->ob_size = -(x->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002680 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002681}
2682
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002683static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002684long_pos(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002685{
Tim Peters69c2de32001-09-11 22:31:33 +00002686 if (PyLong_CheckExact(v)) {
2687 Py_INCREF(v);
2688 return (PyObject *)v;
2689 }
2690 else
2691 return _PyLong_Copy(v);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002692}
2693
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002694static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002695long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002696{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002697 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002698 if (v->ob_size == 0 && PyLong_CheckExact(v)) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002699 /* -0 == 0 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002700 Py_INCREF(v);
2701 return (PyObject *) v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002702 }
Tim Peters69c2de32001-09-11 22:31:33 +00002703 z = (PyLongObject *)_PyLong_Copy(v);
2704 if (z != NULL)
2705 z->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002706 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002707}
2708
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002709static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002710long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002711{
2712 if (v->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002713 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00002714 else
2715 return long_pos(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002716}
2717
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002718static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002719long_nonzero(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002720{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002721 return ABS(v->ob_size) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002722}
2723
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002724static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002725long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002726{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002727 PyLongObject *a, *b;
2728 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002729 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002730 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002731 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002732
Neil Schemenauerba872e22001-01-04 01:46:03 +00002733 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2734
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002735 if (a->ob_size < 0) {
2736 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002737 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002738 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002739 if (a1 == NULL)
2740 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002741 a2 = (PyLongObject *) long_rshift(a1, b);
2742 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002743 if (a2 == NULL)
2744 goto rshift_error;
2745 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002746 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002747 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002748 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002749
Neil Schemenauerba872e22001-01-04 01:46:03 +00002750 shiftby = PyLong_AsLong((PyObject *)b);
2751 if (shiftby == -1L && PyErr_Occurred())
2752 goto rshift_error;
2753 if (shiftby < 0) {
2754 PyErr_SetString(PyExc_ValueError,
2755 "negative shift count");
2756 goto rshift_error;
2757 }
2758 wordshift = shiftby / SHIFT;
2759 newsize = ABS(a->ob_size) - wordshift;
2760 if (newsize <= 0) {
2761 z = _PyLong_New(0);
2762 Py_DECREF(a);
2763 Py_DECREF(b);
2764 return (PyObject *)z;
2765 }
2766 loshift = shiftby % SHIFT;
2767 hishift = SHIFT - loshift;
2768 lomask = ((digit)1 << hishift) - 1;
2769 himask = MASK ^ lomask;
2770 z = _PyLong_New(newsize);
2771 if (z == NULL)
2772 goto rshift_error;
2773 if (a->ob_size < 0)
2774 z->ob_size = -(z->ob_size);
2775 for (i = 0, j = wordshift; i < newsize; i++, j++) {
2776 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
2777 if (i+1 < newsize)
2778 z->ob_digit[i] |=
2779 (a->ob_digit[j+1] << hishift) & himask;
2780 }
2781 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002782 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002783rshift_error:
2784 Py_DECREF(a);
2785 Py_DECREF(b);
2786 return (PyObject *) z;
2787
Guido van Rossumc6913e71991-11-19 20:26:46 +00002788}
2789
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002790static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002791long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002792{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002793 /* This version due to Tim Peters */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002794 PyLongObject *a, *b;
2795 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002796 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002797 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002798 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002799
Neil Schemenauerba872e22001-01-04 01:46:03 +00002800 CONVERT_BINOP(v, w, &a, &b);
2801
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002802 shiftby = PyLong_AsLong((PyObject *)b);
2803 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00002804 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002805 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002806 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00002807 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002808 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002809 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002810 PyErr_SetString(PyExc_ValueError,
2811 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00002812 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002813 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002814 /* wordshift, remshift = divmod(shiftby, SHIFT) */
2815 wordshift = (int)shiftby / SHIFT;
2816 remshift = (int)shiftby - wordshift * SHIFT;
2817
2818 oldsize = ABS(a->ob_size);
2819 newsize = oldsize + wordshift;
2820 if (remshift)
2821 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002822 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002823 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002824 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002825 if (a->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002826 z->ob_size = -(z->ob_size);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002827 for (i = 0; i < wordshift; i++)
2828 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002829 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002830 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00002831 accum |= (twodigits)a->ob_digit[j] << remshift;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002832 z->ob_digit[i] = (digit)(accum & MASK);
2833 accum >>= SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002834 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002835 if (remshift)
2836 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002837 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002838 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002839 z = long_normalize(z);
2840lshift_error:
2841 Py_DECREF(a);
2842 Py_DECREF(b);
2843 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002844}
2845
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002846
2847/* Bitwise and/xor/or operations */
2848
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002849static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002850long_bitwise(PyLongObject *a,
2851 int op, /* '&', '|', '^' */
2852 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002853{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002854 digit maska, maskb; /* 0 or MASK */
2855 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002856 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002857 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002858 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00002859 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002860 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002861
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002862 if (a->ob_size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002863 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00002864 if (a == NULL)
2865 return NULL;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002866 maska = MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002867 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002868 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002869 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002870 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00002871 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002872 if (b->ob_size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002873 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00002874 if (b == NULL) {
2875 Py_DECREF(a);
2876 return NULL;
2877 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002878 maskb = MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002879 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002880 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002881 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002882 maskb = 0;
2883 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002884
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002885 negz = 0;
2886 switch (op) {
2887 case '^':
2888 if (maska != maskb) {
2889 maska ^= MASK;
2890 negz = -1;
2891 }
2892 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002893 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002894 if (maska && maskb) {
2895 op = '|';
2896 maska ^= MASK;
2897 maskb ^= MASK;
2898 negz = -1;
2899 }
2900 break;
2901 case '|':
2902 if (maska || maskb) {
2903 op = '&';
2904 maska ^= MASK;
2905 maskb ^= MASK;
2906 negz = -1;
2907 }
2908 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002909 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002910
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002911 /* JRH: The original logic here was to allocate the result value (z)
2912 as the longer of the two operands. However, there are some cases
2913 where the result is guaranteed to be shorter than that: AND of two
2914 positives, OR of two negatives: use the shorter number. AND with
2915 mixed signs: use the positive number. OR with mixed signs: use the
2916 negative number. After the transformations above, op will be '&'
2917 iff one of these cases applies, and mask will be non-0 for operands
2918 whose length should be ignored.
2919 */
2920
2921 size_a = a->ob_size;
2922 size_b = b->ob_size;
2923 size_z = op == '&'
2924 ? (maska
2925 ? size_b
2926 : (maskb ? size_a : MIN(size_a, size_b)))
2927 : MAX(size_a, size_b);
2928 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00002929 if (z == NULL) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002930 Py_XDECREF(a);
2931 Py_XDECREF(b);
2932 Py_XDECREF(z);
2933 return NULL;
2934 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002935
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002936 for (i = 0; i < size_z; ++i) {
2937 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
2938 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
2939 switch (op) {
2940 case '&': z->ob_digit[i] = diga & digb; break;
2941 case '|': z->ob_digit[i] = diga | digb; break;
2942 case '^': z->ob_digit[i] = diga ^ digb; break;
2943 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00002944 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002945
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002946 Py_DECREF(a);
2947 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002948 z = long_normalize(z);
2949 if (negz == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002950 return (PyObject *) z;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002951 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002952 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002953 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002954}
2955
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002956static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002957long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002958{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002959 PyLongObject *a, *b;
2960 PyObject *c;
2961 CONVERT_BINOP(v, w, &a, &b);
2962 c = long_bitwise(a, '&', b);
2963 Py_DECREF(a);
2964 Py_DECREF(b);
2965 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002966}
2967
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002968static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002969long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002970{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002971 PyLongObject *a, *b;
2972 PyObject *c;
2973 CONVERT_BINOP(v, w, &a, &b);
2974 c = long_bitwise(a, '^', b);
2975 Py_DECREF(a);
2976 Py_DECREF(b);
2977 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002978}
2979
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002980static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002981long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002982{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002983 PyLongObject *a, *b;
2984 PyObject *c;
2985 CONVERT_BINOP(v, w, &a, &b);
2986 c = long_bitwise(a, '|', b);
2987 Py_DECREF(a);
2988 Py_DECREF(b);
2989 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002990}
2991
Guido van Rossum234f9421993-06-17 12:35:49 +00002992static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002993long_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00002994{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002995 if (PyInt_Check(*pw)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00002996 *pw = PyLong_FromLong(PyInt_AS_LONG(*pw));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002997 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00002998 return 0;
2999 }
Guido van Rossum1952e382001-09-19 01:25:16 +00003000 else if (PyLong_Check(*pw)) {
3001 Py_INCREF(*pv);
3002 Py_INCREF(*pw);
3003 return 0;
3004 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00003005 return 1; /* Can't do it */
3006}
3007
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003008static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003009long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003010{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003011 if (PyLong_CheckExact(v))
3012 Py_INCREF(v);
3013 else
3014 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003015 return v;
3016}
3017
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003018static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00003019long_int(PyObject *v)
3020{
3021 long x;
3022 x = PyLong_AsLong(v);
3023 if (PyErr_Occurred()) {
3024 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
3025 PyErr_Clear();
3026 if (PyLong_CheckExact(v)) {
3027 Py_INCREF(v);
3028 return v;
3029 }
3030 else
3031 return _PyLong_Copy((PyLongObject *)v);
3032 }
3033 else
3034 return NULL;
3035 }
3036 return PyInt_FromLong(x);
3037}
3038
3039static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003040long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003041{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003042 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003043 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003044 if (result == -1.0 && PyErr_Occurred())
3045 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003046 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003047}
3048
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003049static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003050long_oct(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003051{
Fred Drake121ee271999-12-23 15:41:28 +00003052 return long_format(v, 8, 1);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003053}
3054
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003055static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003056long_hex(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003057{
Fred Drake121ee271999-12-23 15:41:28 +00003058 return long_format(v, 16, 1);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003059}
Jeremy Hylton938ace62002-07-17 16:30:39 +00003060
3061static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003062long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003063
Tim Peters6d6c1a32001-08-02 04:15:00 +00003064static PyObject *
3065long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3066{
3067 PyObject *x = NULL;
3068 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003069 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003070
Guido van Rossumbef14172001-08-29 15:47:46 +00003071 if (type != &PyLong_Type)
3072 return long_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003073 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist,
3074 &x, &base))
3075 return NULL;
3076 if (x == NULL)
3077 return PyLong_FromLong(0L);
3078 if (base == -909)
3079 return PyNumber_Long(x);
3080 else if (PyString_Check(x))
3081 return PyLong_FromString(PyString_AS_STRING(x), NULL, base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003082#ifdef Py_USING_UNICODE
Tim Peters6d6c1a32001-08-02 04:15:00 +00003083 else if (PyUnicode_Check(x))
3084 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3085 PyUnicode_GET_SIZE(x),
3086 base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003087#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +00003088 else {
3089 PyErr_SetString(PyExc_TypeError,
3090 "long() can't convert non-string with explicit base");
3091 return NULL;
3092 }
3093}
3094
Guido van Rossumbef14172001-08-29 15:47:46 +00003095/* Wimpy, slow approach to tp_new calls for subtypes of long:
3096 first create a regular long from whatever arguments we got,
3097 then allocate a subtype instance and initialize it from
3098 the regular long. The regular long is then thrown away.
3099*/
3100static PyObject *
3101long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3102{
Anthony Baxter377be112006-04-11 06:54:30 +00003103 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003104 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003105
3106 assert(PyType_IsSubtype(type, &PyLong_Type));
3107 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3108 if (tmp == NULL)
3109 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003110 assert(PyLong_CheckExact(tmp));
Guido van Rossumbef14172001-08-29 15:47:46 +00003111 n = tmp->ob_size;
3112 if (n < 0)
3113 n = -n;
Anthony Baxter377be112006-04-11 06:54:30 +00003114 newobj = (PyLongObject *)type->tp_alloc(type, n);
3115 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003116 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003117 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003118 }
Anthony Baxter377be112006-04-11 06:54:30 +00003119 assert(PyLong_Check(newobj));
3120 newobj->ob_size = tmp->ob_size;
Guido van Rossumbef14172001-08-29 15:47:46 +00003121 for (i = 0; i < n; i++)
Anthony Baxter377be112006-04-11 06:54:30 +00003122 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003123 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00003124 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003125}
3126
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003127static PyObject *
3128long_getnewargs(PyLongObject *v)
3129{
3130 return Py_BuildValue("(N)", _PyLong_Copy(v));
3131}
3132
3133static PyMethodDef long_methods[] = {
3134 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
3135 {NULL, NULL} /* sentinel */
3136};
3137
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003138PyDoc_STRVAR(long_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003139"long(x[, base]) -> integer\n\
3140\n\
3141Convert a string or number to a long integer, if possible. A floating\n\
3142point argument will be truncated towards zero (this does not include a\n\
3143string representation of a floating point number!) When converting a\n\
3144string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003145converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003146
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003147static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003148 (binaryfunc) long_add, /*nb_add*/
3149 (binaryfunc) long_sub, /*nb_subtract*/
3150 (binaryfunc) long_mul, /*nb_multiply*/
Georg Brandl347b3002006-03-30 11:57:00 +00003151 long_classic_div, /*nb_divide*/
3152 long_mod, /*nb_remainder*/
3153 long_divmod, /*nb_divmod*/
3154 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003155 (unaryfunc) long_neg, /*nb_negative*/
3156 (unaryfunc) long_pos, /*tp_positive*/
3157 (unaryfunc) long_abs, /*tp_absolute*/
3158 (inquiry) long_nonzero, /*tp_nonzero*/
3159 (unaryfunc) long_invert, /*nb_invert*/
Georg Brandl347b3002006-03-30 11:57:00 +00003160 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003161 (binaryfunc) long_rshift, /*nb_rshift*/
Georg Brandl347b3002006-03-30 11:57:00 +00003162 long_and, /*nb_and*/
3163 long_xor, /*nb_xor*/
3164 long_or, /*nb_or*/
3165 long_coerce, /*nb_coerce*/
3166 long_int, /*nb_int*/
3167 long_long, /*nb_long*/
3168 long_float, /*nb_float*/
3169 long_oct, /*nb_oct*/
3170 long_hex, /*nb_hex*/
Guido van Rossum4668b002001-08-08 05:00:18 +00003171 0, /* nb_inplace_add */
3172 0, /* nb_inplace_subtract */
3173 0, /* nb_inplace_multiply */
3174 0, /* nb_inplace_divide */
3175 0, /* nb_inplace_remainder */
3176 0, /* nb_inplace_power */
3177 0, /* nb_inplace_lshift */
3178 0, /* nb_inplace_rshift */
3179 0, /* nb_inplace_and */
3180 0, /* nb_inplace_xor */
3181 0, /* nb_inplace_or */
Georg Brandl347b3002006-03-30 11:57:00 +00003182 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003183 long_true_divide, /* nb_true_divide */
3184 0, /* nb_inplace_floor_divide */
3185 0, /* nb_inplace_true_divide */
Georg Brandl347b3002006-03-30 11:57:00 +00003186 long_index, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003187};
3188
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003189PyTypeObject PyLong_Type = {
3190 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003191 0, /* ob_size */
3192 "long", /* tp_name */
3193 sizeof(PyLongObject) - sizeof(digit), /* tp_basicsize */
3194 sizeof(digit), /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00003195 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003196 0, /* tp_print */
3197 0, /* tp_getattr */
3198 0, /* tp_setattr */
3199 (cmpfunc)long_compare, /* tp_compare */
Georg Brandl347b3002006-03-30 11:57:00 +00003200 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003201 &long_as_number, /* tp_as_number */
3202 0, /* tp_as_sequence */
3203 0, /* tp_as_mapping */
3204 (hashfunc)long_hash, /* tp_hash */
3205 0, /* tp_call */
Georg Brandl347b3002006-03-30 11:57:00 +00003206 long_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003207 PyObject_GenericGetAttr, /* tp_getattro */
3208 0, /* tp_setattro */
3209 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00003210 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3211 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003212 long_doc, /* tp_doc */
3213 0, /* tp_traverse */
3214 0, /* tp_clear */
3215 0, /* tp_richcompare */
3216 0, /* tp_weaklistoffset */
3217 0, /* tp_iter */
3218 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003219 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003220 0, /* tp_members */
3221 0, /* tp_getset */
3222 0, /* tp_base */
3223 0, /* tp_dict */
3224 0, /* tp_descr_get */
3225 0, /* tp_descr_set */
3226 0, /* tp_dictoffset */
3227 0, /* tp_init */
3228 0, /* tp_alloc */
3229 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003230 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003231};