blob: dc2311a435b700fe97b30a84760f9f29c92352a9 [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");
Tim Peters696cf432006-05-24 21:10:40 +0000280 if (sign > 0)
Guido van Rossum38fff8c2006-03-07 18:50:55 +0000281 return PY_SSIZE_T_MAX;
Tim Peters696cf432006-05-24 21:10:40 +0000282 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 Peters696cf432006-05-24 21:10:40 +00001307static int digval[] = {
1308 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1309 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1310 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1311 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1312 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1313 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1314 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1315 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1316 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1317 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1318 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1319 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1320 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1321 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1322 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1323 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1324 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1325 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1326 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1327 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1328 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1329 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1330 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1331 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37
1332};
1333
1334/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001335 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1336 * non-digit (which may be *str!). A normalized long is returned.
1337 * The point to this routine is that it takes time linear in the number of
1338 * string characters.
1339 */
1340static PyLongObject *
1341long_from_binary_base(char **str, int base)
1342{
1343 char *p = *str;
1344 char *start = p;
1345 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001346 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001347 PyLongObject *z;
1348 twodigits accum;
1349 int bits_in_accum;
1350 digit *pdigit;
1351
1352 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1353 n = base;
1354 for (bits_per_char = -1; n; ++bits_per_char)
1355 n >>= 1;
1356 /* n <- total # of bits needed, while setting p to end-of-string */
1357 n = 0;
Tim Peters696cf432006-05-24 21:10:40 +00001358 while (digval[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001359 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001360 *str = p;
Tim Peters1a3b19a2003-02-02 17:33:53 +00001361 n = (p - start) * bits_per_char;
1362 if (n / bits_per_char != p - start) {
1363 PyErr_SetString(PyExc_ValueError,
1364 "long string too large to convert");
1365 return NULL;
1366 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001367 /* n <- # of Python digits needed, = ceiling(n/SHIFT). */
1368 n = (n + SHIFT - 1) / SHIFT;
1369 z = _PyLong_New(n);
1370 if (z == NULL)
1371 return NULL;
1372 /* Read string from right, and fill in long from left; i.e.,
1373 * from least to most significant in both.
1374 */
1375 accum = 0;
1376 bits_in_accum = 0;
1377 pdigit = z->ob_digit;
1378 while (--p >= start) {
Tim Peters696cf432006-05-24 21:10:40 +00001379 int k = digval[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001380 assert(k >= 0 && k < base);
1381 accum |= (twodigits)(k << bits_in_accum);
Tim Petersbf2674b2003-02-02 07:51:32 +00001382 bits_in_accum += bits_per_char;
1383 if (bits_in_accum >= SHIFT) {
1384 *pdigit++ = (digit)(accum & MASK);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001385 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001386 accum >>= SHIFT;
1387 bits_in_accum -= SHIFT;
1388 assert(bits_in_accum < SHIFT);
1389 }
1390 }
1391 if (bits_in_accum) {
1392 assert(bits_in_accum <= SHIFT);
1393 *pdigit++ = (digit)accum;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001394 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001395 }
1396 while (pdigit - z->ob_digit < n)
1397 *pdigit++ = 0;
1398 return long_normalize(z);
1399}
1400
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001401PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001402PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001403{
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001404 int sign = 1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001405 char *start, *orig_str = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001406 PyLongObject *z;
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001407 PyObject *strobj, *strrepr;
1408 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001409
Guido van Rossum472c04f1996-12-05 21:57:21 +00001410 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001411 PyErr_SetString(PyExc_ValueError,
Fred Drake661ea262000-10-24 19:57:45 +00001412 "long() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001413 return NULL;
1414 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001415 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001416 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001417 if (*str == '+')
1418 ++str;
1419 else if (*str == '-') {
1420 ++str;
1421 sign = -1;
1422 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001423 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001424 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001425 if (base == 0) {
1426 if (str[0] != '0')
1427 base = 10;
1428 else if (str[1] == 'x' || str[1] == 'X')
1429 base = 16;
1430 else
1431 base = 8;
1432 }
1433 if (base == 16 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
1434 str += 2;
Tim Peters696cf432006-05-24 21:10:40 +00001435
Guido van Rossume6762971998-06-22 03:54:46 +00001436 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001437 if ((base & (base - 1)) == 0)
1438 z = long_from_binary_base(&str, base);
1439 else {
Tim Peters696cf432006-05-24 21:10:40 +00001440/***
1441Binary bases can be converted in time linear in the number of digits, because
1442Python's representation base is binary. Other bases (including decimal!) use
1443the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001444
Tim Peters696cf432006-05-24 21:10:40 +00001445First some math: the largest integer that can be expressed in N base-B digits
1446is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1447case number of Python digits needed to hold it is the smallest integer n s.t.
1448
1449 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1450 BASE**n >= B**N [taking logs to base BASE]
1451 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1452
1453The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1454this quickly. A Python long with that much space is reserved near the start,
1455and the result is computed into it.
1456
1457The input string is actually treated as being in base base**i (i.e., i digits
1458are processed at a time), where two more static arrays hold:
1459
1460 convwidth_base[base] = the largest integer i such that base**i <= BASE
1461 convmultmax_base[base] = base ** convwidth_base[base]
1462
1463The first of these is the largest i such that i consecutive input digits
1464must fit in a single Python digit. The second is effectively the input
1465base we're really using.
1466
1467Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1468convmultmax_base[base], the result is "simply"
1469
1470 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1471
1472where B = convmultmax_base[base].
1473***/
1474 register twodigits c; /* current input character */
1475 Py_ssize_t size_z;
1476 int i;
1477 int convwidth;
1478 twodigits convmultmax, convmult;
1479 digit *pz, *pzstop;
1480 char* scan;
1481
1482 static double log_base_BASE[37] = {0.0e0,};
1483 static int convwidth_base[37] = {0,};
1484 static twodigits convmultmax_base[37] = {0,};
1485
1486 if (log_base_BASE[base] == 0.0) {
1487 twodigits convmax = base;
1488 int i = 1;
1489
1490 log_base_BASE[base] = log((double)base) /
1491 log((double)BASE);
1492 for (;;) {
1493 twodigits next = convmax * base;
1494 if (next > BASE)
1495 break;
1496 convmax = next;
1497 ++i;
1498 }
1499 convmultmax_base[base] = convmax;
1500 assert(i > 0);
1501 convwidth_base[base] = i;
1502 }
1503
1504 /* Find length of the string of numeric characters. */
1505 scan = str;
1506 while (digval[Py_CHARMASK(*scan)] < base)
1507 ++scan;
1508
1509 /* Create a long object that can contain the largest possible
1510 * integer with this base and length. Note that there's no
1511 * need to initialize z->ob_digit -- no slot is read up before
1512 * being stored into.
1513 */
1514 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1515 assert(size_z > 0);
1516 z = _PyLong_New(size_z);
1517 if (z == NULL)
1518 return NULL;
1519 z->ob_size = 0;
1520
1521 /* `convwidth` consecutive input digits are treated as a single
1522 * digit in base `convmultmax`.
1523 */
1524 convwidth = convwidth_base[base];
1525 convmultmax = convmultmax_base[base];
1526
1527 /* Work ;-) */
1528 while (str < scan) {
1529 /* grab up to convwidth digits from the input string */
1530 c = (digit)digval[Py_CHARMASK(*str++)];
1531 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1532 c = (twodigits)(c * base +
1533 digval[Py_CHARMASK(*str)]);
1534 assert(c < BASE);
1535 }
1536
1537 convmult = convmultmax;
1538 /* Calculate the shift only if we couldn't get
1539 * convwidth digits.
1540 */
1541 if (i != convwidth) {
1542 convmult = base;
1543 for ( ; i > 1; --i)
1544 convmult *= base;
1545 }
1546
1547 /* Multiply z by convmult, and add c. */
1548 pz = z->ob_digit;
1549 pzstop = pz + z->ob_size;
1550 for (; pz < pzstop; ++pz) {
1551 c += (twodigits)*pz * convmult;
1552 *pz = (digit)(c & MASK);
1553 c >>= SHIFT;
1554 }
1555 /* carry off the current end? */
1556 if (c) {
1557 assert(c < BASE);
1558 assert(z->ob_size < size_z);
1559 *pz = (digit)c;
1560 ++z->ob_size;
1561 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001562 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001563 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001564 if (z == NULL)
1565 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001566 if (str == start)
1567 goto onError;
Tim Peters696cf432006-05-24 21:10:40 +00001568 if (sign < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001569 z->ob_size = -(z->ob_size);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001570 if (*str == 'L' || *str == 'l')
1571 str++;
1572 while (*str && isspace(Py_CHARMASK(*str)))
1573 str++;
1574 if (*str != '\0')
1575 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001576 if (pend)
1577 *pend = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001578 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001579
1580 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00001581 Py_XDECREF(z);
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001582 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
1583 strobj = PyString_FromStringAndSize(orig_str, slen);
1584 if (strobj == NULL)
1585 return NULL;
1586 strrepr = PyObject_Repr(strobj);
1587 Py_DECREF(strobj);
1588 if (strrepr == NULL)
1589 return NULL;
1590 PyErr_Format(PyExc_ValueError,
1591 "invalid literal for long() with base %d: %s",
1592 base, PyString_AS_STRING(strrepr));
1593 Py_DECREF(strrepr);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001594 return NULL;
1595}
1596
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001597#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +00001598PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001599PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001600{
Walter Dörwald07e14762002-11-06 16:15:14 +00001601 PyObject *result;
Anthony Baxter377be112006-04-11 06:54:30 +00001602 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001603
Walter Dörwald07e14762002-11-06 16:15:14 +00001604 if (buffer == NULL)
1605 return NULL;
1606
1607 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1608 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001609 return NULL;
1610 }
Walter Dörwald07e14762002-11-06 16:15:14 +00001611 result = PyLong_FromString(buffer, NULL, base);
1612 PyMem_FREE(buffer);
1613 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001614}
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001615#endif
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001616
Tim Peters9f688bf2000-07-07 15:53:28 +00001617/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001618static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00001619 (PyLongObject *, PyLongObject *, PyLongObject **);
1620static PyObject *long_pos(PyLongObject *);
1621static int long_divrem(PyLongObject *, PyLongObject *,
1622 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001623
1624/* Long division with remainder, top-level routine */
1625
Guido van Rossume32e0141992-01-19 16:31:05 +00001626static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001627long_divrem(PyLongObject *a, PyLongObject *b,
1628 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001629{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001630 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001631 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001632
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001633 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001634 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +00001635 "long division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00001636 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001637 }
1638 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00001639 (size_a == size_b &&
1640 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001641 /* |a| < |b|. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001642 *pdiv = _PyLong_New(0);
1643 Py_INCREF(a);
1644 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00001645 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001646 }
1647 if (size_b == 1) {
1648 digit rem = 0;
1649 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001650 if (z == NULL)
1651 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001652 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001653 }
Guido van Rossume32e0141992-01-19 16:31:05 +00001654 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001655 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001656 if (z == NULL)
1657 return -1;
1658 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001659 /* Set the signs.
1660 The quotient z has the sign of a*b;
1661 the remainder r has the sign of a,
1662 so a = b*z + r. */
Guido van Rossume32e0141992-01-19 16:31:05 +00001663 if ((a->ob_size < 0) != (b->ob_size < 0))
1664 z->ob_size = -(z->ob_size);
1665 if (a->ob_size < 0 && (*prem)->ob_size != 0)
1666 (*prem)->ob_size = -((*prem)->ob_size);
1667 *pdiv = z;
1668 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001669}
1670
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001671/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001672
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001673static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001674x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001675{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001676 Py_ssize_t size_v = ABS(v1->ob_size), size_w = ABS(w1->ob_size);
Guido van Rossum2095d241997-04-09 19:41:24 +00001677 digit d = (digit) ((twodigits)BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001678 PyLongObject *v = mul1(v1, d);
1679 PyLongObject *w = mul1(w1, d);
1680 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001681 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001682
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001683 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001684 Py_XDECREF(v);
1685 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001686 return NULL;
1687 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001688
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001689 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001690 assert(v->ob_refcnt == 1); /* Since v will be used as accumulator! */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001691 assert(size_w == ABS(w->ob_size)); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00001692
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001693 size_v = ABS(v->ob_size);
Neal Norwitzc6a989a2006-05-10 06:57:58 +00001694 k = size_v - size_w;
1695 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001696
Neal Norwitzc6a989a2006-05-10 06:57:58 +00001697 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001698 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
1699 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001700 stwodigits carry = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001701 int i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001702
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001703 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001704 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001705 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001706 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001707 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001708 if (vj == w->ob_digit[size_w-1])
1709 q = MASK;
1710 else
1711 q = (((twodigits)vj << SHIFT) + v->ob_digit[j-1]) /
1712 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00001713
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001714 while (w->ob_digit[size_w-2]*q >
1715 ((
1716 ((twodigits)vj << SHIFT)
1717 + v->ob_digit[j-1]
1718 - q*w->ob_digit[size_w-1]
1719 ) << SHIFT)
1720 + v->ob_digit[j-2])
1721 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001722
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001723 for (i = 0; i < size_w && i+k < size_v; ++i) {
1724 twodigits z = w->ob_digit[i] * q;
Guido van Rossum2095d241997-04-09 19:41:24 +00001725 digit zz = (digit) (z >> SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001726 carry += v->ob_digit[i+k] - z
1727 + ((twodigits)zz << SHIFT);
Jeremy Hyltonfc61f9a2003-05-01 21:31:53 +00001728 v->ob_digit[i+k] = (digit)(carry & MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00001729 carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
1730 carry, SHIFT);
1731 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001732 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001733
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001734 if (i+k < size_v) {
1735 carry += v->ob_digit[i+k];
1736 v->ob_digit[i+k] = 0;
1737 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001738
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001739 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00001740 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001741 else {
1742 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00001743 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001744 carry = 0;
1745 for (i = 0; i < size_w && i+k < size_v; ++i) {
1746 carry += v->ob_digit[i+k] + w->ob_digit[i];
Jeremy Hyltonfc61f9a2003-05-01 21:31:53 +00001747 v->ob_digit[i+k] = (digit)(carry & MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00001748 carry = Py_ARITHMETIC_RIGHT_SHIFT(
1749 BASE_TWODIGITS_TYPE,
1750 carry, SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001751 }
1752 }
1753 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00001754
Guido van Rossumc206c761995-01-10 15:23:19 +00001755 if (a == NULL)
1756 *prem = NULL;
1757 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00001758 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00001759 *prem = divrem1(v, d, &d);
1760 /* d receives the (unused) remainder */
1761 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001762 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00001763 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00001764 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001765 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001766 Py_DECREF(v);
1767 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001768 return a;
1769}
1770
1771/* Methods */
1772
1773static void
Tim Peters9f688bf2000-07-07 15:53:28 +00001774long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001775{
Guido van Rossum9475a232001-10-05 20:51:39 +00001776 v->ob_type->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001777}
1778
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001779static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001780long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001781{
Fred Drake121ee271999-12-23 15:41:28 +00001782 return long_format(v, 10, 1);
1783}
1784
1785static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001786long_str(PyObject *v)
Fred Drake121ee271999-12-23 15:41:28 +00001787{
1788 return long_format(v, 10, 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001789}
1790
1791static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001792long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001793{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001794 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001795
Guido van Rossumc6913e71991-11-19 20:26:46 +00001796 if (a->ob_size != b->ob_size) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001797 if (ABS(a->ob_size) == 0 && ABS(b->ob_size) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00001798 sign = 0;
1799 else
1800 sign = a->ob_size - b->ob_size;
1801 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001802 else {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001803 Py_ssize_t i = ABS(a->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001804 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
1805 ;
1806 if (i < 0)
1807 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00001808 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001809 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00001810 if (a->ob_size < 0)
1811 sign = -sign;
1812 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001813 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001814 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001815}
1816
Guido van Rossum9bfef441993-03-29 10:43:31 +00001817static long
Tim Peters9f688bf2000-07-07 15:53:28 +00001818long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001819{
1820 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001821 Py_ssize_t i;
1822 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001823
1824 /* This is designed so that Python ints and longs with the
1825 same value hash to the same value, otherwise comparisons
1826 of mapping keys will turn out weird */
1827 i = v->ob_size;
1828 sign = 1;
1829 x = 0;
1830 if (i < 0) {
1831 sign = -1;
1832 i = -(i);
1833 }
Neal Norwitzd5a65a72003-02-23 23:11:41 +00001834#define LONG_BIT_SHIFT (8*sizeof(long) - SHIFT)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001835 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00001836 /* Force a native long #-bits (32 or 64) circular shift */
1837 x = ((x << SHIFT) & ~MASK) | ((x >> LONG_BIT_SHIFT) & MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001838 x += v->ob_digit[i];
1839 }
Neal Norwitzd5a65a72003-02-23 23:11:41 +00001840#undef LONG_BIT_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00001841 x = x * sign;
1842 if (x == -1)
1843 x = -2;
1844 return x;
1845}
1846
1847
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001848/* Add the absolute values of two long integers. */
1849
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001850static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001851x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001852{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001853 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001854 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001855 int i;
1856 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00001857
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001858 /* Ensure a is the larger of the two: */
1859 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001860 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00001861 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001862 size_a = size_b;
1863 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001864 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001865 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001866 if (z == NULL)
1867 return NULL;
1868 for (i = 0; i < size_b; ++i) {
1869 carry += a->ob_digit[i] + b->ob_digit[i];
1870 z->ob_digit[i] = carry & MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001871 carry >>= SHIFT;
1872 }
1873 for (; i < size_a; ++i) {
1874 carry += a->ob_digit[i];
1875 z->ob_digit[i] = carry & MASK;
1876 carry >>= SHIFT;
1877 }
1878 z->ob_digit[i] = carry;
1879 return long_normalize(z);
1880}
1881
1882/* Subtract the absolute values of two integers. */
1883
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001884static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001885x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001886{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001887 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001888 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001889 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001890 int sign = 1;
1891 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00001892
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001893 /* Ensure a is the larger of the two: */
1894 if (size_a < size_b) {
1895 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001896 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00001897 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001898 size_a = size_b;
1899 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001900 }
1901 else if (size_a == size_b) {
1902 /* Find highest digit where a and b differ: */
1903 i = size_a;
1904 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
1905 ;
1906 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001907 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001908 if (a->ob_digit[i] < b->ob_digit[i]) {
1909 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001910 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001911 }
1912 size_a = size_b = i+1;
1913 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001914 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001915 if (z == NULL)
1916 return NULL;
1917 for (i = 0; i < size_b; ++i) {
1918 /* The following assumes unsigned arithmetic
1919 works module 2**N for some N>SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001920 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001921 z->ob_digit[i] = borrow & MASK;
1922 borrow >>= SHIFT;
1923 borrow &= 1; /* Keep only one sign bit */
1924 }
1925 for (; i < size_a; ++i) {
1926 borrow = a->ob_digit[i] - borrow;
1927 z->ob_digit[i] = borrow & MASK;
1928 borrow >>= SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00001929 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001930 }
1931 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00001932 if (sign < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001933 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001934 return long_normalize(z);
1935}
1936
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001937static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00001938long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001939{
Neil Schemenauerba872e22001-01-04 01:46:03 +00001940 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00001941
Neil Schemenauerba872e22001-01-04 01:46:03 +00001942 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
1943
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001944 if (a->ob_size < 0) {
1945 if (b->ob_size < 0) {
1946 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00001947 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001948 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001949 }
1950 else
1951 z = x_sub(b, a);
1952 }
1953 else {
1954 if (b->ob_size < 0)
1955 z = x_sub(a, b);
1956 else
1957 z = x_add(a, b);
1958 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00001959 Py_DECREF(a);
1960 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001961 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001962}
1963
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001964static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00001965long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001966{
Neil Schemenauerba872e22001-01-04 01:46:03 +00001967 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001968
Neil Schemenauerba872e22001-01-04 01:46:03 +00001969 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
1970
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001971 if (a->ob_size < 0) {
1972 if (b->ob_size < 0)
1973 z = x_sub(a, b);
1974 else
1975 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00001976 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001977 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001978 }
1979 else {
1980 if (b->ob_size < 0)
1981 z = x_add(a, b);
1982 else
1983 z = x_sub(a, b);
1984 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00001985 Py_DECREF(a);
1986 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001987 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001988}
1989
Tim Peters5af4e6c2002-08-12 02:31:19 +00001990/* Grade school multiplication, ignoring the signs.
1991 * Returns the absolute value of the product, or NULL if error.
1992 */
1993static PyLongObject *
1994x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001995{
Tim Peters5af4e6c2002-08-12 02:31:19 +00001996 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001997 Py_ssize_t size_a = ABS(a->ob_size);
1998 Py_ssize_t size_b = ABS(b->ob_size);
1999 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002000
Tim Peters5af4e6c2002-08-12 02:31:19 +00002001 z = _PyLong_New(size_a + size_b);
2002 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002003 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002004
2005 memset(z->ob_digit, 0, z->ob_size * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002006 if (a == b) {
2007 /* Efficient squaring per HAC, Algorithm 14.16:
2008 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2009 * Gives slightly less than a 2x speedup when a == b,
2010 * via exploiting that each entry in the multiplication
2011 * pyramid appears twice (except for the size_a squares).
2012 */
2013 for (i = 0; i < size_a; ++i) {
2014 twodigits carry;
2015 twodigits f = a->ob_digit[i];
2016 digit *pz = z->ob_digit + (i << 1);
2017 digit *pa = a->ob_digit + i + 1;
2018 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002019
Tim Peters0973b992004-08-29 22:16:50 +00002020 SIGCHECK({
2021 Py_DECREF(z);
2022 return NULL;
2023 })
2024
2025 carry = *pz + f * f;
2026 *pz++ = (digit)(carry & MASK);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002027 carry >>= SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002028 assert(carry <= MASK);
2029
2030 /* Now f is added in twice in each column of the
2031 * pyramid it appears. Same as adding f<<1 once.
2032 */
2033 f <<= 1;
2034 while (pa < paend) {
2035 carry += *pz + *pa++ * f;
2036 *pz++ = (digit)(carry & MASK);
2037 carry >>= SHIFT;
2038 assert(carry <= (MASK << 1));
2039 }
2040 if (carry) {
2041 carry += *pz;
2042 *pz++ = (digit)(carry & MASK);
2043 carry >>= SHIFT;
2044 }
2045 if (carry)
2046 *pz += (digit)(carry & MASK);
2047 assert((carry >> SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002048 }
Tim Peters0973b992004-08-29 22:16:50 +00002049 }
2050 else { /* a is not the same as b -- gradeschool long mult */
2051 for (i = 0; i < size_a; ++i) {
2052 twodigits carry = 0;
2053 twodigits f = a->ob_digit[i];
2054 digit *pz = z->ob_digit + i;
2055 digit *pb = b->ob_digit;
2056 digit *pbend = b->ob_digit + size_b;
2057
2058 SIGCHECK({
2059 Py_DECREF(z);
2060 return NULL;
2061 })
2062
2063 while (pb < pbend) {
2064 carry += *pz + *pb++ * f;
2065 *pz++ = (digit)(carry & MASK);
2066 carry >>= SHIFT;
2067 assert(carry <= MASK);
2068 }
2069 if (carry)
2070 *pz += (digit)(carry & MASK);
2071 assert((carry >> SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002072 }
2073 }
Tim Peters44121a62002-08-12 06:17:58 +00002074 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002075}
2076
2077/* A helper for Karatsuba multiplication (k_mul).
2078 Takes a long "n" and an integer "size" representing the place to
2079 split, and sets low and high such that abs(n) == (high << size) + low,
2080 viewing the shift as being by digits. The sign bit is ignored, and
2081 the return values are >= 0.
2082 Returns 0 on success, -1 on failure.
2083*/
2084static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002085kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002086{
2087 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002088 Py_ssize_t size_lo, size_hi;
2089 const Py_ssize_t size_n = ABS(n->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002090
2091 size_lo = MIN(size_n, size);
2092 size_hi = size_n - size_lo;
2093
2094 if ((hi = _PyLong_New(size_hi)) == NULL)
2095 return -1;
2096 if ((lo = _PyLong_New(size_lo)) == NULL) {
2097 Py_DECREF(hi);
2098 return -1;
2099 }
2100
2101 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2102 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2103
2104 *high = long_normalize(hi);
2105 *low = long_normalize(lo);
2106 return 0;
2107}
2108
Tim Peters60004642002-08-12 22:01:34 +00002109static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2110
Tim Peters5af4e6c2002-08-12 02:31:19 +00002111/* Karatsuba multiplication. Ignores the input signs, and returns the
2112 * absolute value of the product (or NULL if error).
2113 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2114 */
2115static PyLongObject *
2116k_mul(PyLongObject *a, PyLongObject *b)
2117{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002118 Py_ssize_t asize = ABS(a->ob_size);
2119 Py_ssize_t bsize = ABS(b->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002120 PyLongObject *ah = NULL;
2121 PyLongObject *al = NULL;
2122 PyLongObject *bh = NULL;
2123 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002124 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002125 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002126 Py_ssize_t shift; /* the number of digits we split off */
2127 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002128
Tim Peters5af4e6c2002-08-12 02:31:19 +00002129 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2130 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2131 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002132 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002133 * By picking X to be a power of 2, "*X" is just shifting, and it's
2134 * been reduced to 3 multiplies on numbers half the size.
2135 */
2136
Tim Petersfc07e562002-08-12 02:54:10 +00002137 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002138 * is largest.
2139 */
Tim Peters738eda72002-08-12 15:08:20 +00002140 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002141 t1 = a;
2142 a = b;
2143 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002144
2145 i = asize;
2146 asize = bsize;
2147 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002148 }
2149
2150 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002151 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2152 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002153 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002154 return _PyLong_New(0);
2155 else
2156 return x_mul(a, b);
2157 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002158
Tim Peters60004642002-08-12 22:01:34 +00002159 /* If a is small compared to b, splitting on b gives a degenerate
2160 * case with ah==0, and Karatsuba may be (even much) less efficient
2161 * than "grade school" then. However, we can still win, by viewing
2162 * b as a string of "big digits", each of width a->ob_size. That
2163 * leads to a sequence of balanced calls to k_mul.
2164 */
2165 if (2 * asize <= bsize)
2166 return k_lopsided_mul(a, b);
2167
Tim Petersd6974a52002-08-13 20:37:51 +00002168 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002169 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002170 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Tim Petersd6974a52002-08-13 20:37:51 +00002171 assert(ah->ob_size > 0); /* the split isn't degenerate */
2172
Tim Peters0973b992004-08-29 22:16:50 +00002173 if (a == b) {
2174 bh = ah;
2175 bl = al;
2176 Py_INCREF(bh);
2177 Py_INCREF(bl);
2178 }
2179 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002180
Tim Petersd64c1de2002-08-12 17:36:03 +00002181 /* The plan:
2182 * 1. Allocate result space (asize + bsize digits: that's always
2183 * enough).
2184 * 2. Compute ah*bh, and copy into result at 2*shift.
2185 * 3. Compute al*bl, and copy into result at 0. Note that this
2186 * can't overlap with #2.
2187 * 4. Subtract al*bl from the result, starting at shift. This may
2188 * underflow (borrow out of the high digit), but we don't care:
2189 * we're effectively doing unsigned arithmetic mod
2190 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2191 * borrows and carries out of the high digit can be ignored.
2192 * 5. Subtract ah*bh from the result, starting at shift.
2193 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2194 * at shift.
2195 */
2196
2197 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002198 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002199 if (ret == NULL) goto fail;
2200#ifdef Py_DEBUG
2201 /* Fill with trash, to catch reference to uninitialized digits. */
2202 memset(ret->ob_digit, 0xDF, ret->ob_size * sizeof(digit));
2203#endif
Tim Peters44121a62002-08-12 06:17:58 +00002204
Tim Petersd64c1de2002-08-12 17:36:03 +00002205 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002206 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
2207 assert(t1->ob_size >= 0);
2208 assert(2*shift + t1->ob_size <= ret->ob_size);
2209 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
2210 t1->ob_size * sizeof(digit));
2211
2212 /* Zero-out the digits higher than the ah*bh copy. */
2213 i = ret->ob_size - 2*shift - t1->ob_size;
Tim Peters44121a62002-08-12 06:17:58 +00002214 if (i)
Tim Peters738eda72002-08-12 15:08:20 +00002215 memset(ret->ob_digit + 2*shift + t1->ob_size, 0,
Tim Peters44121a62002-08-12 06:17:58 +00002216 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002217
Tim Petersd64c1de2002-08-12 17:36:03 +00002218 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002219 if ((t2 = k_mul(al, bl)) == NULL) {
2220 Py_DECREF(t1);
2221 goto fail;
2222 }
2223 assert(t2->ob_size >= 0);
2224 assert(t2->ob_size <= 2*shift); /* no overlap with high digits */
2225 memcpy(ret->ob_digit, t2->ob_digit, t2->ob_size * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002226
2227 /* Zero out remaining digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002228 i = 2*shift - t2->ob_size; /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002229 if (i)
Tim Peters738eda72002-08-12 15:08:20 +00002230 memset(ret->ob_digit + t2->ob_size, 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002231
Tim Petersd64c1de2002-08-12 17:36:03 +00002232 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2233 * because it's fresher in cache.
2234 */
Tim Peters738eda72002-08-12 15:08:20 +00002235 i = ret->ob_size - shift; /* # digits after shift */
Tim Petersd64c1de2002-08-12 17:36:03 +00002236 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, t2->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002237 Py_DECREF(t2);
2238
Tim Petersd64c1de2002-08-12 17:36:03 +00002239 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, t1->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002240 Py_DECREF(t1);
2241
Tim Petersd64c1de2002-08-12 17:36:03 +00002242 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002243 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2244 Py_DECREF(ah);
2245 Py_DECREF(al);
2246 ah = al = NULL;
2247
Tim Peters0973b992004-08-29 22:16:50 +00002248 if (a == b) {
2249 t2 = t1;
2250 Py_INCREF(t2);
2251 }
2252 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002253 Py_DECREF(t1);
2254 goto fail;
2255 }
2256 Py_DECREF(bh);
2257 Py_DECREF(bl);
2258 bh = bl = NULL;
2259
Tim Peters738eda72002-08-12 15:08:20 +00002260 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002261 Py_DECREF(t1);
2262 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002263 if (t3 == NULL) goto fail;
Tim Peters547607c2002-08-12 19:43:49 +00002264 assert(t3->ob_size >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002265
Tim Petersd6974a52002-08-13 20:37:51 +00002266 /* Add t3. It's not obvious why we can't run out of room here.
2267 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002268 */
Tim Petersd64c1de2002-08-12 17:36:03 +00002269 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, t3->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002270 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002271
Tim Peters5af4e6c2002-08-12 02:31:19 +00002272 return long_normalize(ret);
2273
2274 fail:
2275 Py_XDECREF(ret);
2276 Py_XDECREF(ah);
2277 Py_XDECREF(al);
2278 Py_XDECREF(bh);
2279 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002280 return NULL;
2281}
2282
Tim Petersd6974a52002-08-13 20:37:51 +00002283/* (*) Why adding t3 can't "run out of room" above.
2284
Tim Petersab86c2b2002-08-15 20:06:00 +00002285Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2286to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002287
Tim Petersab86c2b2002-08-15 20:06:00 +000022881. For any integer i, i = c(i/2) + f(i/2). In particular,
2289 bsize = c(bsize/2) + f(bsize/2).
22902. shift = f(bsize/2)
22913. asize <= bsize
22924. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2293 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002294
Tim Petersab86c2b2002-08-15 20:06:00 +00002295We allocated asize + bsize result digits, and add t3 into them at an offset
2296of shift. This leaves asize+bsize-shift allocated digit positions for t3
2297to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2298asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002299
Tim Petersab86c2b2002-08-15 20:06:00 +00002300bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2301at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002302
Tim Petersab86c2b2002-08-15 20:06:00 +00002303If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2304digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2305most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002306
Tim Petersab86c2b2002-08-15 20:06:00 +00002307The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002308
Tim Petersab86c2b2002-08-15 20:06:00 +00002309 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002310
Tim Petersab86c2b2002-08-15 20:06:00 +00002311and we have asize + c(bsize/2) available digit positions. We need to show
2312this is always enough. An instance of c(bsize/2) cancels out in both, so
2313the question reduces to whether asize digits is enough to hold
2314(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2315then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2316asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
2317digit is enough to hold 2 bits. This is so since SHIFT=15 >= 2. If
2318asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002319c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2320is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2321bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002322
Tim Peters48d52c02002-08-14 17:07:32 +00002323Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2324clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2325ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002326*/
2327
Tim Peters60004642002-08-12 22:01:34 +00002328/* b has at least twice the digits of a, and a is big enough that Karatsuba
2329 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2330 * of slices, each with a->ob_size digits, and multiply the slices by a,
2331 * one at a time. This gives k_mul balanced inputs to work with, and is
2332 * also cache-friendly (we compute one double-width slice of the result
2333 * at a time, then move on, never bactracking except for the helpful
2334 * single-width slice overlap between successive partial sums).
2335 */
2336static PyLongObject *
2337k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2338{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002339 const Py_ssize_t asize = ABS(a->ob_size);
2340 Py_ssize_t bsize = ABS(b->ob_size);
2341 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002342 PyLongObject *ret;
2343 PyLongObject *bslice = NULL;
2344
2345 assert(asize > KARATSUBA_CUTOFF);
2346 assert(2 * asize <= bsize);
2347
2348 /* Allocate result space, and zero it out. */
2349 ret = _PyLong_New(asize + bsize);
2350 if (ret == NULL)
2351 return NULL;
2352 memset(ret->ob_digit, 0, ret->ob_size * sizeof(digit));
2353
2354 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002355 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002356 if (bslice == NULL)
2357 goto fail;
2358
2359 nbdone = 0;
2360 while (bsize > 0) {
2361 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002362 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002363
2364 /* Multiply the next slice of b by a. */
2365 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2366 nbtouse * sizeof(digit));
2367 bslice->ob_size = nbtouse;
2368 product = k_mul(a, bslice);
2369 if (product == NULL)
2370 goto fail;
2371
2372 /* Add into result. */
2373 (void)v_iadd(ret->ob_digit + nbdone, ret->ob_size - nbdone,
2374 product->ob_digit, product->ob_size);
2375 Py_DECREF(product);
2376
2377 bsize -= nbtouse;
2378 nbdone += nbtouse;
2379 }
2380
2381 Py_DECREF(bslice);
2382 return long_normalize(ret);
2383
2384 fail:
2385 Py_DECREF(ret);
2386 Py_XDECREF(bslice);
2387 return NULL;
2388}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002389
2390static PyObject *
2391long_mul(PyLongObject *v, PyLongObject *w)
2392{
2393 PyLongObject *a, *b, *z;
2394
2395 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002396 Py_INCREF(Py_NotImplemented);
2397 return Py_NotImplemented;
2398 }
2399
Tim Petersd64c1de2002-08-12 17:36:03 +00002400 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002401 /* Negate if exactly one of the inputs is negative. */
2402 if (((a->ob_size ^ b->ob_size) < 0) && z)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002403 z->ob_size = -(z->ob_size);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002404 Py_DECREF(a);
2405 Py_DECREF(b);
Tim Peters9973d742002-08-15 19:41:06 +00002406 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002407}
2408
Guido van Rossume32e0141992-01-19 16:31:05 +00002409/* The / and % operators are now defined in terms of divmod().
2410 The expression a mod b has the value a - b*floor(a/b).
2411 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002412 |a| by |b|, with the sign of a. This is also expressed
2413 as a - b*trunc(a/b), if trunc truncates towards zero.
2414 Some examples:
2415 a b a rem b a mod b
2416 13 10 3 3
2417 -13 10 -3 7
2418 13 -10 3 -7
2419 -13 -10 -3 -3
2420 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002421 have different signs. We then subtract one from the 'div'
2422 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002423
Tim Peters47e52ee2004-08-30 02:44:38 +00002424/* Compute
2425 * *pdiv, *pmod = divmod(v, w)
2426 * NULL can be passed for pdiv or pmod, in which case that part of
2427 * the result is simply thrown away. The caller owns a reference to
2428 * each of these it requests (does not pass NULL for).
2429 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002430static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002431l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002432 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002433{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002434 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002435
Guido van Rossume32e0141992-01-19 16:31:05 +00002436 if (long_divrem(v, w, &div, &mod) < 0)
2437 return -1;
Guido van Rossum472c04f1996-12-05 21:57:21 +00002438 if ((mod->ob_size < 0 && w->ob_size > 0) ||
2439 (mod->ob_size > 0 && w->ob_size < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002440 PyLongObject *temp;
2441 PyLongObject *one;
2442 temp = (PyLongObject *) long_add(mod, w);
2443 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002444 mod = temp;
2445 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002446 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002447 return -1;
2448 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002449 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002450 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002451 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2452 Py_DECREF(mod);
2453 Py_DECREF(div);
2454 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002455 return -1;
2456 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002457 Py_DECREF(one);
2458 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002459 div = temp;
2460 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002461 if (pdiv != NULL)
2462 *pdiv = div;
2463 else
2464 Py_DECREF(div);
2465
2466 if (pmod != NULL)
2467 *pmod = mod;
2468 else
2469 Py_DECREF(mod);
2470
Guido van Rossume32e0141992-01-19 16:31:05 +00002471 return 0;
2472}
2473
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002474static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002475long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002476{
Tim Peters47e52ee2004-08-30 02:44:38 +00002477 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002478
2479 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002480 if (l_divmod(a, b, &div, NULL) < 0)
2481 div = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002482 Py_DECREF(a);
2483 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002484 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002485}
2486
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002487static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +00002488long_classic_div(PyObject *v, PyObject *w)
2489{
Tim Peters47e52ee2004-08-30 02:44:38 +00002490 PyLongObject *a, *b, *div;
Guido van Rossum393661d2001-08-31 17:40:15 +00002491
2492 CONVERT_BINOP(v, w, &a, &b);
Guido van Rossum393661d2001-08-31 17:40:15 +00002493 if (Py_DivisionWarningFlag &&
2494 PyErr_Warn(PyExc_DeprecationWarning, "classic long division") < 0)
2495 div = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00002496 else if (l_divmod(a, b, &div, NULL) < 0)
Guido van Rossum393661d2001-08-31 17:40:15 +00002497 div = NULL;
Guido van Rossum393661d2001-08-31 17:40:15 +00002498 Py_DECREF(a);
2499 Py_DECREF(b);
2500 return (PyObject *)div;
2501}
2502
2503static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00002504long_true_divide(PyObject *v, PyObject *w)
2505{
Tim Peterse2a60002001-09-04 06:17:36 +00002506 PyLongObject *a, *b;
2507 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002508 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002509
2510 CONVERT_BINOP(v, w, &a, &b);
2511 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2512 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002513 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
2514 Py_DECREF(a);
2515 Py_DECREF(b);
2516 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002517 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002518 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2519 but should really be set correctly after sucessful calls to
2520 _PyLong_AsScaledDouble() */
2521 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002522
2523 if (bd == 0.0) {
2524 PyErr_SetString(PyExc_ZeroDivisionError,
2525 "long division or modulo by zero");
2526 return NULL;
2527 }
2528
2529 /* True value is very close to ad/bd * 2**(SHIFT*(aexp-bexp)) */
2530 ad /= bd; /* overflow/underflow impossible here */
2531 aexp -= bexp;
2532 if (aexp > INT_MAX / SHIFT)
2533 goto overflow;
Tim Peterse56ed9b2001-09-06 21:59:14 +00002534 else if (aexp < -(INT_MAX / SHIFT))
2535 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002536 errno = 0;
2537 ad = ldexp(ad, aexp * SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002538 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002539 goto overflow;
2540 return PyFloat_FromDouble(ad);
2541
2542overflow:
2543 PyErr_SetString(PyExc_OverflowError,
2544 "long/long too large for a float");
2545 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002546
Tim Peters20dab9f2001-09-04 05:31:47 +00002547}
2548
2549static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002550long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002551{
Tim Peters47e52ee2004-08-30 02:44:38 +00002552 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002553
2554 CONVERT_BINOP(v, w, &a, &b);
2555
Tim Peters47e52ee2004-08-30 02:44:38 +00002556 if (l_divmod(a, b, NULL, &mod) < 0)
2557 mod = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002558 Py_DECREF(a);
2559 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002560 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002561}
2562
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002563static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002564long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002565{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002566 PyLongObject *a, *b, *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002567 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002568
2569 CONVERT_BINOP(v, w, &a, &b);
2570
2571 if (l_divmod(a, b, &div, &mod) < 0) {
2572 Py_DECREF(a);
2573 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002574 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002575 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002576 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002577 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002578 PyTuple_SetItem(z, 0, (PyObject *) div);
2579 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002580 }
2581 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002582 Py_DECREF(div);
2583 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002584 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002585 Py_DECREF(a);
2586 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002587 return z;
2588}
2589
Tim Peters47e52ee2004-08-30 02:44:38 +00002590/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002591static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002592long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002593{
Tim Peters47e52ee2004-08-30 02:44:38 +00002594 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
2595 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002596
Tim Peters47e52ee2004-08-30 02:44:38 +00002597 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002598 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00002599 PyLongObject *temp = NULL;
2600
2601 /* 5-ary values. If the exponent is large enough, table is
2602 * precomputed so that table[i] == a**i % c for i in range(32).
2603 */
2604 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2605 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2606
2607 /* a, b, c = v, w, x */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002608 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002609 if (PyLong_Check(x)) {
2610 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002611 Py_INCREF(x);
2612 }
Tim Petersde7990b2005-07-17 23:45:23 +00002613 else if (PyInt_Check(x)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002614 c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x));
Tim Petersde7990b2005-07-17 23:45:23 +00002615 if (c == NULL)
2616 goto Error;
2617 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002618 else if (x == Py_None)
2619 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002620 else {
2621 Py_DECREF(a);
2622 Py_DECREF(b);
2623 Py_INCREF(Py_NotImplemented);
2624 return Py_NotImplemented;
2625 }
Tim Peters4c483c42001-09-05 06:24:58 +00002626
Tim Peters47e52ee2004-08-30 02:44:38 +00002627 if (b->ob_size < 0) { /* if exponent is negative */
2628 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00002629 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00002630 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00002631 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00002632 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002633 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00002634 /* else return a float. This works because we know
2635 that this calls float_pow() which converts its
2636 arguments to double. */
2637 Py_DECREF(a);
2638 Py_DECREF(b);
2639 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002640 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002641 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002642
2643 if (c) {
2644 /* if modulus == 0:
2645 raise ValueError() */
2646 if (c->ob_size == 0) {
2647 PyErr_SetString(PyExc_ValueError,
2648 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00002649 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002650 }
2651
2652 /* if modulus < 0:
2653 negativeOutput = True
2654 modulus = -modulus */
2655 if (c->ob_size < 0) {
2656 negativeOutput = 1;
2657 temp = (PyLongObject *)_PyLong_Copy(c);
2658 if (temp == NULL)
2659 goto Error;
2660 Py_DECREF(c);
2661 c = temp;
2662 temp = NULL;
2663 c->ob_size = - c->ob_size;
2664 }
2665
2666 /* if modulus == 1:
2667 return 0 */
2668 if ((c->ob_size == 1) && (c->ob_digit[0] == 1)) {
2669 z = (PyLongObject *)PyLong_FromLong(0L);
2670 goto Done;
2671 }
2672
2673 /* if base < 0:
2674 base = base % modulus
2675 Having the base positive just makes things easier. */
2676 if (a->ob_size < 0) {
2677 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00002678 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002679 Py_DECREF(a);
2680 a = temp;
2681 temp = NULL;
2682 }
2683 }
2684
2685 /* At this point a, b, and c are guaranteed non-negative UNLESS
2686 c is NULL, in which case a may be negative. */
2687
2688 z = (PyLongObject *)PyLong_FromLong(1L);
2689 if (z == NULL)
2690 goto Error;
2691
2692 /* Perform a modular reduction, X = X % c, but leave X alone if c
2693 * is NULL.
2694 */
2695#define REDUCE(X) \
2696 if (c != NULL) { \
2697 if (l_divmod(X, c, NULL, &temp) < 0) \
2698 goto Error; \
2699 Py_XDECREF(X); \
2700 X = temp; \
2701 temp = NULL; \
2702 }
2703
2704 /* Multiply two values, then reduce the result:
2705 result = X*Y % c. If c is NULL, skip the mod. */
2706#define MULT(X, Y, result) \
2707{ \
2708 temp = (PyLongObject *)long_mul(X, Y); \
2709 if (temp == NULL) \
2710 goto Error; \
2711 Py_XDECREF(result); \
2712 result = temp; \
2713 temp = NULL; \
2714 REDUCE(result) \
2715}
2716
2717 if (b->ob_size <= FIVEARY_CUTOFF) {
2718 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
2719 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
2720 for (i = b->ob_size - 1; i >= 0; --i) {
2721 digit bi = b->ob_digit[i];
2722
2723 for (j = 1 << (SHIFT-1); j != 0; j >>= 1) {
2724 MULT(z, z, z)
2725 if (bi & j)
2726 MULT(z, a, z)
2727 }
2728 }
2729 }
2730 else {
2731 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
2732 Py_INCREF(z); /* still holds 1L */
2733 table[0] = z;
2734 for (i = 1; i < 32; ++i)
2735 MULT(table[i-1], a, table[i])
2736
2737 for (i = b->ob_size - 1; i >= 0; --i) {
2738 const digit bi = b->ob_digit[i];
2739
2740 for (j = SHIFT - 5; j >= 0; j -= 5) {
2741 const int index = (bi >> j) & 0x1f;
2742 for (k = 0; k < 5; ++k)
2743 MULT(z, z, z)
2744 if (index)
2745 MULT(z, table[index], z)
2746 }
2747 }
2748 }
2749
2750 if (negativeOutput && (z->ob_size != 0)) {
2751 temp = (PyLongObject *)long_sub(z, c);
2752 if (temp == NULL)
2753 goto Error;
2754 Py_DECREF(z);
2755 z = temp;
2756 temp = NULL;
2757 }
2758 goto Done;
2759
2760 Error:
2761 if (z != NULL) {
2762 Py_DECREF(z);
2763 z = NULL;
2764 }
2765 /* fall through */
2766 Done:
Tim Peters47e52ee2004-08-30 02:44:38 +00002767 if (b->ob_size > FIVEARY_CUTOFF) {
2768 for (i = 0; i < 32; ++i)
2769 Py_XDECREF(table[i]);
2770 }
Tim Petersde7990b2005-07-17 23:45:23 +00002771 Py_DECREF(a);
2772 Py_DECREF(b);
2773 Py_XDECREF(c);
2774 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002775 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002776}
2777
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002778static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002779long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002780{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002781 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002782 PyLongObject *x;
2783 PyLongObject *w;
2784 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002785 if (w == NULL)
2786 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002787 x = (PyLongObject *) long_add(v, w);
2788 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002789 if (x == NULL)
2790 return NULL;
Tim Peters40c397d2001-09-11 23:24:22 +00002791 x->ob_size = -(x->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002792 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002793}
2794
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002795static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002796long_pos(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002797{
Tim Peters69c2de32001-09-11 22:31:33 +00002798 if (PyLong_CheckExact(v)) {
2799 Py_INCREF(v);
2800 return (PyObject *)v;
2801 }
2802 else
2803 return _PyLong_Copy(v);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002804}
2805
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002806static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002807long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002808{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002809 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002810 if (v->ob_size == 0 && PyLong_CheckExact(v)) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002811 /* -0 == 0 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002812 Py_INCREF(v);
2813 return (PyObject *) v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002814 }
Tim Peters69c2de32001-09-11 22:31:33 +00002815 z = (PyLongObject *)_PyLong_Copy(v);
2816 if (z != NULL)
2817 z->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002818 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002819}
2820
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002821static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002822long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002823{
2824 if (v->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002825 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00002826 else
2827 return long_pos(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002828}
2829
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002830static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002831long_nonzero(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002832{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002833 return ABS(v->ob_size) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002834}
2835
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002836static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002837long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002838{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002839 PyLongObject *a, *b;
2840 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002841 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002842 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002843 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002844
Neil Schemenauerba872e22001-01-04 01:46:03 +00002845 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2846
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002847 if (a->ob_size < 0) {
2848 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002849 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002850 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002851 if (a1 == NULL)
2852 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002853 a2 = (PyLongObject *) long_rshift(a1, b);
2854 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002855 if (a2 == NULL)
2856 goto rshift_error;
2857 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002858 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002859 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002860 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002861
Neil Schemenauerba872e22001-01-04 01:46:03 +00002862 shiftby = PyLong_AsLong((PyObject *)b);
2863 if (shiftby == -1L && PyErr_Occurred())
2864 goto rshift_error;
2865 if (shiftby < 0) {
2866 PyErr_SetString(PyExc_ValueError,
2867 "negative shift count");
2868 goto rshift_error;
2869 }
2870 wordshift = shiftby / SHIFT;
2871 newsize = ABS(a->ob_size) - wordshift;
2872 if (newsize <= 0) {
2873 z = _PyLong_New(0);
2874 Py_DECREF(a);
2875 Py_DECREF(b);
2876 return (PyObject *)z;
2877 }
2878 loshift = shiftby % SHIFT;
2879 hishift = SHIFT - loshift;
2880 lomask = ((digit)1 << hishift) - 1;
2881 himask = MASK ^ lomask;
2882 z = _PyLong_New(newsize);
2883 if (z == NULL)
2884 goto rshift_error;
2885 if (a->ob_size < 0)
2886 z->ob_size = -(z->ob_size);
2887 for (i = 0, j = wordshift; i < newsize; i++, j++) {
2888 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
2889 if (i+1 < newsize)
2890 z->ob_digit[i] |=
2891 (a->ob_digit[j+1] << hishift) & himask;
2892 }
2893 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002894 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002895rshift_error:
2896 Py_DECREF(a);
2897 Py_DECREF(b);
2898 return (PyObject *) z;
2899
Guido van Rossumc6913e71991-11-19 20:26:46 +00002900}
2901
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002902static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002903long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002904{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002905 /* This version due to Tim Peters */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002906 PyLongObject *a, *b;
2907 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002908 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002909 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002910 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002911
Neil Schemenauerba872e22001-01-04 01:46:03 +00002912 CONVERT_BINOP(v, w, &a, &b);
2913
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002914 shiftby = PyLong_AsLong((PyObject *)b);
2915 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00002916 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002917 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002918 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00002919 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002920 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002921 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002922 PyErr_SetString(PyExc_ValueError,
2923 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00002924 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002925 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002926 /* wordshift, remshift = divmod(shiftby, SHIFT) */
2927 wordshift = (int)shiftby / SHIFT;
2928 remshift = (int)shiftby - wordshift * SHIFT;
2929
2930 oldsize = ABS(a->ob_size);
2931 newsize = oldsize + wordshift;
2932 if (remshift)
2933 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002934 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002935 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002936 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002937 if (a->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002938 z->ob_size = -(z->ob_size);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002939 for (i = 0; i < wordshift; i++)
2940 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002941 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002942 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00002943 accum |= (twodigits)a->ob_digit[j] << remshift;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002944 z->ob_digit[i] = (digit)(accum & MASK);
2945 accum >>= SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002946 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002947 if (remshift)
2948 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002949 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002950 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002951 z = long_normalize(z);
2952lshift_error:
2953 Py_DECREF(a);
2954 Py_DECREF(b);
2955 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002956}
2957
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002958
2959/* Bitwise and/xor/or operations */
2960
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002961static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002962long_bitwise(PyLongObject *a,
2963 int op, /* '&', '|', '^' */
2964 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002965{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002966 digit maska, maskb; /* 0 or MASK */
2967 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002968 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002969 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002970 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00002971 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002972 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002973
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002974 if (a->ob_size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002975 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00002976 if (a == NULL)
2977 return NULL;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002978 maska = MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002979 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002980 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002981 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002982 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00002983 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002984 if (b->ob_size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002985 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00002986 if (b == NULL) {
2987 Py_DECREF(a);
2988 return NULL;
2989 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002990 maskb = MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002991 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002992 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002993 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002994 maskb = 0;
2995 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002996
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002997 negz = 0;
2998 switch (op) {
2999 case '^':
3000 if (maska != maskb) {
3001 maska ^= MASK;
3002 negz = -1;
3003 }
3004 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003005 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003006 if (maska && maskb) {
3007 op = '|';
3008 maska ^= MASK;
3009 maskb ^= MASK;
3010 negz = -1;
3011 }
3012 break;
3013 case '|':
3014 if (maska || maskb) {
3015 op = '&';
3016 maska ^= MASK;
3017 maskb ^= MASK;
3018 negz = -1;
3019 }
3020 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003021 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003022
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003023 /* JRH: The original logic here was to allocate the result value (z)
3024 as the longer of the two operands. However, there are some cases
3025 where the result is guaranteed to be shorter than that: AND of two
3026 positives, OR of two negatives: use the shorter number. AND with
3027 mixed signs: use the positive number. OR with mixed signs: use the
3028 negative number. After the transformations above, op will be '&'
3029 iff one of these cases applies, and mask will be non-0 for operands
3030 whose length should be ignored.
3031 */
3032
3033 size_a = a->ob_size;
3034 size_b = b->ob_size;
3035 size_z = op == '&'
3036 ? (maska
3037 ? size_b
3038 : (maskb ? size_a : MIN(size_a, size_b)))
3039 : MAX(size_a, size_b);
3040 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003041 if (z == NULL) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003042 Py_XDECREF(a);
3043 Py_XDECREF(b);
3044 Py_XDECREF(z);
3045 return NULL;
3046 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003047
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003048 for (i = 0; i < size_z; ++i) {
3049 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3050 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3051 switch (op) {
3052 case '&': z->ob_digit[i] = diga & digb; break;
3053 case '|': z->ob_digit[i] = diga | digb; break;
3054 case '^': z->ob_digit[i] = diga ^ digb; break;
3055 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003056 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003057
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003058 Py_DECREF(a);
3059 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003060 z = long_normalize(z);
3061 if (negz == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003062 return (PyObject *) z;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003063 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003064 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003065 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003066}
3067
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003068static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003069long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003070{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003071 PyLongObject *a, *b;
3072 PyObject *c;
3073 CONVERT_BINOP(v, w, &a, &b);
3074 c = long_bitwise(a, '&', b);
3075 Py_DECREF(a);
3076 Py_DECREF(b);
3077 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003078}
3079
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003080static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003081long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003082{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003083 PyLongObject *a, *b;
3084 PyObject *c;
3085 CONVERT_BINOP(v, w, &a, &b);
3086 c = long_bitwise(a, '^', b);
3087 Py_DECREF(a);
3088 Py_DECREF(b);
3089 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003090}
3091
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003092static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003093long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003094{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003095 PyLongObject *a, *b;
3096 PyObject *c;
3097 CONVERT_BINOP(v, w, &a, &b);
3098 c = long_bitwise(a, '|', b);
3099 Py_DECREF(a);
3100 Py_DECREF(b);
3101 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003102}
3103
Guido van Rossum234f9421993-06-17 12:35:49 +00003104static int
Tim Peters9f688bf2000-07-07 15:53:28 +00003105long_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00003106{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003107 if (PyInt_Check(*pw)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00003108 *pw = PyLong_FromLong(PyInt_AS_LONG(*pw));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003109 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00003110 return 0;
3111 }
Guido van Rossum1952e382001-09-19 01:25:16 +00003112 else if (PyLong_Check(*pw)) {
3113 Py_INCREF(*pv);
3114 Py_INCREF(*pw);
3115 return 0;
3116 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00003117 return 1; /* Can't do it */
3118}
3119
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003120static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003121long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003122{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003123 if (PyLong_CheckExact(v))
3124 Py_INCREF(v);
3125 else
3126 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003127 return v;
3128}
3129
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003130static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00003131long_int(PyObject *v)
3132{
3133 long x;
3134 x = PyLong_AsLong(v);
3135 if (PyErr_Occurred()) {
3136 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
3137 PyErr_Clear();
3138 if (PyLong_CheckExact(v)) {
3139 Py_INCREF(v);
3140 return v;
3141 }
3142 else
3143 return _PyLong_Copy((PyLongObject *)v);
3144 }
3145 else
3146 return NULL;
3147 }
3148 return PyInt_FromLong(x);
3149}
3150
3151static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003152long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003153{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003154 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003155 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003156 if (result == -1.0 && PyErr_Occurred())
3157 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003158 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003159}
3160
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003161static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003162long_oct(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003163{
Fred Drake121ee271999-12-23 15:41:28 +00003164 return long_format(v, 8, 1);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003165}
3166
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003167static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003168long_hex(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003169{
Fred Drake121ee271999-12-23 15:41:28 +00003170 return long_format(v, 16, 1);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003171}
Jeremy Hylton938ace62002-07-17 16:30:39 +00003172
3173static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003174long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003175
Tim Peters6d6c1a32001-08-02 04:15:00 +00003176static PyObject *
3177long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3178{
3179 PyObject *x = NULL;
3180 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003181 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003182
Guido van Rossumbef14172001-08-29 15:47:46 +00003183 if (type != &PyLong_Type)
3184 return long_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003185 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist,
3186 &x, &base))
3187 return NULL;
3188 if (x == NULL)
3189 return PyLong_FromLong(0L);
3190 if (base == -909)
3191 return PyNumber_Long(x);
3192 else if (PyString_Check(x))
3193 return PyLong_FromString(PyString_AS_STRING(x), NULL, base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003194#ifdef Py_USING_UNICODE
Tim Peters6d6c1a32001-08-02 04:15:00 +00003195 else if (PyUnicode_Check(x))
3196 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3197 PyUnicode_GET_SIZE(x),
3198 base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003199#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +00003200 else {
3201 PyErr_SetString(PyExc_TypeError,
3202 "long() can't convert non-string with explicit base");
3203 return NULL;
3204 }
3205}
3206
Guido van Rossumbef14172001-08-29 15:47:46 +00003207/* Wimpy, slow approach to tp_new calls for subtypes of long:
3208 first create a regular long from whatever arguments we got,
3209 then allocate a subtype instance and initialize it from
3210 the regular long. The regular long is then thrown away.
3211*/
3212static PyObject *
3213long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3214{
Anthony Baxter377be112006-04-11 06:54:30 +00003215 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003216 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003217
3218 assert(PyType_IsSubtype(type, &PyLong_Type));
3219 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3220 if (tmp == NULL)
3221 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003222 assert(PyLong_CheckExact(tmp));
Guido van Rossumbef14172001-08-29 15:47:46 +00003223 n = tmp->ob_size;
3224 if (n < 0)
3225 n = -n;
Anthony Baxter377be112006-04-11 06:54:30 +00003226 newobj = (PyLongObject *)type->tp_alloc(type, n);
3227 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003228 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003229 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003230 }
Anthony Baxter377be112006-04-11 06:54:30 +00003231 assert(PyLong_Check(newobj));
3232 newobj->ob_size = tmp->ob_size;
Guido van Rossumbef14172001-08-29 15:47:46 +00003233 for (i = 0; i < n; i++)
Anthony Baxter377be112006-04-11 06:54:30 +00003234 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003235 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00003236 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003237}
3238
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003239static PyObject *
3240long_getnewargs(PyLongObject *v)
3241{
3242 return Py_BuildValue("(N)", _PyLong_Copy(v));
3243}
3244
3245static PyMethodDef long_methods[] = {
3246 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
3247 {NULL, NULL} /* sentinel */
3248};
3249
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003250PyDoc_STRVAR(long_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003251"long(x[, base]) -> integer\n\
3252\n\
3253Convert a string or number to a long integer, if possible. A floating\n\
3254point argument will be truncated towards zero (this does not include a\n\
3255string representation of a floating point number!) When converting a\n\
3256string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003257converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003258
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003259static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003260 (binaryfunc) long_add, /*nb_add*/
3261 (binaryfunc) long_sub, /*nb_subtract*/
3262 (binaryfunc) long_mul, /*nb_multiply*/
Georg Brandl347b3002006-03-30 11:57:00 +00003263 long_classic_div, /*nb_divide*/
3264 long_mod, /*nb_remainder*/
3265 long_divmod, /*nb_divmod*/
3266 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003267 (unaryfunc) long_neg, /*nb_negative*/
3268 (unaryfunc) long_pos, /*tp_positive*/
3269 (unaryfunc) long_abs, /*tp_absolute*/
3270 (inquiry) long_nonzero, /*tp_nonzero*/
3271 (unaryfunc) long_invert, /*nb_invert*/
Georg Brandl347b3002006-03-30 11:57:00 +00003272 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003273 (binaryfunc) long_rshift, /*nb_rshift*/
Georg Brandl347b3002006-03-30 11:57:00 +00003274 long_and, /*nb_and*/
3275 long_xor, /*nb_xor*/
3276 long_or, /*nb_or*/
3277 long_coerce, /*nb_coerce*/
3278 long_int, /*nb_int*/
3279 long_long, /*nb_long*/
3280 long_float, /*nb_float*/
3281 long_oct, /*nb_oct*/
3282 long_hex, /*nb_hex*/
Guido van Rossum4668b002001-08-08 05:00:18 +00003283 0, /* nb_inplace_add */
3284 0, /* nb_inplace_subtract */
3285 0, /* nb_inplace_multiply */
3286 0, /* nb_inplace_divide */
3287 0, /* nb_inplace_remainder */
3288 0, /* nb_inplace_power */
3289 0, /* nb_inplace_lshift */
3290 0, /* nb_inplace_rshift */
3291 0, /* nb_inplace_and */
3292 0, /* nb_inplace_xor */
3293 0, /* nb_inplace_or */
Georg Brandl347b3002006-03-30 11:57:00 +00003294 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003295 long_true_divide, /* nb_true_divide */
3296 0, /* nb_inplace_floor_divide */
3297 0, /* nb_inplace_true_divide */
Georg Brandl347b3002006-03-30 11:57:00 +00003298 long_index, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003299};
3300
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003301PyTypeObject PyLong_Type = {
3302 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003303 0, /* ob_size */
3304 "long", /* tp_name */
3305 sizeof(PyLongObject) - sizeof(digit), /* tp_basicsize */
3306 sizeof(digit), /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00003307 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003308 0, /* tp_print */
3309 0, /* tp_getattr */
3310 0, /* tp_setattr */
3311 (cmpfunc)long_compare, /* tp_compare */
Georg Brandl347b3002006-03-30 11:57:00 +00003312 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003313 &long_as_number, /* tp_as_number */
3314 0, /* tp_as_sequence */
3315 0, /* tp_as_mapping */
3316 (hashfunc)long_hash, /* tp_hash */
3317 0, /* tp_call */
Georg Brandl347b3002006-03-30 11:57:00 +00003318 long_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003319 PyObject_GenericGetAttr, /* tp_getattro */
3320 0, /* tp_setattro */
3321 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00003322 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3323 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003324 long_doc, /* tp_doc */
3325 0, /* tp_traverse */
3326 0, /* tp_clear */
3327 0, /* tp_richcompare */
3328 0, /* tp_weaklistoffset */
3329 0, /* tp_iter */
3330 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003331 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003332 0, /* tp_members */
3333 0, /* tp_getset */
3334 0, /* tp_base */
3335 0, /* tp_dict */
3336 0, /* tp_descr_get */
3337 0, /* tp_descr_set */
3338 0, /* tp_dictoffset */
3339 0, /* tp_init */
3340 0, /* tp_alloc */
3341 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003342 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003343};