blob: e47c292c9506f80b6b6edc0034526a463c980b0f [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003/* Long (arbitrary precision) integer object implementation */
4
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00005/* XXX The functional organization of this file is terrible */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Guido van Rossumedcc38a1991-05-05 20:09:44 +00008#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00009
Guido van Rossumeb1fafc1994-08-29 12:47:19 +000010#include <ctype.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000011
Tim Peters5af4e6c2002-08-12 02:31:19 +000012/* For long multiplication, use the O(N**2) school algorithm unless
13 * both operands contain more than KARATSUBA_CUTOFF digits (this
14 * being an internal Python long digit, in base BASE).
15 */
Tim Peters0973b992004-08-29 22:16:50 +000016#define KARATSUBA_CUTOFF 70
17#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000018
Tim Peters47e52ee2004-08-30 02:44:38 +000019/* For exponentiation, use the binary left-to-right algorithm
20 * unless the exponent contains more than FIVEARY_CUTOFF digits.
21 * In that case, do 5 bits at a time. The potential drawback is that
22 * a table of 2**5 intermediate results is computed.
23 */
24#define FIVEARY_CUTOFF 8
25
Guido van Rossume32e0141992-01-19 16:31:05 +000026#define ABS(x) ((x) < 0 ? -(x) : (x))
27
Tim Peters5af4e6c2002-08-12 02:31:19 +000028#undef MIN
29#undef MAX
30#define MAX(x, y) ((x) < (y) ? (y) : (x))
31#define MIN(x, y) ((x) > (y) ? (y) : (x))
32
Guido van Rossume32e0141992-01-19 16:31:05 +000033/* Forward */
Tim Peters9f688bf2000-07-07 15:53:28 +000034static PyLongObject *long_normalize(PyLongObject *);
35static PyLongObject *mul1(PyLongObject *, wdigit);
36static PyLongObject *muladd1(PyLongObject *, wdigit, wdigit);
Tim Peters212e6142001-07-14 12:23:19 +000037static PyLongObject *divrem1(PyLongObject *, digit, digit *);
Tim Peters9f688bf2000-07-07 15:53:28 +000038static PyObject *long_format(PyObject *aa, int base, int addL);
Guido van Rossume32e0141992-01-19 16:31:05 +000039
Guido van Rossumc0b618a1997-05-02 03:12:38 +000040#define SIGCHECK(PyTryBlock) \
Skip Montanarod581d772002-09-03 20:10:45 +000041 if (--_Py_Ticker < 0) { \
42 _Py_Ticker = _Py_CheckInterval; \
Guido van Rossumc0b618a1997-05-02 03:12:38 +000043 if (PyErr_CheckSignals()) { PyTryBlock; } \
Guido van Rossum23d6f0e1991-05-14 12:06:49 +000044 }
45
Guido van Rossumedcc38a1991-05-05 20:09:44 +000046/* Normalize (remove leading zeros from) a long int object.
47 Doesn't attempt to free the storage--in most cases, due to the nature
48 of the algorithms used, this could save at most be one word anyway. */
49
Guido van Rossumc0b618a1997-05-02 03:12:38 +000050static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +000051long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +000052{
Martin v. Löwis18e16552006-02-15 17:27:45 +000053 Py_ssize_t j = ABS(v->ob_size);
54 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +000055
Guido van Rossumedcc38a1991-05-05 20:09:44 +000056 while (i > 0 && v->ob_digit[i-1] == 0)
57 --i;
58 if (i != j)
Guido van Rossum4c260ff1992-01-14 18:36:43 +000059 v->ob_size = (v->ob_size < 0) ? -(i) : i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +000060 return v;
61}
62
63/* Allocate a new long int object with size digits.
64 Return NULL and set exception if we run out of memory. */
65
Guido van Rossumc0b618a1997-05-02 03:12:38 +000066PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000067_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +000068{
Martin v. Löwis18e16552006-02-15 17:27:45 +000069 if (size > INT_MAX) {
70 /* XXX: Fix this check when ob_size becomes ssize_t */
71 PyErr_NoMemory();
72 return NULL;
73 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +000074 return PyObject_NEW_VAR(PyLongObject, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +000075}
76
Tim Peters64b5ce32001-09-10 20:52:51 +000077PyObject *
78_PyLong_Copy(PyLongObject *src)
79{
80 PyLongObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +000081 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +000082
83 assert(src != NULL);
84 i = src->ob_size;
85 if (i < 0)
86 i = -(i);
87 result = _PyLong_New(i);
88 if (result != NULL) {
Tim Peters5329cdb2002-03-02 04:18:04 +000089 result->ob_size = src->ob_size;
Tim Peters64b5ce32001-09-10 20:52:51 +000090 while (--i >= 0)
91 result->ob_digit[i] = src->ob_digit[i];
92 }
93 return (PyObject *)result;
94}
95
Guido van Rossumedcc38a1991-05-05 20:09:44 +000096/* Create a new long int object from a C long int */
97
Guido van Rossumc0b618a1997-05-02 03:12:38 +000098PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +000099PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000100{
Tim Petersce9de2f2001-06-14 04:56:19 +0000101 PyLongObject *v;
102 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
103 int ndigits = 0;
104 int negative = 0;
105
106 if (ival < 0) {
107 ival = -ival;
108 negative = 1;
109 }
110
111 /* Count the number of Python digits.
112 We used to pick 5 ("big enough for anything"), but that's a
113 waste of time and space given that 5*15 = 75 bits are rarely
114 needed. */
115 t = (unsigned long)ival;
116 while (t) {
117 ++ndigits;
118 t >>= SHIFT;
119 }
120 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000121 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000122 digit *p = v->ob_digit;
123 v->ob_size = negative ? -ndigits : ndigits;
124 t = (unsigned long)ival;
125 while (t) {
126 *p++ = (digit)(t & MASK);
Guido van Rossum472c04f1996-12-05 21:57:21 +0000127 t >>= SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000128 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000129 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000130 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000131}
132
Guido van Rossum53756b11997-01-03 17:14:46 +0000133/* Create a new long int object from a C unsigned long int */
134
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000135PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000136PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000137{
Tim Petersce9de2f2001-06-14 04:56:19 +0000138 PyLongObject *v;
139 unsigned long t;
140 int ndigits = 0;
141
142 /* Count the number of Python digits. */
143 t = (unsigned long)ival;
144 while (t) {
145 ++ndigits;
146 t >>= SHIFT;
147 }
148 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000149 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000150 digit *p = v->ob_digit;
151 v->ob_size = ndigits;
152 while (ival) {
153 *p++ = (digit)(ival & MASK);
154 ival >>= SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000155 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000156 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000157 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000158}
159
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000160/* Create a new long int object from a C double */
161
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000162PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000163PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000164{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000165 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000166 double frac;
167 int i, ndig, expo, neg;
168 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000169 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000170 PyErr_SetString(PyExc_OverflowError,
171 "cannot convert float infinity to long");
172 return NULL;
173 }
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000174 if (dval < 0.0) {
175 neg = 1;
176 dval = -dval;
177 }
178 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
179 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000180 return PyLong_FromLong(0L);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000181 ndig = (expo-1) / SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000182 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000183 if (v == NULL)
184 return NULL;
185 frac = ldexp(frac, (expo-1) % SHIFT + 1);
186 for (i = ndig; --i >= 0; ) {
187 long bits = (long)frac;
Guido van Rossum2095d241997-04-09 19:41:24 +0000188 v->ob_digit[i] = (digit) bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000189 frac = frac - (double)bits;
190 frac = ldexp(frac, SHIFT);
191 }
192 if (neg)
Guido van Rossum4c260ff1992-01-14 18:36:43 +0000193 v->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000194 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000195}
196
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000197/* Get a C long int from a long int object.
198 Returns -1 and sets an error condition if overflow occurs. */
199
200long
Tim Peters9f688bf2000-07-07 15:53:28 +0000201PyLong_AsLong(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000202{
Guido van Rossumf7531811998-05-26 14:33:37 +0000203 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000204 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000205 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000206 Py_ssize_t i;
207 int sign;
Guido van Rossumf7531811998-05-26 14:33:37 +0000208
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000209 if (vv == NULL || !PyLong_Check(vv)) {
Guido van Rossum7e35d572001-09-15 03:14:32 +0000210 if (vv != NULL && PyInt_Check(vv))
211 return PyInt_AsLong(vv);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000212 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000213 return -1;
214 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000215 v = (PyLongObject *)vv;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000216 i = v->ob_size;
217 sign = 1;
218 x = 0;
219 if (i < 0) {
220 sign = -1;
Guido van Rossum4c260ff1992-01-14 18:36:43 +0000221 i = -(i);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000222 }
223 while (--i >= 0) {
224 prev = x;
225 x = (x << SHIFT) + v->ob_digit[i];
Guido van Rossumf7531811998-05-26 14:33:37 +0000226 if ((x >> SHIFT) != prev)
227 goto overflow;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000228 }
Guido van Rossumf7531811998-05-26 14:33:37 +0000229 /* Haven't lost any bits, but if the sign bit is set we're in
230 * trouble *unless* this is the min negative number. So,
231 * trouble iff sign bit set && (positive || some bit set other
232 * than the sign bit).
233 */
234 if ((long)x < 0 && (sign > 0 || (x << 1) != 0))
235 goto overflow;
236 return (long)x * sign;
237
238 overflow:
239 PyErr_SetString(PyExc_OverflowError,
Skip Montanarobafedec2001-09-13 19:05:30 +0000240 "long int too large to convert to int");
Guido van Rossumf7531811998-05-26 14:33:37 +0000241 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000242}
243
Guido van Rossum38fff8c2006-03-07 18:50:55 +0000244static Py_ssize_t
245_long_as_ssize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000246 register PyLongObject *v;
247 size_t x, prev;
248 Py_ssize_t i;
249 int sign;
250
251 if (vv == NULL || !PyLong_Check(vv)) {
252 PyErr_BadInternalCall();
253 return -1;
254 }
255 v = (PyLongObject *)vv;
256 i = v->ob_size;
257 sign = 1;
258 x = 0;
259 if (i < 0) {
260 sign = -1;
261 i = -(i);
262 }
263 while (--i >= 0) {
264 prev = x;
265 x = (x << SHIFT) + v->ob_digit[i];
266 if ((x >> SHIFT) != prev)
267 goto overflow;
268 }
269 /* Haven't lost any bits, but if the sign bit is set we're in
270 * trouble *unless* this is the min negative number. So,
271 * trouble iff sign bit set && (positive || some bit set other
272 * than the sign bit).
273 */
274 if ((Py_ssize_t)x < 0 && (sign > 0 || (x << 1) != 0))
275 goto overflow;
276 return (Py_ssize_t)x * sign;
277
278 overflow:
279 PyErr_SetString(PyExc_OverflowError,
280 "long int too large to convert to int");
Guido van Rossum38fff8c2006-03-07 18:50:55 +0000281 if (sign > 0)
282 return PY_SSIZE_T_MAX;
283 else
284 return -PY_SSIZE_T_MAX-1;
285}
286
287/* Get a Py_ssize_t from a long int object.
288 Returns -1 and sets an error condition if overflow occurs. */
289
290Py_ssize_t
291_PyLong_AsSsize_t(PyObject *vv)
292{
293 Py_ssize_t x;
294
295 x = _long_as_ssize_t(vv);
296 if (PyErr_Occurred()) return -1;
297 return x;
298}
299
300
301/* Get a Py_ssize_t from a long int object.
302 Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX,
303 and silently boost values less than -PY_SSIZE_T_MAX-1 to -PY_SSIZE_T_MAX-1.
304 Return 0 on error, 1 on success.
305*/
306
307static Py_ssize_t
308long_index(PyObject *vv)
309{
310 Py_ssize_t x;
311
312 x = _long_as_ssize_t(vv);
313 if (PyErr_Occurred()) {
314 /* If overflow error, ignore the error */
315 if (x != -1) {
316 PyErr_Clear();
317 }
318 }
319 return x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000320}
321
Guido van Rossumd8c80482002-08-13 00:24:58 +0000322/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000323 Returns -1 and sets an error condition if overflow occurs. */
324
325unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000326PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000327{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000328 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000329 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000330 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000331
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000332 if (vv == NULL || !PyLong_Check(vv)) {
Martin v. Löwis729d47d2004-09-20 06:17:46 +0000333 if (vv != NULL && PyInt_Check(vv)) {
334 long val = PyInt_AsLong(vv);
335 if (val < 0) {
336 PyErr_SetString(PyExc_OverflowError,
337 "can't convert negative value to unsigned long");
338 return (unsigned long) -1;
339 }
340 return val;
341 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000342 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000343 return (unsigned long) -1;
344 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000345 v = (PyLongObject *)vv;
Guido van Rossum53756b11997-01-03 17:14:46 +0000346 i = v->ob_size;
347 x = 0;
348 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000349 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum53756b11997-01-03 17:14:46 +0000350 "can't convert negative value to unsigned long");
351 return (unsigned long) -1;
352 }
353 while (--i >= 0) {
354 prev = x;
355 x = (x << SHIFT) + v->ob_digit[i];
356 if ((x >> SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000357 PyErr_SetString(PyExc_OverflowError,
Fred Drake661ea262000-10-24 19:57:45 +0000358 "long int too large to convert");
Guido van Rossum53756b11997-01-03 17:14:46 +0000359 return (unsigned long) -1;
360 }
361 }
362 return x;
363}
364
Thomas Hellera4ea6032003-04-17 18:55:45 +0000365/* Get a C unsigned long int from a long int object, ignoring the high bits.
366 Returns -1 and sets an error condition if an error occurs. */
367
368unsigned long
369PyLong_AsUnsignedLongMask(PyObject *vv)
370{
371 register PyLongObject *v;
372 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000373 Py_ssize_t i;
374 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000375
376 if (vv == NULL || !PyLong_Check(vv)) {
Martin v. Löwis729d47d2004-09-20 06:17:46 +0000377 if (vv != NULL && PyInt_Check(vv))
378 return PyInt_AsUnsignedLongMask(vv);
Thomas Hellera4ea6032003-04-17 18:55:45 +0000379 PyErr_BadInternalCall();
380 return (unsigned long) -1;
381 }
382 v = (PyLongObject *)vv;
383 i = v->ob_size;
384 sign = 1;
385 x = 0;
386 if (i < 0) {
387 sign = -1;
388 i = -i;
389 }
390 while (--i >= 0) {
391 x = (x << SHIFT) + v->ob_digit[i];
392 }
393 return x * sign;
394}
395
Tim Peters5b8132f2003-01-31 15:52:05 +0000396int
397_PyLong_Sign(PyObject *vv)
398{
399 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000400
401 assert(v != NULL);
402 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000403
Tim Petersee1a53c2003-02-02 02:57:53 +0000404 return v->ob_size == 0 ? 0 : (v->ob_size < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000405}
406
Tim Petersbaefd9e2003-01-28 20:37:45 +0000407size_t
408_PyLong_NumBits(PyObject *vv)
409{
410 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000411 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000412 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000413
414 assert(v != NULL);
415 assert(PyLong_Check(v));
Guido van Rossum004a65c2003-02-03 15:28:19 +0000416 ndigits = ABS(v->ob_size);
Tim Petersbaefd9e2003-01-28 20:37:45 +0000417 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
418 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000419 digit msd = v->ob_digit[ndigits - 1];
420
Tim Peters5b8132f2003-01-31 15:52:05 +0000421 result = (ndigits - 1) * SHIFT;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000422 if (result / SHIFT != ndigits - 1)
Tim Petersbaefd9e2003-01-28 20:37:45 +0000423 goto Overflow;
424 do {
425 ++result;
426 if (result == 0)
427 goto Overflow;
428 msd >>= 1;
429 } while (msd);
430 }
431 return result;
432
433Overflow:
434 PyErr_SetString(PyExc_OverflowError, "long has too many bits "
435 "to express in a platform size_t");
436 return (size_t)-1;
437}
438
Tim Peters2a9b3672001-06-11 21:23:58 +0000439PyObject *
440_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
441 int little_endian, int is_signed)
442{
443 const unsigned char* pstartbyte;/* LSB of bytes */
444 int incr; /* direction to move pstartbyte */
445 const unsigned char* pendbyte; /* MSB of bytes */
446 size_t numsignificantbytes; /* number of bytes that matter */
447 size_t ndigits; /* number of Python long digits */
448 PyLongObject* v; /* result */
449 int idigit = 0; /* next free index in v->ob_digit */
450
451 if (n == 0)
452 return PyLong_FromLong(0L);
453
454 if (little_endian) {
455 pstartbyte = bytes;
456 pendbyte = bytes + n - 1;
457 incr = 1;
458 }
459 else {
460 pstartbyte = bytes + n - 1;
461 pendbyte = bytes;
462 incr = -1;
463 }
464
465 if (is_signed)
466 is_signed = *pendbyte >= 0x80;
467
468 /* Compute numsignificantbytes. This consists of finding the most
469 significant byte. Leading 0 bytes are insignficant if the number
470 is positive, and leading 0xff bytes if negative. */
471 {
472 size_t i;
473 const unsigned char* p = pendbyte;
474 const int pincr = -incr; /* search MSB to LSB */
475 const unsigned char insignficant = is_signed ? 0xff : 0x00;
476
477 for (i = 0; i < n; ++i, p += pincr) {
478 if (*p != insignficant)
479 break;
480 }
481 numsignificantbytes = n - i;
482 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
483 actually has 2 significant bytes. OTOH, 0xff0001 ==
484 -0x00ffff, so we wouldn't *need* to bump it there; but we
485 do for 0xffff = -0x0001. To be safe without bothering to
486 check every case, bump it regardless. */
487 if (is_signed && numsignificantbytes < n)
488 ++numsignificantbytes;
489 }
490
491 /* How many Python long digits do we need? We have
492 8*numsignificantbytes bits, and each Python long digit has SHIFT
493 bits, so it's the ceiling of the quotient. */
494 ndigits = (numsignificantbytes * 8 + SHIFT - 1) / SHIFT;
495 if (ndigits > (size_t)INT_MAX)
496 return PyErr_NoMemory();
497 v = _PyLong_New((int)ndigits);
498 if (v == NULL)
499 return NULL;
500
501 /* Copy the bits over. The tricky parts are computing 2's-comp on
502 the fly for signed numbers, and dealing with the mismatch between
503 8-bit bytes and (probably) 15-bit Python digits.*/
504 {
505 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000506 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000507 twodigits accum = 0; /* sliding register */
508 unsigned int accumbits = 0; /* number of bits in accum */
509 const unsigned char* p = pstartbyte;
510
511 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000512 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000513 /* Compute correction for 2's comp, if needed. */
514 if (is_signed) {
515 thisbyte = (0xff ^ thisbyte) + carry;
516 carry = thisbyte >> 8;
517 thisbyte &= 0xff;
518 }
519 /* Because we're going LSB to MSB, thisbyte is
520 more significant than what's already in accum,
521 so needs to be prepended to accum. */
522 accum |= thisbyte << accumbits;
523 accumbits += 8;
524 if (accumbits >= SHIFT) {
525 /* There's enough to fill a Python digit. */
526 assert(idigit < (int)ndigits);
527 v->ob_digit[idigit] = (digit)(accum & MASK);
528 ++idigit;
529 accum >>= SHIFT;
530 accumbits -= SHIFT;
531 assert(accumbits < SHIFT);
532 }
533 }
534 assert(accumbits < SHIFT);
535 if (accumbits) {
536 assert(idigit < (int)ndigits);
537 v->ob_digit[idigit] = (digit)accum;
538 ++idigit;
539 }
540 }
541
542 v->ob_size = is_signed ? -idigit : idigit;
543 return (PyObject *)long_normalize(v);
544}
545
546int
547_PyLong_AsByteArray(PyLongObject* v,
548 unsigned char* bytes, size_t n,
549 int little_endian, int is_signed)
550{
551 int i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000552 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000553 twodigits accum; /* sliding register */
554 unsigned int accumbits; /* # bits in accum */
555 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
556 twodigits carry; /* for computing 2's-comp */
557 size_t j; /* # bytes filled */
558 unsigned char* p; /* pointer to next byte in bytes */
559 int pincr; /* direction to move p */
560
561 assert(v != NULL && PyLong_Check(v));
562
563 if (v->ob_size < 0) {
564 ndigits = -(v->ob_size);
565 if (!is_signed) {
566 PyErr_SetString(PyExc_TypeError,
567 "can't convert negative long to unsigned");
568 return -1;
569 }
570 do_twos_comp = 1;
571 }
572 else {
573 ndigits = v->ob_size;
574 do_twos_comp = 0;
575 }
576
577 if (little_endian) {
578 p = bytes;
579 pincr = 1;
580 }
581 else {
582 p = bytes + n - 1;
583 pincr = -1;
584 }
585
Tim Peters898cf852001-06-13 20:50:08 +0000586 /* Copy over all the Python digits.
587 It's crucial that every Python digit except for the MSD contribute
588 exactly SHIFT bits to the total, so first assert that the long is
589 normalized. */
590 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000591 j = 0;
592 accum = 0;
593 accumbits = 0;
594 carry = do_twos_comp ? 1 : 0;
595 for (i = 0; i < ndigits; ++i) {
596 twodigits thisdigit = v->ob_digit[i];
597 if (do_twos_comp) {
598 thisdigit = (thisdigit ^ MASK) + carry;
599 carry = thisdigit >> SHIFT;
600 thisdigit &= MASK;
601 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000602 /* Because we're going LSB to MSB, thisdigit is more
603 significant than what's already in accum, so needs to be
604 prepended to accum. */
605 accum |= thisdigit << accumbits;
Tim Petersede05092001-06-14 08:53:38 +0000606 accumbits += SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000607
Tim Petersede05092001-06-14 08:53:38 +0000608 /* The most-significant digit may be (probably is) at least
609 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000610 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000611 /* Count # of sign bits -- they needn't be stored,
612 * although for signed conversion we need later to
613 * make sure at least one sign bit gets stored.
614 * First shift conceptual sign bit to real sign bit.
615 */
616 stwodigits s = (stwodigits)(thisdigit <<
617 (8*sizeof(stwodigits) - SHIFT));
Tim Peters7a3bfc32001-06-12 01:22:22 +0000618 unsigned int nsignbits = 0;
Tim Petersede05092001-06-14 08:53:38 +0000619 while ((s < 0) == do_twos_comp && nsignbits < SHIFT) {
Tim Peters7a3bfc32001-06-12 01:22:22 +0000620 ++nsignbits;
Tim Petersede05092001-06-14 08:53:38 +0000621 s <<= 1;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000622 }
Tim Petersede05092001-06-14 08:53:38 +0000623 accumbits -= nsignbits;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000624 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000625
Tim Peters2a9b3672001-06-11 21:23:58 +0000626 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000627 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000628 if (j >= n)
629 goto Overflow;
630 ++j;
631 *p = (unsigned char)(accum & 0xff);
632 p += pincr;
633 accumbits -= 8;
634 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000635 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000636 }
637
638 /* Store the straggler (if any). */
639 assert(accumbits < 8);
640 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000641 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000642 if (j >= n)
643 goto Overflow;
644 ++j;
645 if (do_twos_comp) {
646 /* Fill leading bits of the byte with sign bits
647 (appropriately pretending that the long had an
648 infinite supply of sign bits). */
649 accum |= (~(twodigits)0) << accumbits;
650 }
651 *p = (unsigned char)(accum & 0xff);
652 p += pincr;
653 }
Tim Peters05607ad2001-06-13 21:01:27 +0000654 else if (j == n && n > 0 && is_signed) {
655 /* The main loop filled the byte array exactly, so the code
656 just above didn't get to ensure there's a sign bit, and the
657 loop below wouldn't add one either. Make sure a sign bit
658 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000659 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000660 int sign_bit_set = msb >= 0x80;
661 assert(accumbits == 0);
662 if (sign_bit_set == do_twos_comp)
663 return 0;
664 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000665 goto Overflow;
666 }
Tim Peters05607ad2001-06-13 21:01:27 +0000667
668 /* Fill remaining bytes with copies of the sign bit. */
669 {
670 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
671 for ( ; j < n; ++j, p += pincr)
672 *p = signbyte;
673 }
674
Tim Peters2a9b3672001-06-11 21:23:58 +0000675 return 0;
676
677Overflow:
678 PyErr_SetString(PyExc_OverflowError, "long too big to convert");
679 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000680
Tim Peters2a9b3672001-06-11 21:23:58 +0000681}
682
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000683double
684_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
685{
686/* NBITS_WANTED should be > the number of bits in a double's precision,
687 but small enough so that 2**NBITS_WANTED is within the normal double
688 range. nbitsneeded is set to 1 less than that because the most-significant
689 Python digit contains at least 1 significant bit, but we don't want to
690 bother counting them (catering to the worst case cheaply).
691
692 57 is one more than VAX-D double precision; I (Tim) don't know of a double
693 format with more precision than that; it's 1 larger so that we add in at
694 least one round bit to stand in for the ignored least-significant bits.
695*/
696#define NBITS_WANTED 57
697 PyLongObject *v;
698 double x;
699 const double multiplier = (double)(1L << SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000700 Py_ssize_t i;
701 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000702 int nbitsneeded;
703
704 if (vv == NULL || !PyLong_Check(vv)) {
705 PyErr_BadInternalCall();
706 return -1;
707 }
708 v = (PyLongObject *)vv;
709 i = v->ob_size;
710 sign = 1;
711 if (i < 0) {
712 sign = -1;
713 i = -(i);
714 }
715 else if (i == 0) {
716 *exponent = 0;
717 return 0.0;
718 }
719 --i;
720 x = (double)v->ob_digit[i];
721 nbitsneeded = NBITS_WANTED - 1;
722 /* Invariant: i Python digits remain unaccounted for. */
723 while (i > 0 && nbitsneeded > 0) {
724 --i;
725 x = x * multiplier + (double)v->ob_digit[i];
726 nbitsneeded -= SHIFT;
727 }
728 /* There are i digits we didn't shift in. Pretending they're all
729 zeroes, the true value is x * 2**(i*SHIFT). */
730 *exponent = i;
731 assert(x > 0.0);
732 return x * sign;
733#undef NBITS_WANTED
734}
735
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000736/* Get a C double from a long int object. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000737
738double
Tim Peters9f688bf2000-07-07 15:53:28 +0000739PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000740{
Thomas Wouters553489a2006-02-01 21:32:04 +0000741 int e = -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000742 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000743
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000744 if (vv == NULL || !PyLong_Check(vv)) {
745 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000746 return -1;
747 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000748 x = _PyLong_AsScaledDouble(vv, &e);
749 if (x == -1.0 && PyErr_Occurred())
750 return -1.0;
Thomas Wouters553489a2006-02-01 21:32:04 +0000751 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
752 set correctly after a successful _PyLong_AsScaledDouble() call */
753 assert(e >= 0);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000754 if (e > INT_MAX / SHIFT)
755 goto overflow;
756 errno = 0;
757 x = ldexp(x, e * SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +0000758 if (Py_OVERFLOWED(x))
Tim Peters9fffa3e2001-09-04 05:14:19 +0000759 goto overflow;
760 return x;
761
762overflow:
763 PyErr_SetString(PyExc_OverflowError,
764 "long int too large to convert to float");
765 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000766}
767
Guido van Rossum78694d91998-09-18 14:14:13 +0000768/* Create a new long (or int) object from a C pointer */
769
770PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000771PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000772{
Tim Peters70128a12001-06-16 08:48:40 +0000773#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +0000774 return PyInt_FromLong((long)p);
775#else
Guido van Rossum78694d91998-09-18 14:14:13 +0000776
Tim Peters70128a12001-06-16 08:48:40 +0000777#ifndef HAVE_LONG_LONG
778# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
779#endif
780#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000781# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000782#endif
783 /* optimize null pointers */
784 if (p == NULL)
785 return PyInt_FromLong(0);
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000786 return PyLong_FromLongLong((PY_LONG_LONG)p);
Tim Peters70128a12001-06-16 08:48:40 +0000787
788#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000789}
790
791/* Get a C pointer from a long object (or an int object in some cases) */
792
793void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000794PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000795{
796 /* This function will allow int or long objects. If vv is neither,
797 then the PyLong_AsLong*() functions will raise the exception:
798 PyExc_SystemError, "bad argument to internal function"
799 */
Tim Peters70128a12001-06-16 08:48:40 +0000800#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +0000801 long x;
802
Tim Peters70128a12001-06-16 08:48:40 +0000803 if (PyInt_Check(vv))
Guido van Rossum78694d91998-09-18 14:14:13 +0000804 x = PyInt_AS_LONG(vv);
805 else
806 x = PyLong_AsLong(vv);
807#else
Tim Peters70128a12001-06-16 08:48:40 +0000808
809#ifndef HAVE_LONG_LONG
810# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
811#endif
812#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000813# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000814#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000815 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000816
Tim Peters70128a12001-06-16 08:48:40 +0000817 if (PyInt_Check(vv))
Guido van Rossum78694d91998-09-18 14:14:13 +0000818 x = PyInt_AS_LONG(vv);
819 else
820 x = PyLong_AsLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000821
822#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000823
824 if (x == -1 && PyErr_Occurred())
825 return NULL;
826 return (void *)x;
827}
828
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000829#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000830
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000831/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000832 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000833 */
834
Tim Peterscf37dfc2001-06-14 18:42:50 +0000835#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +0000836
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000837/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000838
839PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000840PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000841{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000842 PY_LONG_LONG bytes = ival;
Tim Petersd1a7da62001-06-13 00:35:57 +0000843 int one = 1;
844 return _PyLong_FromByteArray(
845 (unsigned char *)&bytes,
846 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000847}
848
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000849/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +0000850
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000851PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000852PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000853{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000854 unsigned PY_LONG_LONG bytes = ival;
Tim Petersd1a7da62001-06-13 00:35:57 +0000855 int one = 1;
856 return _PyLong_FromByteArray(
857 (unsigned char *)&bytes,
858 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000859}
860
Martin v. Löwis18e16552006-02-15 17:27:45 +0000861/* Create a new long int object from a C Py_ssize_t. */
862
863PyObject *
864_PyLong_FromSsize_t(Py_ssize_t ival)
865{
866 Py_ssize_t bytes = ival;
867 int one = 1;
868 return _PyLong_FromByteArray(
869 (unsigned char *)&bytes,
870 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
871}
872
873/* Create a new long int object from a C size_t. */
874
875PyObject *
876_PyLong_FromSize_t(size_t ival)
877{
878 size_t bytes = ival;
879 int one = 1;
880 return _PyLong_FromByteArray(
881 (unsigned char *)&bytes,
882 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
883}
884
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000885/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000886 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000887
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000888PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000889PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000890{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000891 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +0000892 int one = 1;
893 int res;
894
Tim Petersd38b1c72001-09-30 05:09:37 +0000895 if (vv == NULL) {
896 PyErr_BadInternalCall();
897 return -1;
898 }
899 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +0000900 PyNumberMethods *nb;
901 PyObject *io;
Tim Petersd38b1c72001-09-30 05:09:37 +0000902 if (PyInt_Check(vv))
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000903 return (PY_LONG_LONG)PyInt_AsLong(vv);
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +0000904 if ((nb = vv->ob_type->tp_as_number) == NULL ||
905 nb->nb_int == NULL) {
906 PyErr_SetString(PyExc_TypeError, "an integer is required");
907 return -1;
908 }
909 io = (*nb->nb_int) (vv);
910 if (io == NULL)
911 return -1;
912 if (PyInt_Check(io)) {
913 bytes = PyInt_AsLong(io);
914 Py_DECREF(io);
915 return bytes;
916 }
917 if (PyLong_Check(io)) {
918 bytes = PyLong_AsLongLong(io);
919 Py_DECREF(io);
920 return bytes;
921 }
922 Py_DECREF(io);
923 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000924 return -1;
925 }
926
Tim Petersd1a7da62001-06-13 00:35:57 +0000927 res = _PyLong_AsByteArray(
928 (PyLongObject *)vv, (unsigned char *)&bytes,
929 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000930
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000931 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000932 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000933 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000934 else
935 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000936}
937
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000938/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000939 Return -1 and set an error if overflow occurs. */
940
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000941unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000942PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000943{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000944 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +0000945 int one = 1;
946 int res;
947
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000948 if (vv == NULL || !PyLong_Check(vv)) {
949 PyErr_BadInternalCall();
Tim Petersd1a7da62001-06-13 00:35:57 +0000950 return -1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000951 }
952
Tim Petersd1a7da62001-06-13 00:35:57 +0000953 res = _PyLong_AsByteArray(
954 (PyLongObject *)vv, (unsigned char *)&bytes,
955 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000956
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000957 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000958 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000959 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000960 else
961 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000962}
Tim Petersd1a7da62001-06-13 00:35:57 +0000963
Thomas Hellera4ea6032003-04-17 18:55:45 +0000964/* Get a C unsigned long int from a long int object, ignoring the high bits.
965 Returns -1 and sets an error condition if an error occurs. */
966
967unsigned PY_LONG_LONG
968PyLong_AsUnsignedLongLongMask(PyObject *vv)
969{
970 register PyLongObject *v;
971 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000972 Py_ssize_t i;
973 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000974
975 if (vv == NULL || !PyLong_Check(vv)) {
976 PyErr_BadInternalCall();
977 return (unsigned long) -1;
978 }
979 v = (PyLongObject *)vv;
980 i = v->ob_size;
981 sign = 1;
982 x = 0;
983 if (i < 0) {
984 sign = -1;
985 i = -i;
986 }
987 while (--i >= 0) {
988 x = (x << SHIFT) + v->ob_digit[i];
989 }
990 return x * sign;
991}
Tim Petersd1a7da62001-06-13 00:35:57 +0000992#undef IS_LITTLE_ENDIAN
993
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000994#endif /* HAVE_LONG_LONG */
995
Neil Schemenauerba872e22001-01-04 01:46:03 +0000996
997static int
998convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) {
Tim Peters5af4e6c2002-08-12 02:31:19 +0000999 if (PyLong_Check(v)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001000 *a = (PyLongObject *) v;
1001 Py_INCREF(v);
1002 }
1003 else if (PyInt_Check(v)) {
1004 *a = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(v));
1005 }
1006 else {
1007 return 0;
1008 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001009 if (PyLong_Check(w)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001010 *b = (PyLongObject *) w;
1011 Py_INCREF(w);
1012 }
1013 else if (PyInt_Check(w)) {
1014 *b = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(w));
1015 }
1016 else {
1017 Py_DECREF(*a);
1018 return 0;
1019 }
1020 return 1;
1021}
1022
1023#define CONVERT_BINOP(v, w, a, b) \
1024 if (!convert_binop(v, w, a, b)) { \
1025 Py_INCREF(Py_NotImplemented); \
1026 return Py_NotImplemented; \
1027 }
1028
Tim Peters877a2122002-08-12 05:09:36 +00001029/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1030 * is modified in place, by adding y to it. Carries are propagated as far as
1031 * x[m-1], and the remaining carry (0 or 1) is returned.
1032 */
1033static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001034v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001035{
1036 int i;
1037 digit carry = 0;
1038
1039 assert(m >= n);
1040 for (i = 0; i < n; ++i) {
1041 carry += x[i] + y[i];
1042 x[i] = carry & MASK;
1043 carry >>= SHIFT;
1044 assert((carry & 1) == carry);
1045 }
1046 for (; carry && i < m; ++i) {
1047 carry += x[i];
1048 x[i] = carry & MASK;
1049 carry >>= SHIFT;
1050 assert((carry & 1) == carry);
1051 }
1052 return carry;
1053}
1054
1055/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1056 * is modified in place, by subtracting y from it. Borrows are propagated as
1057 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1058 */
1059static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001060v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001061{
1062 int i;
1063 digit borrow = 0;
1064
1065 assert(m >= n);
1066 for (i = 0; i < n; ++i) {
1067 borrow = x[i] - y[i] - borrow;
1068 x[i] = borrow & MASK;
1069 borrow >>= SHIFT;
1070 borrow &= 1; /* keep only 1 sign bit */
1071 }
1072 for (; borrow && i < m; ++i) {
1073 borrow = x[i] - borrow;
1074 x[i] = borrow & MASK;
1075 borrow >>= SHIFT;
1076 borrow &= 1;
1077 }
1078 return borrow;
1079}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001080
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001081/* Multiply by a single digit, ignoring the sign. */
1082
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001083static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001084mul1(PyLongObject *a, wdigit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001085{
1086 return muladd1(a, n, (digit)0);
1087}
1088
1089/* Multiply by a single digit and add a single digit, ignoring the sign. */
1090
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001091static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001092muladd1(PyLongObject *a, wdigit n, wdigit extra)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001093{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001094 Py_ssize_t size_a = ABS(a->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001095 PyLongObject *z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001096 twodigits carry = extra;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001097 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001098
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001099 if (z == NULL)
1100 return NULL;
1101 for (i = 0; i < size_a; ++i) {
1102 carry += (twodigits)a->ob_digit[i] * n;
Guido van Rossum2095d241997-04-09 19:41:24 +00001103 z->ob_digit[i] = (digit) (carry & MASK);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001104 carry >>= SHIFT;
1105 }
Guido van Rossum2095d241997-04-09 19:41:24 +00001106 z->ob_digit[i] = (digit) carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001107 return long_normalize(z);
1108}
1109
Tim Peters212e6142001-07-14 12:23:19 +00001110/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1111 in pout, and returning the remainder. pin and pout point at the LSD.
1112 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
1113 long_format, but that should be done with great care since longs are
1114 immutable. */
1115
1116static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001117inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001118{
1119 twodigits rem = 0;
1120
1121 assert(n > 0 && n <= MASK);
1122 pin += size;
1123 pout += size;
1124 while (--size >= 0) {
1125 digit hi;
1126 rem = (rem << SHIFT) + *--pin;
1127 *--pout = hi = (digit)(rem / n);
1128 rem -= hi * n;
1129 }
1130 return (digit)rem;
1131}
1132
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001133/* Divide a long integer by a digit, returning both the quotient
1134 (as function result) and the remainder (through *prem).
1135 The sign of a is ignored; n should not be zero. */
1136
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001137static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001138divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001139{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001140 const Py_ssize_t size = ABS(a->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001141 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001142
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001143 assert(n > 0 && n <= MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001144 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001145 if (z == NULL)
1146 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001147 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001148 return long_normalize(z);
1149}
1150
1151/* Convert a long int object to a string, using a given conversion base.
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001152 Return a string object.
Fred Drake121ee271999-12-23 15:41:28 +00001153 If base is 8 or 16, add the proper prefix '0' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001154
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001155static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001156long_format(PyObject *aa, int base, int addL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001157{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001158 register PyLongObject *a = (PyLongObject *)aa;
1159 PyStringObject *str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001160 Py_ssize_t i;
1161 const Py_ssize_t size_a = ABS(a->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001162 char *p;
1163 int bits;
1164 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001165
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001166 if (a == NULL || !PyLong_Check(a)) {
1167 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001168 return NULL;
1169 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001170 assert(base >= 2 && base <= 36);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001171
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001172 /* Compute a rough upper bound for the length of the string */
1173 i = base;
1174 bits = 0;
1175 while (i > 1) {
1176 ++bits;
1177 i >>= 1;
1178 }
Fred Drake121ee271999-12-23 15:41:28 +00001179 i = 5 + (addL ? 1 : 0) + (size_a*SHIFT + bits-1) / bits;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001180 str = (PyStringObject *) PyString_FromStringAndSize((char *)0, i);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001181 if (str == NULL)
1182 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001183 p = PyString_AS_STRING(str) + i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001184 *p = '\0';
Fred Drake121ee271999-12-23 15:41:28 +00001185 if (addL)
1186 *--p = 'L';
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001187 if (a->ob_size < 0)
1188 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001189
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001190 if (a->ob_size == 0) {
1191 *--p = '0';
1192 }
1193 else if ((base & (base - 1)) == 0) {
1194 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001195 twodigits accum = 0;
1196 int accumbits = 0; /* # of bits in accum */
1197 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001198 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001199 while ((i >>= 1) > 1)
1200 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001201
1202 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001203 accum |= (twodigits)a->ob_digit[i] << accumbits;
Tim Peters586b2e32001-07-15 09:11:14 +00001204 accumbits += SHIFT;
1205 assert(accumbits >= basebits);
1206 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001207 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001208 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001209 assert(p > PyString_AS_STRING(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001210 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001211 accumbits -= basebits;
1212 accum >>= basebits;
1213 } while (i < size_a-1 ? accumbits >= basebits :
1214 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001215 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001216 }
1217 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001218 /* Not 0, and base not a power of 2. Divide repeatedly by
1219 base, but for speed use the highest power of base that
1220 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001221 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001222 digit *pin = a->ob_digit;
1223 PyLongObject *scratch;
1224 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001225 digit powbase = base; /* powbase == base ** power */
1226 int power = 1;
1227 for (;;) {
1228 unsigned long newpow = powbase * (unsigned long)base;
1229 if (newpow >> SHIFT) /* doesn't fit in a digit */
1230 break;
1231 powbase = (digit)newpow;
1232 ++power;
1233 }
Tim Peters212e6142001-07-14 12:23:19 +00001234
1235 /* Get a scratch area for repeated division. */
1236 scratch = _PyLong_New(size);
1237 if (scratch == NULL) {
1238 Py_DECREF(str);
1239 return NULL;
1240 }
1241
1242 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001243 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001244 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001245 digit rem = inplace_divrem1(scratch->ob_digit,
1246 pin, size, powbase);
1247 pin = scratch->ob_digit; /* no need to use a again */
1248 if (pin[size - 1] == 0)
1249 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001250 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001251 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001252 Py_DECREF(str);
1253 return NULL;
1254 })
Tim Peters212e6142001-07-14 12:23:19 +00001255
1256 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001257 assert(ntostore > 0);
1258 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001259 digit nextrem = (digit)(rem / base);
1260 char c = (char)(rem - nextrem * base);
1261 assert(p > PyString_AS_STRING(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001262 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001263 *--p = c;
1264 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001265 --ntostore;
1266 /* Termination is a bit delicate: must not
1267 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001268 remaining quotient and rem are both 0. */
1269 } while (ntostore && (size || rem));
1270 } while (size != 0);
1271 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001272 }
1273
Guido van Rossum2c475421992-08-14 15:13:07 +00001274 if (base == 8) {
1275 if (size_a != 0)
1276 *--p = '0';
1277 }
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001278 else if (base == 16) {
1279 *--p = 'x';
1280 *--p = '0';
1281 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001282 else if (base != 10) {
1283 *--p = '#';
1284 *--p = '0' + base%10;
1285 if (base > 10)
1286 *--p = '0' + base/10;
1287 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001288 if (sign)
1289 *--p = sign;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001290 if (p != PyString_AS_STRING(str)) {
1291 char *q = PyString_AS_STRING(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001292 assert(p > q);
1293 do {
1294 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001295 q--;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001296 _PyString_Resize((PyObject **)&str,
1297 (int) (q - PyString_AS_STRING(str)));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001298 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001299 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001300}
1301
Tim Petersbf2674b2003-02-02 07:51:32 +00001302/* *str points to the first digit in a string of base base digits. base
1303 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1304 * non-digit (which may be *str!). A normalized long is returned.
1305 * The point to this routine is that it takes time linear in the number of
1306 * string characters.
1307 */
1308static PyLongObject *
1309long_from_binary_base(char **str, int base)
1310{
1311 char *p = *str;
1312 char *start = p;
1313 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001314 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001315 PyLongObject *z;
1316 twodigits accum;
1317 int bits_in_accum;
1318 digit *pdigit;
1319
1320 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1321 n = base;
1322 for (bits_per_char = -1; n; ++bits_per_char)
1323 n >>= 1;
1324 /* n <- total # of bits needed, while setting p to end-of-string */
1325 n = 0;
1326 for (;;) {
1327 int k = -1;
1328 char ch = *p;
1329
1330 if (ch <= '9')
1331 k = ch - '0';
1332 else if (ch >= 'a')
1333 k = ch - 'a' + 10;
1334 else if (ch >= 'A')
1335 k = ch - 'A' + 10;
1336 if (k < 0 || k >= base)
1337 break;
Tim Petersbf2674b2003-02-02 07:51:32 +00001338 ++p;
1339 }
1340 *str = p;
Tim Peters1a3b19a2003-02-02 17:33:53 +00001341 n = (p - start) * bits_per_char;
1342 if (n / bits_per_char != p - start) {
1343 PyErr_SetString(PyExc_ValueError,
1344 "long string too large to convert");
1345 return NULL;
1346 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001347 /* n <- # of Python digits needed, = ceiling(n/SHIFT). */
1348 n = (n + SHIFT - 1) / SHIFT;
1349 z = _PyLong_New(n);
1350 if (z == NULL)
1351 return NULL;
1352 /* Read string from right, and fill in long from left; i.e.,
1353 * from least to most significant in both.
1354 */
1355 accum = 0;
1356 bits_in_accum = 0;
1357 pdigit = z->ob_digit;
1358 while (--p >= start) {
Tim Petersc7bc0b92003-05-05 20:39:43 +00001359 int k;
1360 char ch = *p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001361
1362 if (ch <= '9')
1363 k = ch - '0';
1364 else if (ch >= 'a')
1365 k = ch - 'a' + 10;
1366 else {
1367 assert(ch >= 'A');
1368 k = ch - 'A' + 10;
1369 }
Tim Petersc7bc0b92003-05-05 20:39:43 +00001370 assert(k >= 0 && k < base);
1371 accum |= (twodigits)(k << bits_in_accum);
Tim Petersbf2674b2003-02-02 07:51:32 +00001372 bits_in_accum += bits_per_char;
1373 if (bits_in_accum >= SHIFT) {
1374 *pdigit++ = (digit)(accum & MASK);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001375 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001376 accum >>= SHIFT;
1377 bits_in_accum -= SHIFT;
1378 assert(bits_in_accum < SHIFT);
1379 }
1380 }
1381 if (bits_in_accum) {
1382 assert(bits_in_accum <= SHIFT);
1383 *pdigit++ = (digit)accum;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001384 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001385 }
1386 while (pdigit - z->ob_digit < n)
1387 *pdigit++ = 0;
1388 return long_normalize(z);
1389}
1390
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001391PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001392PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001393{
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001394 int sign = 1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001395 char *start, *orig_str = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001396 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001397
Guido van Rossum472c04f1996-12-05 21:57:21 +00001398 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001399 PyErr_SetString(PyExc_ValueError,
Fred Drake661ea262000-10-24 19:57:45 +00001400 "long() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001401 return NULL;
1402 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001403 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001404 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001405 if (*str == '+')
1406 ++str;
1407 else if (*str == '-') {
1408 ++str;
1409 sign = -1;
1410 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001411 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001412 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001413 if (base == 0) {
1414 if (str[0] != '0')
1415 base = 10;
1416 else if (str[1] == 'x' || str[1] == 'X')
1417 base = 16;
1418 else
1419 base = 8;
1420 }
1421 if (base == 16 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
1422 str += 2;
Guido van Rossume6762971998-06-22 03:54:46 +00001423 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001424 if ((base & (base - 1)) == 0)
1425 z = long_from_binary_base(&str, base);
1426 else {
1427 z = _PyLong_New(0);
1428 for ( ; z != NULL; ++str) {
1429 int k = -1;
1430 PyLongObject *temp;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001431
Tim Petersbf2674b2003-02-02 07:51:32 +00001432 if (*str <= '9')
1433 k = *str - '0';
1434 else if (*str >= 'a')
1435 k = *str - 'a' + 10;
1436 else if (*str >= 'A')
1437 k = *str - 'A' + 10;
1438 if (k < 0 || k >= base)
1439 break;
1440 temp = muladd1(z, (digit)base, (digit)k);
1441 Py_DECREF(z);
1442 z = temp;
1443 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001444 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001445 if (z == NULL)
1446 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001447 if (str == start)
1448 goto onError;
Guido van Rossumc6913e71991-11-19 20:26:46 +00001449 if (sign < 0 && z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001450 z->ob_size = -(z->ob_size);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001451 if (*str == 'L' || *str == 'l')
1452 str++;
1453 while (*str && isspace(Py_CHARMASK(*str)))
1454 str++;
1455 if (*str != '\0')
1456 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001457 if (pend)
1458 *pend = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001459 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001460
1461 onError:
Tim Peters5af4e6c2002-08-12 02:31:19 +00001462 PyErr_Format(PyExc_ValueError,
Guido van Rossum9e896b32000-04-05 20:11:21 +00001463 "invalid literal for long(): %.200s", orig_str);
1464 Py_XDECREF(z);
1465 return NULL;
1466}
1467
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001468#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +00001469PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001470PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001471{
Walter Dörwald07e14762002-11-06 16:15:14 +00001472 PyObject *result;
1473 char *buffer = PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001474
Walter Dörwald07e14762002-11-06 16:15:14 +00001475 if (buffer == NULL)
1476 return NULL;
1477
1478 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1479 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001480 return NULL;
1481 }
Walter Dörwald07e14762002-11-06 16:15:14 +00001482 result = PyLong_FromString(buffer, NULL, base);
1483 PyMem_FREE(buffer);
1484 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001485}
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001486#endif
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001487
Tim Peters9f688bf2000-07-07 15:53:28 +00001488/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001489static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00001490 (PyLongObject *, PyLongObject *, PyLongObject **);
1491static PyObject *long_pos(PyLongObject *);
1492static int long_divrem(PyLongObject *, PyLongObject *,
1493 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001494
1495/* Long division with remainder, top-level routine */
1496
Guido van Rossume32e0141992-01-19 16:31:05 +00001497static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001498long_divrem(PyLongObject *a, PyLongObject *b,
1499 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001500{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001501 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001502 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001503
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001504 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001505 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +00001506 "long division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00001507 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001508 }
1509 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00001510 (size_a == size_b &&
1511 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001512 /* |a| < |b|. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001513 *pdiv = _PyLong_New(0);
1514 Py_INCREF(a);
1515 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00001516 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001517 }
1518 if (size_b == 1) {
1519 digit rem = 0;
1520 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001521 if (z == NULL)
1522 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001523 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001524 }
Guido van Rossume32e0141992-01-19 16:31:05 +00001525 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001526 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001527 if (z == NULL)
1528 return -1;
1529 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001530 /* Set the signs.
1531 The quotient z has the sign of a*b;
1532 the remainder r has the sign of a,
1533 so a = b*z + r. */
Guido van Rossume32e0141992-01-19 16:31:05 +00001534 if ((a->ob_size < 0) != (b->ob_size < 0))
1535 z->ob_size = -(z->ob_size);
1536 if (a->ob_size < 0 && (*prem)->ob_size != 0)
1537 (*prem)->ob_size = -((*prem)->ob_size);
1538 *pdiv = z;
1539 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001540}
1541
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001542/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001543
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001544static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001545x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001546{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001547 Py_ssize_t size_v = ABS(v1->ob_size), size_w = ABS(w1->ob_size);
Guido van Rossum2095d241997-04-09 19:41:24 +00001548 digit d = (digit) ((twodigits)BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001549 PyLongObject *v = mul1(v1, d);
1550 PyLongObject *w = mul1(w1, d);
1551 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001552 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001553
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001554 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001555 Py_XDECREF(v);
1556 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001557 return NULL;
1558 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001559
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001560 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001561 assert(v->ob_refcnt == 1); /* Since v will be used as accumulator! */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001562 assert(size_w == ABS(w->ob_size)); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00001563
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001564 size_v = ABS(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001565 a = _PyLong_New(size_v - size_w + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001566
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001567 for (j = size_v, k = a->ob_size-1; a != NULL && k >= 0; --j, --k) {
1568 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
1569 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001570 stwodigits carry = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001571 int i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001572
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001573 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001574 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001575 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001576 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001577 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001578 if (vj == w->ob_digit[size_w-1])
1579 q = MASK;
1580 else
1581 q = (((twodigits)vj << SHIFT) + v->ob_digit[j-1]) /
1582 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00001583
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001584 while (w->ob_digit[size_w-2]*q >
1585 ((
1586 ((twodigits)vj << SHIFT)
1587 + v->ob_digit[j-1]
1588 - q*w->ob_digit[size_w-1]
1589 ) << SHIFT)
1590 + v->ob_digit[j-2])
1591 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001592
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001593 for (i = 0; i < size_w && i+k < size_v; ++i) {
1594 twodigits z = w->ob_digit[i] * q;
Guido van Rossum2095d241997-04-09 19:41:24 +00001595 digit zz = (digit) (z >> SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001596 carry += v->ob_digit[i+k] - z
1597 + ((twodigits)zz << SHIFT);
Jeremy Hyltonfc61f9a2003-05-01 21:31:53 +00001598 v->ob_digit[i+k] = (digit)(carry & MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00001599 carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
1600 carry, SHIFT);
1601 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001602 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001603
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001604 if (i+k < size_v) {
1605 carry += v->ob_digit[i+k];
1606 v->ob_digit[i+k] = 0;
1607 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001608
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001609 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00001610 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001611 else {
1612 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00001613 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001614 carry = 0;
1615 for (i = 0; i < size_w && i+k < size_v; ++i) {
1616 carry += v->ob_digit[i+k] + w->ob_digit[i];
Jeremy Hyltonfc61f9a2003-05-01 21:31:53 +00001617 v->ob_digit[i+k] = (digit)(carry & MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00001618 carry = Py_ARITHMETIC_RIGHT_SHIFT(
1619 BASE_TWODIGITS_TYPE,
1620 carry, SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001621 }
1622 }
1623 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00001624
Guido van Rossumc206c761995-01-10 15:23:19 +00001625 if (a == NULL)
1626 *prem = NULL;
1627 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00001628 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00001629 *prem = divrem1(v, d, &d);
1630 /* d receives the (unused) remainder */
1631 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001632 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00001633 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00001634 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001635 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001636 Py_DECREF(v);
1637 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001638 return a;
1639}
1640
1641/* Methods */
1642
1643static void
Tim Peters9f688bf2000-07-07 15:53:28 +00001644long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001645{
Guido van Rossum9475a232001-10-05 20:51:39 +00001646 v->ob_type->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001647}
1648
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001649static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001650long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001651{
Fred Drake121ee271999-12-23 15:41:28 +00001652 return long_format(v, 10, 1);
1653}
1654
1655static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001656long_str(PyObject *v)
Fred Drake121ee271999-12-23 15:41:28 +00001657{
1658 return long_format(v, 10, 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001659}
1660
1661static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001662long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001663{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001664 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001665
Guido van Rossumc6913e71991-11-19 20:26:46 +00001666 if (a->ob_size != b->ob_size) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001667 if (ABS(a->ob_size) == 0 && ABS(b->ob_size) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00001668 sign = 0;
1669 else
1670 sign = a->ob_size - b->ob_size;
1671 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001672 else {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001673 Py_ssize_t i = ABS(a->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001674 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
1675 ;
1676 if (i < 0)
1677 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00001678 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001679 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00001680 if (a->ob_size < 0)
1681 sign = -sign;
1682 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001683 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001684 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001685}
1686
Guido van Rossum9bfef441993-03-29 10:43:31 +00001687static long
Tim Peters9f688bf2000-07-07 15:53:28 +00001688long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001689{
1690 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001691 Py_ssize_t i;
1692 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001693
1694 /* This is designed so that Python ints and longs with the
1695 same value hash to the same value, otherwise comparisons
1696 of mapping keys will turn out weird */
1697 i = v->ob_size;
1698 sign = 1;
1699 x = 0;
1700 if (i < 0) {
1701 sign = -1;
1702 i = -(i);
1703 }
Neal Norwitzd5a65a72003-02-23 23:11:41 +00001704#define LONG_BIT_SHIFT (8*sizeof(long) - SHIFT)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001705 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00001706 /* Force a native long #-bits (32 or 64) circular shift */
1707 x = ((x << SHIFT) & ~MASK) | ((x >> LONG_BIT_SHIFT) & MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001708 x += v->ob_digit[i];
1709 }
Neal Norwitzd5a65a72003-02-23 23:11:41 +00001710#undef LONG_BIT_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00001711 x = x * sign;
1712 if (x == -1)
1713 x = -2;
1714 return x;
1715}
1716
1717
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001718/* Add the absolute values of two long integers. */
1719
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001720static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001721x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001722{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001723 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001724 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001725 int i;
1726 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00001727
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001728 /* Ensure a is the larger of the two: */
1729 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001730 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00001731 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001732 size_a = size_b;
1733 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001734 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001735 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001736 if (z == NULL)
1737 return NULL;
1738 for (i = 0; i < size_b; ++i) {
1739 carry += a->ob_digit[i] + b->ob_digit[i];
1740 z->ob_digit[i] = carry & MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001741 carry >>= SHIFT;
1742 }
1743 for (; i < size_a; ++i) {
1744 carry += a->ob_digit[i];
1745 z->ob_digit[i] = carry & MASK;
1746 carry >>= SHIFT;
1747 }
1748 z->ob_digit[i] = carry;
1749 return long_normalize(z);
1750}
1751
1752/* Subtract the absolute values of two integers. */
1753
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001754static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001755x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001756{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001757 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001758 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001759 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001760 int sign = 1;
1761 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00001762
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001763 /* Ensure a is the larger of the two: */
1764 if (size_a < size_b) {
1765 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001766 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00001767 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001768 size_a = size_b;
1769 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001770 }
1771 else if (size_a == size_b) {
1772 /* Find highest digit where a and b differ: */
1773 i = size_a;
1774 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
1775 ;
1776 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001777 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001778 if (a->ob_digit[i] < b->ob_digit[i]) {
1779 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001780 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001781 }
1782 size_a = size_b = i+1;
1783 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001784 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001785 if (z == NULL)
1786 return NULL;
1787 for (i = 0; i < size_b; ++i) {
1788 /* The following assumes unsigned arithmetic
1789 works module 2**N for some N>SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001790 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001791 z->ob_digit[i] = borrow & MASK;
1792 borrow >>= SHIFT;
1793 borrow &= 1; /* Keep only one sign bit */
1794 }
1795 for (; i < size_a; ++i) {
1796 borrow = a->ob_digit[i] - borrow;
1797 z->ob_digit[i] = borrow & MASK;
1798 borrow >>= SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00001799 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001800 }
1801 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00001802 if (sign < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001803 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001804 return long_normalize(z);
1805}
1806
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001807static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00001808long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001809{
Neil Schemenauerba872e22001-01-04 01:46:03 +00001810 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00001811
Neil Schemenauerba872e22001-01-04 01:46:03 +00001812 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
1813
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001814 if (a->ob_size < 0) {
1815 if (b->ob_size < 0) {
1816 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00001817 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001818 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001819 }
1820 else
1821 z = x_sub(b, a);
1822 }
1823 else {
1824 if (b->ob_size < 0)
1825 z = x_sub(a, b);
1826 else
1827 z = x_add(a, b);
1828 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00001829 Py_DECREF(a);
1830 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001831 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001832}
1833
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001834static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00001835long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001836{
Neil Schemenauerba872e22001-01-04 01:46:03 +00001837 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001838
Neil Schemenauerba872e22001-01-04 01:46:03 +00001839 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
1840
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001841 if (a->ob_size < 0) {
1842 if (b->ob_size < 0)
1843 z = x_sub(a, b);
1844 else
1845 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00001846 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001847 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001848 }
1849 else {
1850 if (b->ob_size < 0)
1851 z = x_add(a, b);
1852 else
1853 z = x_sub(a, b);
1854 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00001855 Py_DECREF(a);
1856 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001857 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001858}
1859
Tim Peters5af4e6c2002-08-12 02:31:19 +00001860/* Grade school multiplication, ignoring the signs.
1861 * Returns the absolute value of the product, or NULL if error.
1862 */
1863static PyLongObject *
1864x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001865{
Tim Peters5af4e6c2002-08-12 02:31:19 +00001866 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001867 Py_ssize_t size_a = ABS(a->ob_size);
1868 Py_ssize_t size_b = ABS(b->ob_size);
1869 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00001870
Tim Peters5af4e6c2002-08-12 02:31:19 +00001871 z = _PyLong_New(size_a + size_b);
1872 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001873 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001874
1875 memset(z->ob_digit, 0, z->ob_size * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00001876 if (a == b) {
1877 /* Efficient squaring per HAC, Algorithm 14.16:
1878 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
1879 * Gives slightly less than a 2x speedup when a == b,
1880 * via exploiting that each entry in the multiplication
1881 * pyramid appears twice (except for the size_a squares).
1882 */
1883 for (i = 0; i < size_a; ++i) {
1884 twodigits carry;
1885 twodigits f = a->ob_digit[i];
1886 digit *pz = z->ob_digit + (i << 1);
1887 digit *pa = a->ob_digit + i + 1;
1888 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001889
Tim Peters0973b992004-08-29 22:16:50 +00001890 SIGCHECK({
1891 Py_DECREF(z);
1892 return NULL;
1893 })
1894
1895 carry = *pz + f * f;
1896 *pz++ = (digit)(carry & MASK);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001897 carry >>= SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00001898 assert(carry <= MASK);
1899
1900 /* Now f is added in twice in each column of the
1901 * pyramid it appears. Same as adding f<<1 once.
1902 */
1903 f <<= 1;
1904 while (pa < paend) {
1905 carry += *pz + *pa++ * f;
1906 *pz++ = (digit)(carry & MASK);
1907 carry >>= SHIFT;
1908 assert(carry <= (MASK << 1));
1909 }
1910 if (carry) {
1911 carry += *pz;
1912 *pz++ = (digit)(carry & MASK);
1913 carry >>= SHIFT;
1914 }
1915 if (carry)
1916 *pz += (digit)(carry & MASK);
1917 assert((carry >> SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001918 }
Tim Peters0973b992004-08-29 22:16:50 +00001919 }
1920 else { /* a is not the same as b -- gradeschool long mult */
1921 for (i = 0; i < size_a; ++i) {
1922 twodigits carry = 0;
1923 twodigits f = a->ob_digit[i];
1924 digit *pz = z->ob_digit + i;
1925 digit *pb = b->ob_digit;
1926 digit *pbend = b->ob_digit + size_b;
1927
1928 SIGCHECK({
1929 Py_DECREF(z);
1930 return NULL;
1931 })
1932
1933 while (pb < pbend) {
1934 carry += *pz + *pb++ * f;
1935 *pz++ = (digit)(carry & MASK);
1936 carry >>= SHIFT;
1937 assert(carry <= MASK);
1938 }
1939 if (carry)
1940 *pz += (digit)(carry & MASK);
1941 assert((carry >> SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001942 }
1943 }
Tim Peters44121a62002-08-12 06:17:58 +00001944 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001945}
1946
1947/* A helper for Karatsuba multiplication (k_mul).
1948 Takes a long "n" and an integer "size" representing the place to
1949 split, and sets low and high such that abs(n) == (high << size) + low,
1950 viewing the shift as being by digits. The sign bit is ignored, and
1951 the return values are >= 0.
1952 Returns 0 on success, -1 on failure.
1953*/
1954static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001955kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00001956{
1957 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001958 Py_ssize_t size_lo, size_hi;
1959 const Py_ssize_t size_n = ABS(n->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001960
1961 size_lo = MIN(size_n, size);
1962 size_hi = size_n - size_lo;
1963
1964 if ((hi = _PyLong_New(size_hi)) == NULL)
1965 return -1;
1966 if ((lo = _PyLong_New(size_lo)) == NULL) {
1967 Py_DECREF(hi);
1968 return -1;
1969 }
1970
1971 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
1972 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
1973
1974 *high = long_normalize(hi);
1975 *low = long_normalize(lo);
1976 return 0;
1977}
1978
Tim Peters60004642002-08-12 22:01:34 +00001979static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
1980
Tim Peters5af4e6c2002-08-12 02:31:19 +00001981/* Karatsuba multiplication. Ignores the input signs, and returns the
1982 * absolute value of the product (or NULL if error).
1983 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
1984 */
1985static PyLongObject *
1986k_mul(PyLongObject *a, PyLongObject *b)
1987{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001988 Py_ssize_t asize = ABS(a->ob_size);
1989 Py_ssize_t bsize = ABS(b->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001990 PyLongObject *ah = NULL;
1991 PyLongObject *al = NULL;
1992 PyLongObject *bh = NULL;
1993 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001994 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00001995 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001996 Py_ssize_t shift; /* the number of digits we split off */
1997 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00001998
Tim Peters5af4e6c2002-08-12 02:31:19 +00001999 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2000 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2001 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002002 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002003 * By picking X to be a power of 2, "*X" is just shifting, and it's
2004 * been reduced to 3 multiplies on numbers half the size.
2005 */
2006
Tim Petersfc07e562002-08-12 02:54:10 +00002007 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002008 * is largest.
2009 */
Tim Peters738eda72002-08-12 15:08:20 +00002010 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002011 t1 = a;
2012 a = b;
2013 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002014
2015 i = asize;
2016 asize = bsize;
2017 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002018 }
2019
2020 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002021 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2022 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002023 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002024 return _PyLong_New(0);
2025 else
2026 return x_mul(a, b);
2027 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002028
Tim Peters60004642002-08-12 22:01:34 +00002029 /* If a is small compared to b, splitting on b gives a degenerate
2030 * case with ah==0, and Karatsuba may be (even much) less efficient
2031 * than "grade school" then. However, we can still win, by viewing
2032 * b as a string of "big digits", each of width a->ob_size. That
2033 * leads to a sequence of balanced calls to k_mul.
2034 */
2035 if (2 * asize <= bsize)
2036 return k_lopsided_mul(a, b);
2037
Tim Petersd6974a52002-08-13 20:37:51 +00002038 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002039 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002040 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Tim Petersd6974a52002-08-13 20:37:51 +00002041 assert(ah->ob_size > 0); /* the split isn't degenerate */
2042
Tim Peters0973b992004-08-29 22:16:50 +00002043 if (a == b) {
2044 bh = ah;
2045 bl = al;
2046 Py_INCREF(bh);
2047 Py_INCREF(bl);
2048 }
2049 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002050
Tim Petersd64c1de2002-08-12 17:36:03 +00002051 /* The plan:
2052 * 1. Allocate result space (asize + bsize digits: that's always
2053 * enough).
2054 * 2. Compute ah*bh, and copy into result at 2*shift.
2055 * 3. Compute al*bl, and copy into result at 0. Note that this
2056 * can't overlap with #2.
2057 * 4. Subtract al*bl from the result, starting at shift. This may
2058 * underflow (borrow out of the high digit), but we don't care:
2059 * we're effectively doing unsigned arithmetic mod
2060 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2061 * borrows and carries out of the high digit can be ignored.
2062 * 5. Subtract ah*bh from the result, starting at shift.
2063 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2064 * at shift.
2065 */
2066
2067 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002068 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002069 if (ret == NULL) goto fail;
2070#ifdef Py_DEBUG
2071 /* Fill with trash, to catch reference to uninitialized digits. */
2072 memset(ret->ob_digit, 0xDF, ret->ob_size * sizeof(digit));
2073#endif
Tim Peters44121a62002-08-12 06:17:58 +00002074
Tim Petersd64c1de2002-08-12 17:36:03 +00002075 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002076 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
2077 assert(t1->ob_size >= 0);
2078 assert(2*shift + t1->ob_size <= ret->ob_size);
2079 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
2080 t1->ob_size * sizeof(digit));
2081
2082 /* Zero-out the digits higher than the ah*bh copy. */
2083 i = ret->ob_size - 2*shift - t1->ob_size;
Tim Peters44121a62002-08-12 06:17:58 +00002084 if (i)
Tim Peters738eda72002-08-12 15:08:20 +00002085 memset(ret->ob_digit + 2*shift + t1->ob_size, 0,
Tim Peters44121a62002-08-12 06:17:58 +00002086 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002087
Tim Petersd64c1de2002-08-12 17:36:03 +00002088 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002089 if ((t2 = k_mul(al, bl)) == NULL) {
2090 Py_DECREF(t1);
2091 goto fail;
2092 }
2093 assert(t2->ob_size >= 0);
2094 assert(t2->ob_size <= 2*shift); /* no overlap with high digits */
2095 memcpy(ret->ob_digit, t2->ob_digit, t2->ob_size * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002096
2097 /* Zero out remaining digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002098 i = 2*shift - t2->ob_size; /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002099 if (i)
Tim Peters738eda72002-08-12 15:08:20 +00002100 memset(ret->ob_digit + t2->ob_size, 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002101
Tim Petersd64c1de2002-08-12 17:36:03 +00002102 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2103 * because it's fresher in cache.
2104 */
Tim Peters738eda72002-08-12 15:08:20 +00002105 i = ret->ob_size - shift; /* # digits after shift */
Tim Petersd64c1de2002-08-12 17:36:03 +00002106 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, t2->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002107 Py_DECREF(t2);
2108
Tim Petersd64c1de2002-08-12 17:36:03 +00002109 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, t1->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002110 Py_DECREF(t1);
2111
Tim Petersd64c1de2002-08-12 17:36:03 +00002112 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002113 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2114 Py_DECREF(ah);
2115 Py_DECREF(al);
2116 ah = al = NULL;
2117
Tim Peters0973b992004-08-29 22:16:50 +00002118 if (a == b) {
2119 t2 = t1;
2120 Py_INCREF(t2);
2121 }
2122 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002123 Py_DECREF(t1);
2124 goto fail;
2125 }
2126 Py_DECREF(bh);
2127 Py_DECREF(bl);
2128 bh = bl = NULL;
2129
Tim Peters738eda72002-08-12 15:08:20 +00002130 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002131 Py_DECREF(t1);
2132 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002133 if (t3 == NULL) goto fail;
Tim Peters547607c2002-08-12 19:43:49 +00002134 assert(t3->ob_size >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002135
Tim Petersd6974a52002-08-13 20:37:51 +00002136 /* Add t3. It's not obvious why we can't run out of room here.
2137 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002138 */
Tim Petersd64c1de2002-08-12 17:36:03 +00002139 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, t3->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002140 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002141
Tim Peters5af4e6c2002-08-12 02:31:19 +00002142 return long_normalize(ret);
2143
2144 fail:
2145 Py_XDECREF(ret);
2146 Py_XDECREF(ah);
2147 Py_XDECREF(al);
2148 Py_XDECREF(bh);
2149 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002150 return NULL;
2151}
2152
Tim Petersd6974a52002-08-13 20:37:51 +00002153/* (*) Why adding t3 can't "run out of room" above.
2154
Tim Petersab86c2b2002-08-15 20:06:00 +00002155Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2156to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002157
Tim Petersab86c2b2002-08-15 20:06:00 +000021581. For any integer i, i = c(i/2) + f(i/2). In particular,
2159 bsize = c(bsize/2) + f(bsize/2).
21602. shift = f(bsize/2)
21613. asize <= bsize
21624. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2163 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002164
Tim Petersab86c2b2002-08-15 20:06:00 +00002165We allocated asize + bsize result digits, and add t3 into them at an offset
2166of shift. This leaves asize+bsize-shift allocated digit positions for t3
2167to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2168asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002169
Tim Petersab86c2b2002-08-15 20:06:00 +00002170bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2171at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002172
Tim Petersab86c2b2002-08-15 20:06:00 +00002173If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2174digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2175most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002176
Tim Petersab86c2b2002-08-15 20:06:00 +00002177The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002178
Tim Petersab86c2b2002-08-15 20:06:00 +00002179 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002180
Tim Petersab86c2b2002-08-15 20:06:00 +00002181and we have asize + c(bsize/2) available digit positions. We need to show
2182this is always enough. An instance of c(bsize/2) cancels out in both, so
2183the question reduces to whether asize digits is enough to hold
2184(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2185then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2186asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
2187digit is enough to hold 2 bits. This is so since SHIFT=15 >= 2. If
2188asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002189c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2190is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2191bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002192
Tim Peters48d52c02002-08-14 17:07:32 +00002193Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2194clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2195ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002196*/
2197
Tim Peters60004642002-08-12 22:01:34 +00002198/* b has at least twice the digits of a, and a is big enough that Karatsuba
2199 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2200 * of slices, each with a->ob_size digits, and multiply the slices by a,
2201 * one at a time. This gives k_mul balanced inputs to work with, and is
2202 * also cache-friendly (we compute one double-width slice of the result
2203 * at a time, then move on, never bactracking except for the helpful
2204 * single-width slice overlap between successive partial sums).
2205 */
2206static PyLongObject *
2207k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2208{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002209 const Py_ssize_t asize = ABS(a->ob_size);
2210 Py_ssize_t bsize = ABS(b->ob_size);
2211 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002212 PyLongObject *ret;
2213 PyLongObject *bslice = NULL;
2214
2215 assert(asize > KARATSUBA_CUTOFF);
2216 assert(2 * asize <= bsize);
2217
2218 /* Allocate result space, and zero it out. */
2219 ret = _PyLong_New(asize + bsize);
2220 if (ret == NULL)
2221 return NULL;
2222 memset(ret->ob_digit, 0, ret->ob_size * sizeof(digit));
2223
2224 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002225 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002226 if (bslice == NULL)
2227 goto fail;
2228
2229 nbdone = 0;
2230 while (bsize > 0) {
2231 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002232 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002233
2234 /* Multiply the next slice of b by a. */
2235 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2236 nbtouse * sizeof(digit));
2237 bslice->ob_size = nbtouse;
2238 product = k_mul(a, bslice);
2239 if (product == NULL)
2240 goto fail;
2241
2242 /* Add into result. */
2243 (void)v_iadd(ret->ob_digit + nbdone, ret->ob_size - nbdone,
2244 product->ob_digit, product->ob_size);
2245 Py_DECREF(product);
2246
2247 bsize -= nbtouse;
2248 nbdone += nbtouse;
2249 }
2250
2251 Py_DECREF(bslice);
2252 return long_normalize(ret);
2253
2254 fail:
2255 Py_DECREF(ret);
2256 Py_XDECREF(bslice);
2257 return NULL;
2258}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002259
2260static PyObject *
2261long_mul(PyLongObject *v, PyLongObject *w)
2262{
2263 PyLongObject *a, *b, *z;
2264
2265 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002266 Py_INCREF(Py_NotImplemented);
2267 return Py_NotImplemented;
2268 }
2269
Tim Petersd64c1de2002-08-12 17:36:03 +00002270 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002271 /* Negate if exactly one of the inputs is negative. */
2272 if (((a->ob_size ^ b->ob_size) < 0) && z)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002273 z->ob_size = -(z->ob_size);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002274 Py_DECREF(a);
2275 Py_DECREF(b);
Tim Peters9973d742002-08-15 19:41:06 +00002276 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002277}
2278
Guido van Rossume32e0141992-01-19 16:31:05 +00002279/* The / and % operators are now defined in terms of divmod().
2280 The expression a mod b has the value a - b*floor(a/b).
2281 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002282 |a| by |b|, with the sign of a. This is also expressed
2283 as a - b*trunc(a/b), if trunc truncates towards zero.
2284 Some examples:
2285 a b a rem b a mod b
2286 13 10 3 3
2287 -13 10 -3 7
2288 13 -10 3 -7
2289 -13 -10 -3 -3
2290 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002291 have different signs. We then subtract one from the 'div'
2292 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002293
Tim Peters47e52ee2004-08-30 02:44:38 +00002294/* Compute
2295 * *pdiv, *pmod = divmod(v, w)
2296 * NULL can be passed for pdiv or pmod, in which case that part of
2297 * the result is simply thrown away. The caller owns a reference to
2298 * each of these it requests (does not pass NULL for).
2299 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002300static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002301l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002302 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002303{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002304 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002305
Guido van Rossume32e0141992-01-19 16:31:05 +00002306 if (long_divrem(v, w, &div, &mod) < 0)
2307 return -1;
Guido van Rossum472c04f1996-12-05 21:57:21 +00002308 if ((mod->ob_size < 0 && w->ob_size > 0) ||
2309 (mod->ob_size > 0 && w->ob_size < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002310 PyLongObject *temp;
2311 PyLongObject *one;
2312 temp = (PyLongObject *) long_add(mod, w);
2313 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002314 mod = temp;
2315 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002316 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002317 return -1;
2318 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002319 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002320 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002321 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2322 Py_DECREF(mod);
2323 Py_DECREF(div);
2324 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002325 return -1;
2326 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002327 Py_DECREF(one);
2328 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002329 div = temp;
2330 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002331 if (pdiv != NULL)
2332 *pdiv = div;
2333 else
2334 Py_DECREF(div);
2335
2336 if (pmod != NULL)
2337 *pmod = mod;
2338 else
2339 Py_DECREF(mod);
2340
Guido van Rossume32e0141992-01-19 16:31:05 +00002341 return 0;
2342}
2343
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002344static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002345long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002346{
Tim Peters47e52ee2004-08-30 02:44:38 +00002347 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002348
2349 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002350 if (l_divmod(a, b, &div, NULL) < 0)
2351 div = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002352 Py_DECREF(a);
2353 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002354 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002355}
2356
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002357static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +00002358long_classic_div(PyObject *v, PyObject *w)
2359{
Tim Peters47e52ee2004-08-30 02:44:38 +00002360 PyLongObject *a, *b, *div;
Guido van Rossum393661d2001-08-31 17:40:15 +00002361
2362 CONVERT_BINOP(v, w, &a, &b);
Guido van Rossum393661d2001-08-31 17:40:15 +00002363 if (Py_DivisionWarningFlag &&
2364 PyErr_Warn(PyExc_DeprecationWarning, "classic long division") < 0)
2365 div = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00002366 else if (l_divmod(a, b, &div, NULL) < 0)
Guido van Rossum393661d2001-08-31 17:40:15 +00002367 div = NULL;
Guido van Rossum393661d2001-08-31 17:40:15 +00002368 Py_DECREF(a);
2369 Py_DECREF(b);
2370 return (PyObject *)div;
2371}
2372
2373static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00002374long_true_divide(PyObject *v, PyObject *w)
2375{
Tim Peterse2a60002001-09-04 06:17:36 +00002376 PyLongObject *a, *b;
2377 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002378 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002379
2380 CONVERT_BINOP(v, w, &a, &b);
2381 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2382 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002383 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
2384 Py_DECREF(a);
2385 Py_DECREF(b);
2386 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002387 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002388 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2389 but should really be set correctly after sucessful calls to
2390 _PyLong_AsScaledDouble() */
2391 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002392
2393 if (bd == 0.0) {
2394 PyErr_SetString(PyExc_ZeroDivisionError,
2395 "long division or modulo by zero");
2396 return NULL;
2397 }
2398
2399 /* True value is very close to ad/bd * 2**(SHIFT*(aexp-bexp)) */
2400 ad /= bd; /* overflow/underflow impossible here */
2401 aexp -= bexp;
2402 if (aexp > INT_MAX / SHIFT)
2403 goto overflow;
Tim Peterse56ed9b2001-09-06 21:59:14 +00002404 else if (aexp < -(INT_MAX / SHIFT))
2405 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002406 errno = 0;
2407 ad = ldexp(ad, aexp * SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002408 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002409 goto overflow;
2410 return PyFloat_FromDouble(ad);
2411
2412overflow:
2413 PyErr_SetString(PyExc_OverflowError,
2414 "long/long too large for a float");
2415 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002416
Tim Peters20dab9f2001-09-04 05:31:47 +00002417}
2418
2419static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002420long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002421{
Tim Peters47e52ee2004-08-30 02:44:38 +00002422 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002423
2424 CONVERT_BINOP(v, w, &a, &b);
2425
Tim Peters47e52ee2004-08-30 02:44:38 +00002426 if (l_divmod(a, b, NULL, &mod) < 0)
2427 mod = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002428 Py_DECREF(a);
2429 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002430 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002431}
2432
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002433static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002434long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002435{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002436 PyLongObject *a, *b, *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002437 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002438
2439 CONVERT_BINOP(v, w, &a, &b);
2440
2441 if (l_divmod(a, b, &div, &mod) < 0) {
2442 Py_DECREF(a);
2443 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002444 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002445 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002446 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002447 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002448 PyTuple_SetItem(z, 0, (PyObject *) div);
2449 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002450 }
2451 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002452 Py_DECREF(div);
2453 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002454 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002455 Py_DECREF(a);
2456 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002457 return z;
2458}
2459
Tim Peters47e52ee2004-08-30 02:44:38 +00002460/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002461static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002462long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002463{
Tim Peters47e52ee2004-08-30 02:44:38 +00002464 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
2465 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002466
Tim Peters47e52ee2004-08-30 02:44:38 +00002467 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002468 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00002469 PyLongObject *temp = NULL;
2470
2471 /* 5-ary values. If the exponent is large enough, table is
2472 * precomputed so that table[i] == a**i % c for i in range(32).
2473 */
2474 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2475 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2476
2477 /* a, b, c = v, w, x */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002478 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002479 if (PyLong_Check(x)) {
2480 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002481 Py_INCREF(x);
2482 }
Tim Petersde7990b2005-07-17 23:45:23 +00002483 else if (PyInt_Check(x)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002484 c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x));
Tim Petersde7990b2005-07-17 23:45:23 +00002485 if (c == NULL)
2486 goto Error;
2487 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002488 else if (x == Py_None)
2489 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002490 else {
2491 Py_DECREF(a);
2492 Py_DECREF(b);
2493 Py_INCREF(Py_NotImplemented);
2494 return Py_NotImplemented;
2495 }
Tim Peters4c483c42001-09-05 06:24:58 +00002496
Tim Peters47e52ee2004-08-30 02:44:38 +00002497 if (b->ob_size < 0) { /* if exponent is negative */
2498 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00002499 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00002500 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00002501 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00002502 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002503 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00002504 /* else return a float. This works because we know
2505 that this calls float_pow() which converts its
2506 arguments to double. */
2507 Py_DECREF(a);
2508 Py_DECREF(b);
2509 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002510 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002511 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002512
2513 if (c) {
2514 /* if modulus == 0:
2515 raise ValueError() */
2516 if (c->ob_size == 0) {
2517 PyErr_SetString(PyExc_ValueError,
2518 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00002519 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002520 }
2521
2522 /* if modulus < 0:
2523 negativeOutput = True
2524 modulus = -modulus */
2525 if (c->ob_size < 0) {
2526 negativeOutput = 1;
2527 temp = (PyLongObject *)_PyLong_Copy(c);
2528 if (temp == NULL)
2529 goto Error;
2530 Py_DECREF(c);
2531 c = temp;
2532 temp = NULL;
2533 c->ob_size = - c->ob_size;
2534 }
2535
2536 /* if modulus == 1:
2537 return 0 */
2538 if ((c->ob_size == 1) && (c->ob_digit[0] == 1)) {
2539 z = (PyLongObject *)PyLong_FromLong(0L);
2540 goto Done;
2541 }
2542
2543 /* if base < 0:
2544 base = base % modulus
2545 Having the base positive just makes things easier. */
2546 if (a->ob_size < 0) {
2547 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00002548 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002549 Py_DECREF(a);
2550 a = temp;
2551 temp = NULL;
2552 }
2553 }
2554
2555 /* At this point a, b, and c are guaranteed non-negative UNLESS
2556 c is NULL, in which case a may be negative. */
2557
2558 z = (PyLongObject *)PyLong_FromLong(1L);
2559 if (z == NULL)
2560 goto Error;
2561
2562 /* Perform a modular reduction, X = X % c, but leave X alone if c
2563 * is NULL.
2564 */
2565#define REDUCE(X) \
2566 if (c != NULL) { \
2567 if (l_divmod(X, c, NULL, &temp) < 0) \
2568 goto Error; \
2569 Py_XDECREF(X); \
2570 X = temp; \
2571 temp = NULL; \
2572 }
2573
2574 /* Multiply two values, then reduce the result:
2575 result = X*Y % c. If c is NULL, skip the mod. */
2576#define MULT(X, Y, result) \
2577{ \
2578 temp = (PyLongObject *)long_mul(X, Y); \
2579 if (temp == NULL) \
2580 goto Error; \
2581 Py_XDECREF(result); \
2582 result = temp; \
2583 temp = NULL; \
2584 REDUCE(result) \
2585}
2586
2587 if (b->ob_size <= FIVEARY_CUTOFF) {
2588 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
2589 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
2590 for (i = b->ob_size - 1; i >= 0; --i) {
2591 digit bi = b->ob_digit[i];
2592
2593 for (j = 1 << (SHIFT-1); j != 0; j >>= 1) {
2594 MULT(z, z, z)
2595 if (bi & j)
2596 MULT(z, a, z)
2597 }
2598 }
2599 }
2600 else {
2601 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
2602 Py_INCREF(z); /* still holds 1L */
2603 table[0] = z;
2604 for (i = 1; i < 32; ++i)
2605 MULT(table[i-1], a, table[i])
2606
2607 for (i = b->ob_size - 1; i >= 0; --i) {
2608 const digit bi = b->ob_digit[i];
2609
2610 for (j = SHIFT - 5; j >= 0; j -= 5) {
2611 const int index = (bi >> j) & 0x1f;
2612 for (k = 0; k < 5; ++k)
2613 MULT(z, z, z)
2614 if (index)
2615 MULT(z, table[index], z)
2616 }
2617 }
2618 }
2619
2620 if (negativeOutput && (z->ob_size != 0)) {
2621 temp = (PyLongObject *)long_sub(z, c);
2622 if (temp == NULL)
2623 goto Error;
2624 Py_DECREF(z);
2625 z = temp;
2626 temp = NULL;
2627 }
2628 goto Done;
2629
2630 Error:
2631 if (z != NULL) {
2632 Py_DECREF(z);
2633 z = NULL;
2634 }
2635 /* fall through */
2636 Done:
Tim Peters47e52ee2004-08-30 02:44:38 +00002637 if (b->ob_size > FIVEARY_CUTOFF) {
2638 for (i = 0; i < 32; ++i)
2639 Py_XDECREF(table[i]);
2640 }
Tim Petersde7990b2005-07-17 23:45:23 +00002641 Py_DECREF(a);
2642 Py_DECREF(b);
2643 Py_XDECREF(c);
2644 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002645 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002646}
2647
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002648static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002649long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002650{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002651 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002652 PyLongObject *x;
2653 PyLongObject *w;
2654 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002655 if (w == NULL)
2656 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002657 x = (PyLongObject *) long_add(v, w);
2658 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002659 if (x == NULL)
2660 return NULL;
Tim Peters40c397d2001-09-11 23:24:22 +00002661 x->ob_size = -(x->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002662 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002663}
2664
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002665static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002666long_pos(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002667{
Tim Peters69c2de32001-09-11 22:31:33 +00002668 if (PyLong_CheckExact(v)) {
2669 Py_INCREF(v);
2670 return (PyObject *)v;
2671 }
2672 else
2673 return _PyLong_Copy(v);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002674}
2675
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002676static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002677long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002678{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002679 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002680 if (v->ob_size == 0 && PyLong_CheckExact(v)) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002681 /* -0 == 0 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002682 Py_INCREF(v);
2683 return (PyObject *) v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002684 }
Tim Peters69c2de32001-09-11 22:31:33 +00002685 z = (PyLongObject *)_PyLong_Copy(v);
2686 if (z != NULL)
2687 z->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002688 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002689}
2690
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002691static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002692long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002693{
2694 if (v->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002695 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00002696 else
2697 return long_pos(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002698}
2699
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002700static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002701long_nonzero(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002702{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002703 return ABS(v->ob_size) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002704}
2705
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002706static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002707long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002708{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002709 PyLongObject *a, *b;
2710 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002711 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002712 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002713 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002714
Neil Schemenauerba872e22001-01-04 01:46:03 +00002715 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2716
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002717 if (a->ob_size < 0) {
2718 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002719 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002720 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002721 if (a1 == NULL)
2722 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002723 a2 = (PyLongObject *) long_rshift(a1, b);
2724 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002725 if (a2 == NULL)
2726 goto rshift_error;
2727 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002728 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002729 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002730 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002731
Neil Schemenauerba872e22001-01-04 01:46:03 +00002732 shiftby = PyLong_AsLong((PyObject *)b);
2733 if (shiftby == -1L && PyErr_Occurred())
2734 goto rshift_error;
2735 if (shiftby < 0) {
2736 PyErr_SetString(PyExc_ValueError,
2737 "negative shift count");
2738 goto rshift_error;
2739 }
2740 wordshift = shiftby / SHIFT;
2741 newsize = ABS(a->ob_size) - wordshift;
2742 if (newsize <= 0) {
2743 z = _PyLong_New(0);
2744 Py_DECREF(a);
2745 Py_DECREF(b);
2746 return (PyObject *)z;
2747 }
2748 loshift = shiftby % SHIFT;
2749 hishift = SHIFT - loshift;
2750 lomask = ((digit)1 << hishift) - 1;
2751 himask = MASK ^ lomask;
2752 z = _PyLong_New(newsize);
2753 if (z == NULL)
2754 goto rshift_error;
2755 if (a->ob_size < 0)
2756 z->ob_size = -(z->ob_size);
2757 for (i = 0, j = wordshift; i < newsize; i++, j++) {
2758 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
2759 if (i+1 < newsize)
2760 z->ob_digit[i] |=
2761 (a->ob_digit[j+1] << hishift) & himask;
2762 }
2763 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002764 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002765rshift_error:
2766 Py_DECREF(a);
2767 Py_DECREF(b);
2768 return (PyObject *) z;
2769
Guido van Rossumc6913e71991-11-19 20:26:46 +00002770}
2771
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002772static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002773long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002774{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002775 /* This version due to Tim Peters */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002776 PyLongObject *a, *b;
2777 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002778 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002779 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002780 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002781
Neil Schemenauerba872e22001-01-04 01:46:03 +00002782 CONVERT_BINOP(v, w, &a, &b);
2783
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002784 shiftby = PyLong_AsLong((PyObject *)b);
2785 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00002786 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002787 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002788 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00002789 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002790 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002791 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002792 PyErr_SetString(PyExc_ValueError,
2793 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00002794 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002795 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002796 /* wordshift, remshift = divmod(shiftby, SHIFT) */
2797 wordshift = (int)shiftby / SHIFT;
2798 remshift = (int)shiftby - wordshift * SHIFT;
2799
2800 oldsize = ABS(a->ob_size);
2801 newsize = oldsize + wordshift;
2802 if (remshift)
2803 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002804 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002805 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002806 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002807 if (a->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002808 z->ob_size = -(z->ob_size);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002809 for (i = 0; i < wordshift; i++)
2810 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002811 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002812 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00002813 accum |= (twodigits)a->ob_digit[j] << remshift;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002814 z->ob_digit[i] = (digit)(accum & MASK);
2815 accum >>= SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002816 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002817 if (remshift)
2818 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002819 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002820 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002821 z = long_normalize(z);
2822lshift_error:
2823 Py_DECREF(a);
2824 Py_DECREF(b);
2825 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002826}
2827
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002828
2829/* Bitwise and/xor/or operations */
2830
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002831static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002832long_bitwise(PyLongObject *a,
2833 int op, /* '&', '|', '^' */
2834 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002835{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002836 digit maska, maskb; /* 0 or MASK */
2837 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002838 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002839 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002840 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00002841 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002842 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002843
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002844 if (a->ob_size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002845 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00002846 if (a == NULL)
2847 return NULL;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002848 maska = MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002849 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002850 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002851 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002852 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00002853 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002854 if (b->ob_size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002855 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00002856 if (b == NULL) {
2857 Py_DECREF(a);
2858 return NULL;
2859 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002860 maskb = MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002861 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002862 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002863 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002864 maskb = 0;
2865 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002866
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002867 negz = 0;
2868 switch (op) {
2869 case '^':
2870 if (maska != maskb) {
2871 maska ^= MASK;
2872 negz = -1;
2873 }
2874 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002875 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002876 if (maska && maskb) {
2877 op = '|';
2878 maska ^= MASK;
2879 maskb ^= MASK;
2880 negz = -1;
2881 }
2882 break;
2883 case '|':
2884 if (maska || maskb) {
2885 op = '&';
2886 maska ^= MASK;
2887 maskb ^= MASK;
2888 negz = -1;
2889 }
2890 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002891 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002892
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002893 /* JRH: The original logic here was to allocate the result value (z)
2894 as the longer of the two operands. However, there are some cases
2895 where the result is guaranteed to be shorter than that: AND of two
2896 positives, OR of two negatives: use the shorter number. AND with
2897 mixed signs: use the positive number. OR with mixed signs: use the
2898 negative number. After the transformations above, op will be '&'
2899 iff one of these cases applies, and mask will be non-0 for operands
2900 whose length should be ignored.
2901 */
2902
2903 size_a = a->ob_size;
2904 size_b = b->ob_size;
2905 size_z = op == '&'
2906 ? (maska
2907 ? size_b
2908 : (maskb ? size_a : MIN(size_a, size_b)))
2909 : MAX(size_a, size_b);
2910 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00002911 if (z == NULL) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002912 Py_XDECREF(a);
2913 Py_XDECREF(b);
2914 Py_XDECREF(z);
2915 return NULL;
2916 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002917
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002918 for (i = 0; i < size_z; ++i) {
2919 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
2920 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
2921 switch (op) {
2922 case '&': z->ob_digit[i] = diga & digb; break;
2923 case '|': z->ob_digit[i] = diga | digb; break;
2924 case '^': z->ob_digit[i] = diga ^ digb; break;
2925 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00002926 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002927
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002928 Py_DECREF(a);
2929 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002930 z = long_normalize(z);
2931 if (negz == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002932 return (PyObject *) z;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002933 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002934 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002935 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002936}
2937
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002938static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002939long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002940{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002941 PyLongObject *a, *b;
2942 PyObject *c;
2943 CONVERT_BINOP(v, w, &a, &b);
2944 c = long_bitwise(a, '&', b);
2945 Py_DECREF(a);
2946 Py_DECREF(b);
2947 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002948}
2949
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002950static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002951long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002952{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002953 PyLongObject *a, *b;
2954 PyObject *c;
2955 CONVERT_BINOP(v, w, &a, &b);
2956 c = long_bitwise(a, '^', b);
2957 Py_DECREF(a);
2958 Py_DECREF(b);
2959 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002960}
2961
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002962static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002963long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002964{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002965 PyLongObject *a, *b;
2966 PyObject *c;
2967 CONVERT_BINOP(v, w, &a, &b);
2968 c = long_bitwise(a, '|', b);
2969 Py_DECREF(a);
2970 Py_DECREF(b);
2971 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002972}
2973
Guido van Rossum234f9421993-06-17 12:35:49 +00002974static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002975long_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00002976{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002977 if (PyInt_Check(*pw)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00002978 *pw = PyLong_FromLong(PyInt_AS_LONG(*pw));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002979 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00002980 return 0;
2981 }
Guido van Rossum1952e382001-09-19 01:25:16 +00002982 else if (PyLong_Check(*pw)) {
2983 Py_INCREF(*pv);
2984 Py_INCREF(*pw);
2985 return 0;
2986 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00002987 return 1; /* Can't do it */
2988}
2989
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002990static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002991long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00002992{
Brett Cannonc3647ac2005-04-26 03:45:26 +00002993 if (PyLong_CheckExact(v))
2994 Py_INCREF(v);
2995 else
2996 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00002997 return v;
2998}
2999
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003000static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00003001long_int(PyObject *v)
3002{
3003 long x;
3004 x = PyLong_AsLong(v);
3005 if (PyErr_Occurred()) {
3006 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
3007 PyErr_Clear();
3008 if (PyLong_CheckExact(v)) {
3009 Py_INCREF(v);
3010 return v;
3011 }
3012 else
3013 return _PyLong_Copy((PyLongObject *)v);
3014 }
3015 else
3016 return NULL;
3017 }
3018 return PyInt_FromLong(x);
3019}
3020
3021static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003022long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003023{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003024 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003025 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003026 if (result == -1.0 && PyErr_Occurred())
3027 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003028 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003029}
3030
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003031static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003032long_oct(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003033{
Fred Drake121ee271999-12-23 15:41:28 +00003034 return long_format(v, 8, 1);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003035}
3036
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003037static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003038long_hex(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003039{
Fred Drake121ee271999-12-23 15:41:28 +00003040 return long_format(v, 16, 1);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003041}
Jeremy Hylton938ace62002-07-17 16:30:39 +00003042
3043static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003044long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003045
Tim Peters6d6c1a32001-08-02 04:15:00 +00003046static PyObject *
3047long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3048{
3049 PyObject *x = NULL;
3050 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003051 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003052
Guido van Rossumbef14172001-08-29 15:47:46 +00003053 if (type != &PyLong_Type)
3054 return long_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003055 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist,
3056 &x, &base))
3057 return NULL;
3058 if (x == NULL)
3059 return PyLong_FromLong(0L);
3060 if (base == -909)
3061 return PyNumber_Long(x);
3062 else if (PyString_Check(x))
3063 return PyLong_FromString(PyString_AS_STRING(x), NULL, base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003064#ifdef Py_USING_UNICODE
Tim Peters6d6c1a32001-08-02 04:15:00 +00003065 else if (PyUnicode_Check(x))
3066 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3067 PyUnicode_GET_SIZE(x),
3068 base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003069#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +00003070 else {
3071 PyErr_SetString(PyExc_TypeError,
3072 "long() can't convert non-string with explicit base");
3073 return NULL;
3074 }
3075}
3076
Guido van Rossumbef14172001-08-29 15:47:46 +00003077/* Wimpy, slow approach to tp_new calls for subtypes of long:
3078 first create a regular long from whatever arguments we got,
3079 then allocate a subtype instance and initialize it from
3080 the regular long. The regular long is then thrown away.
3081*/
3082static PyObject *
3083long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3084{
3085 PyLongObject *tmp, *new;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003086 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003087
3088 assert(PyType_IsSubtype(type, &PyLong_Type));
3089 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3090 if (tmp == NULL)
3091 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003092 assert(PyLong_CheckExact(tmp));
Guido van Rossumbef14172001-08-29 15:47:46 +00003093 n = tmp->ob_size;
3094 if (n < 0)
3095 n = -n;
3096 new = (PyLongObject *)type->tp_alloc(type, n);
Raymond Hettingerf4667932003-06-28 20:04:25 +00003097 if (new == NULL) {
3098 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003099 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003100 }
Guido van Rossumbef14172001-08-29 15:47:46 +00003101 assert(PyLong_Check(new));
Guido van Rossum13228a62001-08-30 15:54:44 +00003102 new->ob_size = tmp->ob_size;
Guido van Rossumbef14172001-08-29 15:47:46 +00003103 for (i = 0; i < n; i++)
3104 new->ob_digit[i] = tmp->ob_digit[i];
3105 Py_DECREF(tmp);
3106 return (PyObject *)new;
3107}
3108
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003109static PyObject *
3110long_getnewargs(PyLongObject *v)
3111{
3112 return Py_BuildValue("(N)", _PyLong_Copy(v));
3113}
3114
3115static PyMethodDef long_methods[] = {
3116 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
3117 {NULL, NULL} /* sentinel */
3118};
3119
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003120PyDoc_STRVAR(long_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003121"long(x[, base]) -> integer\n\
3122\n\
3123Convert a string or number to a long integer, if possible. A floating\n\
3124point argument will be truncated towards zero (this does not include a\n\
3125string representation of a floating point number!) When converting a\n\
3126string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003127converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003128
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003129static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003130 (binaryfunc) long_add, /*nb_add*/
3131 (binaryfunc) long_sub, /*nb_subtract*/
3132 (binaryfunc) long_mul, /*nb_multiply*/
Guido van Rossum393661d2001-08-31 17:40:15 +00003133 (binaryfunc) long_classic_div, /*nb_divide*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003134 (binaryfunc) long_mod, /*nb_remainder*/
3135 (binaryfunc) long_divmod, /*nb_divmod*/
3136 (ternaryfunc) long_pow, /*nb_power*/
3137 (unaryfunc) long_neg, /*nb_negative*/
3138 (unaryfunc) long_pos, /*tp_positive*/
3139 (unaryfunc) long_abs, /*tp_absolute*/
3140 (inquiry) long_nonzero, /*tp_nonzero*/
3141 (unaryfunc) long_invert, /*nb_invert*/
3142 (binaryfunc) long_lshift, /*nb_lshift*/
3143 (binaryfunc) long_rshift, /*nb_rshift*/
3144 (binaryfunc) long_and, /*nb_and*/
3145 (binaryfunc) long_xor, /*nb_xor*/
3146 (binaryfunc) long_or, /*nb_or*/
Tim Peters9ace6bc2000-07-08 00:32:04 +00003147 (coercion) long_coerce, /*nb_coerce*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003148 (unaryfunc) long_int, /*nb_int*/
3149 (unaryfunc) long_long, /*nb_long*/
3150 (unaryfunc) long_float, /*nb_float*/
3151 (unaryfunc) long_oct, /*nb_oct*/
3152 (unaryfunc) long_hex, /*nb_hex*/
Guido van Rossum4668b002001-08-08 05:00:18 +00003153 0, /* nb_inplace_add */
3154 0, /* nb_inplace_subtract */
3155 0, /* nb_inplace_multiply */
3156 0, /* nb_inplace_divide */
3157 0, /* nb_inplace_remainder */
3158 0, /* nb_inplace_power */
3159 0, /* nb_inplace_lshift */
3160 0, /* nb_inplace_rshift */
3161 0, /* nb_inplace_and */
3162 0, /* nb_inplace_xor */
3163 0, /* nb_inplace_or */
3164 (binaryfunc)long_div, /* nb_floor_divide */
3165 long_true_divide, /* nb_true_divide */
3166 0, /* nb_inplace_floor_divide */
3167 0, /* nb_inplace_true_divide */
Guido van Rossum38fff8c2006-03-07 18:50:55 +00003168 (lenfunc)long_index, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003169};
3170
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003171PyTypeObject PyLong_Type = {
3172 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003173 0, /* ob_size */
3174 "long", /* tp_name */
3175 sizeof(PyLongObject) - sizeof(digit), /* tp_basicsize */
3176 sizeof(digit), /* tp_itemsize */
3177 (destructor)long_dealloc, /* tp_dealloc */
3178 0, /* tp_print */
3179 0, /* tp_getattr */
3180 0, /* tp_setattr */
3181 (cmpfunc)long_compare, /* tp_compare */
3182 (reprfunc)long_repr, /* tp_repr */
3183 &long_as_number, /* tp_as_number */
3184 0, /* tp_as_sequence */
3185 0, /* tp_as_mapping */
3186 (hashfunc)long_hash, /* tp_hash */
3187 0, /* tp_call */
3188 (reprfunc)long_str, /* tp_str */
3189 PyObject_GenericGetAttr, /* tp_getattro */
3190 0, /* tp_setattro */
3191 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00003192 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3193 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003194 long_doc, /* tp_doc */
3195 0, /* tp_traverse */
3196 0, /* tp_clear */
3197 0, /* tp_richcompare */
3198 0, /* tp_weaklistoffset */
3199 0, /* tp_iter */
3200 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003201 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003202 0, /* tp_members */
3203 0, /* tp_getset */
3204 0, /* tp_base */
3205 0, /* tp_dict */
3206 0, /* tp_descr_get */
3207 0, /* tp_descr_set */
3208 0, /* tp_dictoffset */
3209 0, /* tp_init */
3210 0, /* tp_alloc */
3211 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003212 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003213};