blob: 3073923e1fe5b060bcab675c0d50dc2ec09f3fee [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
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000284 return PY_SSIZE_T_MIN;
Guido van Rossum38fff8c2006-03-07 18:50:55 +0000285}
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.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000304 On error, return -1 with an exception set.
Guido van Rossum38fff8c2006-03-07 18:50:55 +0000305*/
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;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000422 if (result / SHIFT != (size_t)(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
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000774 if ((long)p < 0)
775 return PyLong_FromUnsignedLong((unsigned long)p);
Guido van Rossum78694d91998-09-18 14:14:13 +0000776 return PyInt_FromLong((long)p);
777#else
Guido van Rossum78694d91998-09-18 14:14:13 +0000778
Tim Peters70128a12001-06-16 08:48:40 +0000779#ifndef HAVE_LONG_LONG
780# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
781#endif
782#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000783# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000784#endif
785 /* optimize null pointers */
786 if (p == NULL)
787 return PyInt_FromLong(0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000788 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)p);
Tim Peters70128a12001-06-16 08:48:40 +0000789
790#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000791}
792
793/* Get a C pointer from a long object (or an int object in some cases) */
794
795void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000796PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000797{
798 /* This function will allow int or long objects. If vv is neither,
799 then the PyLong_AsLong*() functions will raise the exception:
800 PyExc_SystemError, "bad argument to internal function"
801 */
Tim Peters70128a12001-06-16 08:48:40 +0000802#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +0000803 long x;
804
Tim Peters70128a12001-06-16 08:48:40 +0000805 if (PyInt_Check(vv))
Guido van Rossum78694d91998-09-18 14:14:13 +0000806 x = PyInt_AS_LONG(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000807 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000808 x = PyLong_AsLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000809 else
810 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000811#else
Tim Peters70128a12001-06-16 08:48:40 +0000812
813#ifndef HAVE_LONG_LONG
814# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
815#endif
816#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000817# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000818#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000819 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000820
Tim Peters70128a12001-06-16 08:48:40 +0000821 if (PyInt_Check(vv))
Guido van Rossum78694d91998-09-18 14:14:13 +0000822 x = PyInt_AS_LONG(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000823 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000824 x = PyLong_AsLongLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000825 else
826 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000827
828#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000829
830 if (x == -1 && PyErr_Occurred())
831 return NULL;
832 return (void *)x;
833}
834
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000835#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000836
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000837/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000838 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000839 */
840
Tim Peterscf37dfc2001-06-14 18:42:50 +0000841#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +0000842
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000843/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000844
845PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000846PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000847{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000848 PY_LONG_LONG bytes = ival;
Tim Petersd1a7da62001-06-13 00:35:57 +0000849 int one = 1;
850 return _PyLong_FromByteArray(
851 (unsigned char *)&bytes,
852 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000853}
854
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000855/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +0000856
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000857PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000858PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000859{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000860 unsigned PY_LONG_LONG bytes = ival;
Tim Petersd1a7da62001-06-13 00:35:57 +0000861 int one = 1;
862 return _PyLong_FromByteArray(
863 (unsigned char *)&bytes,
864 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000865}
866
Martin v. Löwis18e16552006-02-15 17:27:45 +0000867/* Create a new long int object from a C Py_ssize_t. */
868
869PyObject *
870_PyLong_FromSsize_t(Py_ssize_t ival)
871{
872 Py_ssize_t bytes = ival;
873 int one = 1;
874 return _PyLong_FromByteArray(
875 (unsigned char *)&bytes,
876 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
877}
878
879/* Create a new long int object from a C size_t. */
880
881PyObject *
882_PyLong_FromSize_t(size_t ival)
883{
884 size_t bytes = ival;
885 int one = 1;
886 return _PyLong_FromByteArray(
887 (unsigned char *)&bytes,
888 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
889}
890
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000891/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000892 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000893
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000894PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000895PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000896{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000897 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +0000898 int one = 1;
899 int res;
900
Tim Petersd38b1c72001-09-30 05:09:37 +0000901 if (vv == NULL) {
902 PyErr_BadInternalCall();
903 return -1;
904 }
905 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +0000906 PyNumberMethods *nb;
907 PyObject *io;
Tim Petersd38b1c72001-09-30 05:09:37 +0000908 if (PyInt_Check(vv))
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000909 return (PY_LONG_LONG)PyInt_AsLong(vv);
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +0000910 if ((nb = vv->ob_type->tp_as_number) == NULL ||
911 nb->nb_int == NULL) {
912 PyErr_SetString(PyExc_TypeError, "an integer is required");
913 return -1;
914 }
915 io = (*nb->nb_int) (vv);
916 if (io == NULL)
917 return -1;
918 if (PyInt_Check(io)) {
919 bytes = PyInt_AsLong(io);
920 Py_DECREF(io);
921 return bytes;
922 }
923 if (PyLong_Check(io)) {
924 bytes = PyLong_AsLongLong(io);
925 Py_DECREF(io);
926 return bytes;
927 }
928 Py_DECREF(io);
929 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000930 return -1;
931 }
932
Tim Petersd1a7da62001-06-13 00:35:57 +0000933 res = _PyLong_AsByteArray(
934 (PyLongObject *)vv, (unsigned char *)&bytes,
935 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000936
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000937 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000938 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000939 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000940 else
941 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000942}
943
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000944/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000945 Return -1 and set an error if overflow occurs. */
946
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000947unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000948PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000949{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000950 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +0000951 int one = 1;
952 int res;
953
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000954 if (vv == NULL || !PyLong_Check(vv)) {
955 PyErr_BadInternalCall();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000956 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000957 }
958
Tim Petersd1a7da62001-06-13 00:35:57 +0000959 res = _PyLong_AsByteArray(
960 (PyLongObject *)vv, (unsigned char *)&bytes,
961 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000962
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000963 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000964 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000965 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000966 else
967 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000968}
Tim Petersd1a7da62001-06-13 00:35:57 +0000969
Thomas Hellera4ea6032003-04-17 18:55:45 +0000970/* Get a C unsigned long int from a long int object, ignoring the high bits.
971 Returns -1 and sets an error condition if an error occurs. */
972
973unsigned PY_LONG_LONG
974PyLong_AsUnsignedLongLongMask(PyObject *vv)
975{
976 register PyLongObject *v;
977 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000978 Py_ssize_t i;
979 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000980
981 if (vv == NULL || !PyLong_Check(vv)) {
982 PyErr_BadInternalCall();
983 return (unsigned long) -1;
984 }
985 v = (PyLongObject *)vv;
986 i = v->ob_size;
987 sign = 1;
988 x = 0;
989 if (i < 0) {
990 sign = -1;
991 i = -i;
992 }
993 while (--i >= 0) {
994 x = (x << SHIFT) + v->ob_digit[i];
995 }
996 return x * sign;
997}
Tim Petersd1a7da62001-06-13 00:35:57 +0000998#undef IS_LITTLE_ENDIAN
999
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001000#endif /* HAVE_LONG_LONG */
1001
Neil Schemenauerba872e22001-01-04 01:46:03 +00001002
1003static int
1004convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00001005 if (PyLong_Check(v)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001006 *a = (PyLongObject *) v;
1007 Py_INCREF(v);
1008 }
1009 else if (PyInt_Check(v)) {
1010 *a = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(v));
1011 }
1012 else {
1013 return 0;
1014 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001015 if (PyLong_Check(w)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001016 *b = (PyLongObject *) w;
1017 Py_INCREF(w);
1018 }
1019 else if (PyInt_Check(w)) {
1020 *b = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(w));
1021 }
1022 else {
1023 Py_DECREF(*a);
1024 return 0;
1025 }
1026 return 1;
1027}
1028
1029#define CONVERT_BINOP(v, w, a, b) \
1030 if (!convert_binop(v, w, a, b)) { \
1031 Py_INCREF(Py_NotImplemented); \
1032 return Py_NotImplemented; \
1033 }
1034
Tim Peters877a2122002-08-12 05:09:36 +00001035/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1036 * is modified in place, by adding y to it. Carries are propagated as far as
1037 * x[m-1], and the remaining carry (0 or 1) is returned.
1038 */
1039static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001040v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001041{
1042 int i;
1043 digit carry = 0;
1044
1045 assert(m >= n);
1046 for (i = 0; i < n; ++i) {
1047 carry += x[i] + y[i];
1048 x[i] = carry & MASK;
1049 carry >>= SHIFT;
1050 assert((carry & 1) == carry);
1051 }
1052 for (; carry && i < m; ++i) {
1053 carry += x[i];
1054 x[i] = carry & MASK;
1055 carry >>= SHIFT;
1056 assert((carry & 1) == carry);
1057 }
1058 return carry;
1059}
1060
1061/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1062 * is modified in place, by subtracting y from it. Borrows are propagated as
1063 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1064 */
1065static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001066v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001067{
1068 int i;
1069 digit borrow = 0;
1070
1071 assert(m >= n);
1072 for (i = 0; i < n; ++i) {
1073 borrow = x[i] - y[i] - borrow;
1074 x[i] = borrow & MASK;
1075 borrow >>= SHIFT;
1076 borrow &= 1; /* keep only 1 sign bit */
1077 }
1078 for (; borrow && i < m; ++i) {
1079 borrow = x[i] - borrow;
1080 x[i] = borrow & MASK;
1081 borrow >>= SHIFT;
1082 borrow &= 1;
1083 }
1084 return borrow;
1085}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001086
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001087/* Multiply by a single digit, ignoring the sign. */
1088
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001089static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001090mul1(PyLongObject *a, wdigit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001091{
1092 return muladd1(a, n, (digit)0);
1093}
1094
1095/* Multiply by a single digit and add a single digit, ignoring the sign. */
1096
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001097static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001098muladd1(PyLongObject *a, wdigit n, wdigit extra)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001099{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001100 Py_ssize_t size_a = ABS(a->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001101 PyLongObject *z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001102 twodigits carry = extra;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001103 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001104
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001105 if (z == NULL)
1106 return NULL;
1107 for (i = 0; i < size_a; ++i) {
1108 carry += (twodigits)a->ob_digit[i] * n;
Guido van Rossum2095d241997-04-09 19:41:24 +00001109 z->ob_digit[i] = (digit) (carry & MASK);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001110 carry >>= SHIFT;
1111 }
Guido van Rossum2095d241997-04-09 19:41:24 +00001112 z->ob_digit[i] = (digit) carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001113 return long_normalize(z);
1114}
1115
Tim Peters212e6142001-07-14 12:23:19 +00001116/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1117 in pout, and returning the remainder. pin and pout point at the LSD.
1118 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
1119 long_format, but that should be done with great care since longs are
1120 immutable. */
1121
1122static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001123inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001124{
1125 twodigits rem = 0;
1126
1127 assert(n > 0 && n <= MASK);
1128 pin += size;
1129 pout += size;
1130 while (--size >= 0) {
1131 digit hi;
1132 rem = (rem << SHIFT) + *--pin;
1133 *--pout = hi = (digit)(rem / n);
1134 rem -= hi * n;
1135 }
1136 return (digit)rem;
1137}
1138
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001139/* Divide a long integer by a digit, returning both the quotient
1140 (as function result) and the remainder (through *prem).
1141 The sign of a is ignored; n should not be zero. */
1142
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001143static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001144divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001145{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001146 const Py_ssize_t size = ABS(a->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001147 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001148
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001149 assert(n > 0 && n <= MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001150 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001151 if (z == NULL)
1152 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001153 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001154 return long_normalize(z);
1155}
1156
1157/* Convert a long int object to a string, using a given conversion base.
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001158 Return a string object.
Fred Drake121ee271999-12-23 15:41:28 +00001159 If base is 8 or 16, add the proper prefix '0' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001160
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001161static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001162long_format(PyObject *aa, int base, int addL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001163{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001164 register PyLongObject *a = (PyLongObject *)aa;
1165 PyStringObject *str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001166 Py_ssize_t i;
1167 const Py_ssize_t size_a = ABS(a->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001168 char *p;
1169 int bits;
1170 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001171
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001172 if (a == NULL || !PyLong_Check(a)) {
1173 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001174 return NULL;
1175 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001176 assert(base >= 2 && base <= 36);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001177
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001178 /* Compute a rough upper bound for the length of the string */
1179 i = base;
1180 bits = 0;
1181 while (i > 1) {
1182 ++bits;
1183 i >>= 1;
1184 }
Fred Drake121ee271999-12-23 15:41:28 +00001185 i = 5 + (addL ? 1 : 0) + (size_a*SHIFT + bits-1) / bits;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001186 str = (PyStringObject *) PyString_FromStringAndSize((char *)0, i);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001187 if (str == NULL)
1188 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001189 p = PyString_AS_STRING(str) + i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001190 *p = '\0';
Fred Drake121ee271999-12-23 15:41:28 +00001191 if (addL)
1192 *--p = 'L';
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001193 if (a->ob_size < 0)
1194 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001195
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001196 if (a->ob_size == 0) {
1197 *--p = '0';
1198 }
1199 else if ((base & (base - 1)) == 0) {
1200 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001201 twodigits accum = 0;
1202 int accumbits = 0; /* # of bits in accum */
1203 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001204 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001205 while ((i >>= 1) > 1)
1206 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001207
1208 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001209 accum |= (twodigits)a->ob_digit[i] << accumbits;
Tim Peters586b2e32001-07-15 09:11:14 +00001210 accumbits += SHIFT;
1211 assert(accumbits >= basebits);
1212 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001213 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001214 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001215 assert(p > PyString_AS_STRING(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001216 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001217 accumbits -= basebits;
1218 accum >>= basebits;
1219 } while (i < size_a-1 ? accumbits >= basebits :
1220 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001221 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001222 }
1223 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001224 /* Not 0, and base not a power of 2. Divide repeatedly by
1225 base, but for speed use the highest power of base that
1226 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001227 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001228 digit *pin = a->ob_digit;
1229 PyLongObject *scratch;
1230 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001231 digit powbase = base; /* powbase == base ** power */
1232 int power = 1;
1233 for (;;) {
1234 unsigned long newpow = powbase * (unsigned long)base;
1235 if (newpow >> SHIFT) /* doesn't fit in a digit */
1236 break;
1237 powbase = (digit)newpow;
1238 ++power;
1239 }
Tim Peters212e6142001-07-14 12:23:19 +00001240
1241 /* Get a scratch area for repeated division. */
1242 scratch = _PyLong_New(size);
1243 if (scratch == NULL) {
1244 Py_DECREF(str);
1245 return NULL;
1246 }
1247
1248 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001249 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001250 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001251 digit rem = inplace_divrem1(scratch->ob_digit,
1252 pin, size, powbase);
1253 pin = scratch->ob_digit; /* no need to use a again */
1254 if (pin[size - 1] == 0)
1255 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001256 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001257 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001258 Py_DECREF(str);
1259 return NULL;
1260 })
Tim Peters212e6142001-07-14 12:23:19 +00001261
1262 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001263 assert(ntostore > 0);
1264 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001265 digit nextrem = (digit)(rem / base);
1266 char c = (char)(rem - nextrem * base);
1267 assert(p > PyString_AS_STRING(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001268 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001269 *--p = c;
1270 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001271 --ntostore;
1272 /* Termination is a bit delicate: must not
1273 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001274 remaining quotient and rem are both 0. */
1275 } while (ntostore && (size || rem));
1276 } while (size != 0);
1277 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001278 }
1279
Guido van Rossum2c475421992-08-14 15:13:07 +00001280 if (base == 8) {
1281 if (size_a != 0)
1282 *--p = '0';
1283 }
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001284 else if (base == 16) {
1285 *--p = 'x';
1286 *--p = '0';
1287 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001288 else if (base != 10) {
1289 *--p = '#';
1290 *--p = '0' + base%10;
1291 if (base > 10)
1292 *--p = '0' + base/10;
1293 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001294 if (sign)
1295 *--p = sign;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001296 if (p != PyString_AS_STRING(str)) {
1297 char *q = PyString_AS_STRING(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001298 assert(p > q);
1299 do {
1300 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001301 q--;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001302 _PyString_Resize((PyObject **)&str,
1303 (int) (q - PyString_AS_STRING(str)));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001304 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001305 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001306}
1307
Tim Petersbf2674b2003-02-02 07:51:32 +00001308/* *str points to the first digit in a string of base base digits. base
1309 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1310 * non-digit (which may be *str!). A normalized long is returned.
1311 * The point to this routine is that it takes time linear in the number of
1312 * string characters.
1313 */
1314static PyLongObject *
1315long_from_binary_base(char **str, int base)
1316{
1317 char *p = *str;
1318 char *start = p;
1319 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001320 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001321 PyLongObject *z;
1322 twodigits accum;
1323 int bits_in_accum;
1324 digit *pdigit;
1325
1326 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1327 n = base;
1328 for (bits_per_char = -1; n; ++bits_per_char)
1329 n >>= 1;
1330 /* n <- total # of bits needed, while setting p to end-of-string */
1331 n = 0;
1332 for (;;) {
1333 int k = -1;
1334 char ch = *p;
1335
1336 if (ch <= '9')
1337 k = ch - '0';
1338 else if (ch >= 'a')
1339 k = ch - 'a' + 10;
1340 else if (ch >= 'A')
1341 k = ch - 'A' + 10;
1342 if (k < 0 || k >= base)
1343 break;
Tim Petersbf2674b2003-02-02 07:51:32 +00001344 ++p;
1345 }
1346 *str = p;
Tim Peters1a3b19a2003-02-02 17:33:53 +00001347 n = (p - start) * bits_per_char;
1348 if (n / bits_per_char != p - start) {
1349 PyErr_SetString(PyExc_ValueError,
1350 "long string too large to convert");
1351 return NULL;
1352 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001353 /* n <- # of Python digits needed, = ceiling(n/SHIFT). */
1354 n = (n + SHIFT - 1) / SHIFT;
1355 z = _PyLong_New(n);
1356 if (z == NULL)
1357 return NULL;
1358 /* Read string from right, and fill in long from left; i.e.,
1359 * from least to most significant in both.
1360 */
1361 accum = 0;
1362 bits_in_accum = 0;
1363 pdigit = z->ob_digit;
1364 while (--p >= start) {
Tim Petersc7bc0b92003-05-05 20:39:43 +00001365 int k;
1366 char ch = *p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001367
1368 if (ch <= '9')
1369 k = ch - '0';
1370 else if (ch >= 'a')
1371 k = ch - 'a' + 10;
1372 else {
1373 assert(ch >= 'A');
1374 k = ch - 'A' + 10;
1375 }
Tim Petersc7bc0b92003-05-05 20:39:43 +00001376 assert(k >= 0 && k < base);
1377 accum |= (twodigits)(k << bits_in_accum);
Tim Petersbf2674b2003-02-02 07:51:32 +00001378 bits_in_accum += bits_per_char;
1379 if (bits_in_accum >= SHIFT) {
1380 *pdigit++ = (digit)(accum & MASK);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001381 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001382 accum >>= SHIFT;
1383 bits_in_accum -= SHIFT;
1384 assert(bits_in_accum < SHIFT);
1385 }
1386 }
1387 if (bits_in_accum) {
1388 assert(bits_in_accum <= SHIFT);
1389 *pdigit++ = (digit)accum;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001390 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001391 }
1392 while (pdigit - z->ob_digit < n)
1393 *pdigit++ = 0;
1394 return long_normalize(z);
1395}
1396
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001397PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001398PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001399{
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001400 int sign = 1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001401 char *start, *orig_str = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001402 PyLongObject *z;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001403 PyObject *strobj, *strrepr;
1404 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001405
Guido van Rossum472c04f1996-12-05 21:57:21 +00001406 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001407 PyErr_SetString(PyExc_ValueError,
Fred Drake661ea262000-10-24 19:57:45 +00001408 "long() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001409 return NULL;
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 (*str == '+')
1414 ++str;
1415 else if (*str == '-') {
1416 ++str;
1417 sign = -1;
1418 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001419 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001420 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001421 if (base == 0) {
1422 if (str[0] != '0')
1423 base = 10;
1424 else if (str[1] == 'x' || str[1] == 'X')
1425 base = 16;
1426 else
1427 base = 8;
1428 }
1429 if (base == 16 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
1430 str += 2;
Guido van Rossume6762971998-06-22 03:54:46 +00001431 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001432 if ((base & (base - 1)) == 0)
1433 z = long_from_binary_base(&str, base);
1434 else {
1435 z = _PyLong_New(0);
1436 for ( ; z != NULL; ++str) {
1437 int k = -1;
1438 PyLongObject *temp;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001439
Tim Petersbf2674b2003-02-02 07:51:32 +00001440 if (*str <= '9')
1441 k = *str - '0';
1442 else if (*str >= 'a')
1443 k = *str - 'a' + 10;
1444 else if (*str >= 'A')
1445 k = *str - 'A' + 10;
1446 if (k < 0 || k >= base)
1447 break;
1448 temp = muladd1(z, (digit)base, (digit)k);
1449 Py_DECREF(z);
1450 z = temp;
1451 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001452 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001453 if (z == NULL)
1454 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001455 if (str == start)
1456 goto onError;
Guido van Rossumc6913e71991-11-19 20:26:46 +00001457 if (sign < 0 && z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001458 z->ob_size = -(z->ob_size);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001459 if (*str == 'L' || *str == 'l')
1460 str++;
1461 while (*str && isspace(Py_CHARMASK(*str)))
1462 str++;
1463 if (*str != '\0')
1464 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001465 if (pend)
1466 *pend = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001467 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001468
1469 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00001470 Py_XDECREF(z);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001471 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
1472 strobj = PyString_FromStringAndSize(orig_str, slen);
1473 if (strobj == NULL)
1474 return NULL;
1475 strrepr = PyObject_Repr(strobj);
1476 Py_DECREF(strobj);
1477 if (strrepr == NULL)
1478 return NULL;
1479 PyErr_Format(PyExc_ValueError,
1480 "invalid literal for long() with base %d: %s",
1481 base, PyString_AS_STRING(strrepr));
1482 Py_DECREF(strrepr);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001483 return NULL;
1484}
1485
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001486#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +00001487PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001488PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001489{
Walter Dörwald07e14762002-11-06 16:15:14 +00001490 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001491 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001492
Walter Dörwald07e14762002-11-06 16:15:14 +00001493 if (buffer == NULL)
1494 return NULL;
1495
1496 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1497 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001498 return NULL;
1499 }
Walter Dörwald07e14762002-11-06 16:15:14 +00001500 result = PyLong_FromString(buffer, NULL, base);
1501 PyMem_FREE(buffer);
1502 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001503}
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001504#endif
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001505
Tim Peters9f688bf2000-07-07 15:53:28 +00001506/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001507static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00001508 (PyLongObject *, PyLongObject *, PyLongObject **);
1509static PyObject *long_pos(PyLongObject *);
1510static int long_divrem(PyLongObject *, PyLongObject *,
1511 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001512
1513/* Long division with remainder, top-level routine */
1514
Guido van Rossume32e0141992-01-19 16:31:05 +00001515static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001516long_divrem(PyLongObject *a, PyLongObject *b,
1517 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001518{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001519 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001520 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001521
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001522 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001523 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +00001524 "long division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00001525 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001526 }
1527 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00001528 (size_a == size_b &&
1529 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001530 /* |a| < |b|. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001531 *pdiv = _PyLong_New(0);
1532 Py_INCREF(a);
1533 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00001534 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001535 }
1536 if (size_b == 1) {
1537 digit rem = 0;
1538 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001539 if (z == NULL)
1540 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001541 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001542 }
Guido van Rossume32e0141992-01-19 16:31:05 +00001543 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001544 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001545 if (z == NULL)
1546 return -1;
1547 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001548 /* Set the signs.
1549 The quotient z has the sign of a*b;
1550 the remainder r has the sign of a,
1551 so a = b*z + r. */
Guido van Rossume32e0141992-01-19 16:31:05 +00001552 if ((a->ob_size < 0) != (b->ob_size < 0))
1553 z->ob_size = -(z->ob_size);
1554 if (a->ob_size < 0 && (*prem)->ob_size != 0)
1555 (*prem)->ob_size = -((*prem)->ob_size);
1556 *pdiv = z;
1557 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001558}
1559
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001560/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001561
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001562static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001563x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001564{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001565 Py_ssize_t size_v = ABS(v1->ob_size), size_w = ABS(w1->ob_size);
Guido van Rossum2095d241997-04-09 19:41:24 +00001566 digit d = (digit) ((twodigits)BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001567 PyLongObject *v = mul1(v1, d);
1568 PyLongObject *w = mul1(w1, d);
1569 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001570 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001571
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001572 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001573 Py_XDECREF(v);
1574 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001575 return NULL;
1576 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001577
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001578 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001579 assert(v->ob_refcnt == 1); /* Since v will be used as accumulator! */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001580 assert(size_w == ABS(w->ob_size)); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00001581
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001582 size_v = ABS(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001583 a = _PyLong_New(size_v - size_w + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001584
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001585 for (j = size_v, k = a->ob_size-1; a != NULL && k >= 0; --j, --k) {
1586 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
1587 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001588 stwodigits carry = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001589 int i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001590
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001591 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001592 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001593 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001594 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001595 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001596 if (vj == w->ob_digit[size_w-1])
1597 q = MASK;
1598 else
1599 q = (((twodigits)vj << SHIFT) + v->ob_digit[j-1]) /
1600 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00001601
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001602 while (w->ob_digit[size_w-2]*q >
1603 ((
1604 ((twodigits)vj << SHIFT)
1605 + v->ob_digit[j-1]
1606 - q*w->ob_digit[size_w-1]
1607 ) << SHIFT)
1608 + v->ob_digit[j-2])
1609 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001610
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001611 for (i = 0; i < size_w && i+k < size_v; ++i) {
1612 twodigits z = w->ob_digit[i] * q;
Guido van Rossum2095d241997-04-09 19:41:24 +00001613 digit zz = (digit) (z >> SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001614 carry += v->ob_digit[i+k] - z
1615 + ((twodigits)zz << SHIFT);
Jeremy Hyltonfc61f9a2003-05-01 21:31:53 +00001616 v->ob_digit[i+k] = (digit)(carry & MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00001617 carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
1618 carry, SHIFT);
1619 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001620 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001621
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001622 if (i+k < size_v) {
1623 carry += v->ob_digit[i+k];
1624 v->ob_digit[i+k] = 0;
1625 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001626
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001627 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00001628 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001629 else {
1630 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00001631 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001632 carry = 0;
1633 for (i = 0; i < size_w && i+k < size_v; ++i) {
1634 carry += v->ob_digit[i+k] + w->ob_digit[i];
Jeremy Hyltonfc61f9a2003-05-01 21:31:53 +00001635 v->ob_digit[i+k] = (digit)(carry & MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00001636 carry = Py_ARITHMETIC_RIGHT_SHIFT(
1637 BASE_TWODIGITS_TYPE,
1638 carry, SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001639 }
1640 }
1641 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00001642
Guido van Rossumc206c761995-01-10 15:23:19 +00001643 if (a == NULL)
1644 *prem = NULL;
1645 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00001646 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00001647 *prem = divrem1(v, d, &d);
1648 /* d receives the (unused) remainder */
1649 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001650 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00001651 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00001652 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001653 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001654 Py_DECREF(v);
1655 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001656 return a;
1657}
1658
1659/* Methods */
1660
1661static void
Tim Peters9f688bf2000-07-07 15:53:28 +00001662long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001663{
Guido van Rossum9475a232001-10-05 20:51:39 +00001664 v->ob_type->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001665}
1666
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001667static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001668long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001669{
Fred Drake121ee271999-12-23 15:41:28 +00001670 return long_format(v, 10, 1);
1671}
1672
1673static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001674long_str(PyObject *v)
Fred Drake121ee271999-12-23 15:41:28 +00001675{
1676 return long_format(v, 10, 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001677}
1678
1679static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001680long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001681{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001682 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001683
Guido van Rossumc6913e71991-11-19 20:26:46 +00001684 if (a->ob_size != b->ob_size) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001685 if (ABS(a->ob_size) == 0 && ABS(b->ob_size) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00001686 sign = 0;
1687 else
1688 sign = a->ob_size - b->ob_size;
1689 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001690 else {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001691 Py_ssize_t i = ABS(a->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001692 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
1693 ;
1694 if (i < 0)
1695 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00001696 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001697 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00001698 if (a->ob_size < 0)
1699 sign = -sign;
1700 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001701 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001702 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001703}
1704
Guido van Rossum9bfef441993-03-29 10:43:31 +00001705static long
Tim Peters9f688bf2000-07-07 15:53:28 +00001706long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001707{
1708 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001709 Py_ssize_t i;
1710 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001711
1712 /* This is designed so that Python ints and longs with the
1713 same value hash to the same value, otherwise comparisons
1714 of mapping keys will turn out weird */
1715 i = v->ob_size;
1716 sign = 1;
1717 x = 0;
1718 if (i < 0) {
1719 sign = -1;
1720 i = -(i);
1721 }
Neal Norwitzd5a65a72003-02-23 23:11:41 +00001722#define LONG_BIT_SHIFT (8*sizeof(long) - SHIFT)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001723 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00001724 /* Force a native long #-bits (32 or 64) circular shift */
1725 x = ((x << SHIFT) & ~MASK) | ((x >> LONG_BIT_SHIFT) & MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001726 x += v->ob_digit[i];
1727 }
Neal Norwitzd5a65a72003-02-23 23:11:41 +00001728#undef LONG_BIT_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00001729 x = x * sign;
1730 if (x == -1)
1731 x = -2;
1732 return x;
1733}
1734
1735
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001736/* Add the absolute values of two long integers. */
1737
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001738static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001739x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001740{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001741 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001742 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001743 int i;
1744 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00001745
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001746 /* Ensure a is the larger of the two: */
1747 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001748 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00001749 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001750 size_a = size_b;
1751 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001752 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001753 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001754 if (z == NULL)
1755 return NULL;
1756 for (i = 0; i < size_b; ++i) {
1757 carry += a->ob_digit[i] + b->ob_digit[i];
1758 z->ob_digit[i] = carry & MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001759 carry >>= SHIFT;
1760 }
1761 for (; i < size_a; ++i) {
1762 carry += a->ob_digit[i];
1763 z->ob_digit[i] = carry & MASK;
1764 carry >>= SHIFT;
1765 }
1766 z->ob_digit[i] = carry;
1767 return long_normalize(z);
1768}
1769
1770/* Subtract the absolute values of two integers. */
1771
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001772static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001773x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001774{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001775 Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001776 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001777 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001778 int sign = 1;
1779 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00001780
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001781 /* Ensure a is the larger of the two: */
1782 if (size_a < size_b) {
1783 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001784 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00001785 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001786 size_a = size_b;
1787 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001788 }
1789 else if (size_a == size_b) {
1790 /* Find highest digit where a and b differ: */
1791 i = size_a;
1792 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
1793 ;
1794 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001795 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001796 if (a->ob_digit[i] < b->ob_digit[i]) {
1797 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001798 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001799 }
1800 size_a = size_b = i+1;
1801 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001802 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001803 if (z == NULL)
1804 return NULL;
1805 for (i = 0; i < size_b; ++i) {
1806 /* The following assumes unsigned arithmetic
1807 works module 2**N for some N>SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001808 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001809 z->ob_digit[i] = borrow & MASK;
1810 borrow >>= SHIFT;
1811 borrow &= 1; /* Keep only one sign bit */
1812 }
1813 for (; i < size_a; ++i) {
1814 borrow = a->ob_digit[i] - borrow;
1815 z->ob_digit[i] = borrow & MASK;
1816 borrow >>= SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00001817 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001818 }
1819 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00001820 if (sign < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001821 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001822 return long_normalize(z);
1823}
1824
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001825static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00001826long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001827{
Neil Schemenauerba872e22001-01-04 01:46:03 +00001828 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00001829
Neil Schemenauerba872e22001-01-04 01:46:03 +00001830 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
1831
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001832 if (a->ob_size < 0) {
1833 if (b->ob_size < 0) {
1834 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00001835 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001836 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001837 }
1838 else
1839 z = x_sub(b, a);
1840 }
1841 else {
1842 if (b->ob_size < 0)
1843 z = x_sub(a, b);
1844 else
1845 z = x_add(a, b);
1846 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00001847 Py_DECREF(a);
1848 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001849 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001850}
1851
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001852static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00001853long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001854{
Neil Schemenauerba872e22001-01-04 01:46:03 +00001855 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001856
Neil Schemenauerba872e22001-01-04 01:46:03 +00001857 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
1858
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001859 if (a->ob_size < 0) {
1860 if (b->ob_size < 0)
1861 z = x_sub(a, b);
1862 else
1863 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00001864 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001865 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001866 }
1867 else {
1868 if (b->ob_size < 0)
1869 z = x_add(a, b);
1870 else
1871 z = x_sub(a, b);
1872 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00001873 Py_DECREF(a);
1874 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001875 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001876}
1877
Tim Peters5af4e6c2002-08-12 02:31:19 +00001878/* Grade school multiplication, ignoring the signs.
1879 * Returns the absolute value of the product, or NULL if error.
1880 */
1881static PyLongObject *
1882x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001883{
Tim Peters5af4e6c2002-08-12 02:31:19 +00001884 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001885 Py_ssize_t size_a = ABS(a->ob_size);
1886 Py_ssize_t size_b = ABS(b->ob_size);
1887 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00001888
Tim Peters5af4e6c2002-08-12 02:31:19 +00001889 z = _PyLong_New(size_a + size_b);
1890 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001891 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001892
1893 memset(z->ob_digit, 0, z->ob_size * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00001894 if (a == b) {
1895 /* Efficient squaring per HAC, Algorithm 14.16:
1896 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
1897 * Gives slightly less than a 2x speedup when a == b,
1898 * via exploiting that each entry in the multiplication
1899 * pyramid appears twice (except for the size_a squares).
1900 */
1901 for (i = 0; i < size_a; ++i) {
1902 twodigits carry;
1903 twodigits f = a->ob_digit[i];
1904 digit *pz = z->ob_digit + (i << 1);
1905 digit *pa = a->ob_digit + i + 1;
1906 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001907
Tim Peters0973b992004-08-29 22:16:50 +00001908 SIGCHECK({
1909 Py_DECREF(z);
1910 return NULL;
1911 })
1912
1913 carry = *pz + f * f;
1914 *pz++ = (digit)(carry & MASK);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001915 carry >>= SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00001916 assert(carry <= MASK);
1917
1918 /* Now f is added in twice in each column of the
1919 * pyramid it appears. Same as adding f<<1 once.
1920 */
1921 f <<= 1;
1922 while (pa < paend) {
1923 carry += *pz + *pa++ * f;
1924 *pz++ = (digit)(carry & MASK);
1925 carry >>= SHIFT;
1926 assert(carry <= (MASK << 1));
1927 }
1928 if (carry) {
1929 carry += *pz;
1930 *pz++ = (digit)(carry & MASK);
1931 carry >>= SHIFT;
1932 }
1933 if (carry)
1934 *pz += (digit)(carry & MASK);
1935 assert((carry >> SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001936 }
Tim Peters0973b992004-08-29 22:16:50 +00001937 }
1938 else { /* a is not the same as b -- gradeschool long mult */
1939 for (i = 0; i < size_a; ++i) {
1940 twodigits carry = 0;
1941 twodigits f = a->ob_digit[i];
1942 digit *pz = z->ob_digit + i;
1943 digit *pb = b->ob_digit;
1944 digit *pbend = b->ob_digit + size_b;
1945
1946 SIGCHECK({
1947 Py_DECREF(z);
1948 return NULL;
1949 })
1950
1951 while (pb < pbend) {
1952 carry += *pz + *pb++ * f;
1953 *pz++ = (digit)(carry & MASK);
1954 carry >>= SHIFT;
1955 assert(carry <= MASK);
1956 }
1957 if (carry)
1958 *pz += (digit)(carry & MASK);
1959 assert((carry >> SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001960 }
1961 }
Tim Peters44121a62002-08-12 06:17:58 +00001962 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001963}
1964
1965/* A helper for Karatsuba multiplication (k_mul).
1966 Takes a long "n" and an integer "size" representing the place to
1967 split, and sets low and high such that abs(n) == (high << size) + low,
1968 viewing the shift as being by digits. The sign bit is ignored, and
1969 the return values are >= 0.
1970 Returns 0 on success, -1 on failure.
1971*/
1972static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001973kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00001974{
1975 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001976 Py_ssize_t size_lo, size_hi;
1977 const Py_ssize_t size_n = ABS(n->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001978
1979 size_lo = MIN(size_n, size);
1980 size_hi = size_n - size_lo;
1981
1982 if ((hi = _PyLong_New(size_hi)) == NULL)
1983 return -1;
1984 if ((lo = _PyLong_New(size_lo)) == NULL) {
1985 Py_DECREF(hi);
1986 return -1;
1987 }
1988
1989 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
1990 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
1991
1992 *high = long_normalize(hi);
1993 *low = long_normalize(lo);
1994 return 0;
1995}
1996
Tim Peters60004642002-08-12 22:01:34 +00001997static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
1998
Tim Peters5af4e6c2002-08-12 02:31:19 +00001999/* Karatsuba multiplication. Ignores the input signs, and returns the
2000 * absolute value of the product (or NULL if error).
2001 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2002 */
2003static PyLongObject *
2004k_mul(PyLongObject *a, PyLongObject *b)
2005{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002006 Py_ssize_t asize = ABS(a->ob_size);
2007 Py_ssize_t bsize = ABS(b->ob_size);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002008 PyLongObject *ah = NULL;
2009 PyLongObject *al = NULL;
2010 PyLongObject *bh = NULL;
2011 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002012 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002013 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002014 Py_ssize_t shift; /* the number of digits we split off */
2015 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002016
Tim Peters5af4e6c2002-08-12 02:31:19 +00002017 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2018 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2019 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002020 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002021 * By picking X to be a power of 2, "*X" is just shifting, and it's
2022 * been reduced to 3 multiplies on numbers half the size.
2023 */
2024
Tim Petersfc07e562002-08-12 02:54:10 +00002025 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002026 * is largest.
2027 */
Tim Peters738eda72002-08-12 15:08:20 +00002028 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002029 t1 = a;
2030 a = b;
2031 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002032
2033 i = asize;
2034 asize = bsize;
2035 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002036 }
2037
2038 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002039 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2040 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002041 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002042 return _PyLong_New(0);
2043 else
2044 return x_mul(a, b);
2045 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002046
Tim Peters60004642002-08-12 22:01:34 +00002047 /* If a is small compared to b, splitting on b gives a degenerate
2048 * case with ah==0, and Karatsuba may be (even much) less efficient
2049 * than "grade school" then. However, we can still win, by viewing
2050 * b as a string of "big digits", each of width a->ob_size. That
2051 * leads to a sequence of balanced calls to k_mul.
2052 */
2053 if (2 * asize <= bsize)
2054 return k_lopsided_mul(a, b);
2055
Tim Petersd6974a52002-08-13 20:37:51 +00002056 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002057 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002058 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Tim Petersd6974a52002-08-13 20:37:51 +00002059 assert(ah->ob_size > 0); /* the split isn't degenerate */
2060
Tim Peters0973b992004-08-29 22:16:50 +00002061 if (a == b) {
2062 bh = ah;
2063 bl = al;
2064 Py_INCREF(bh);
2065 Py_INCREF(bl);
2066 }
2067 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002068
Tim Petersd64c1de2002-08-12 17:36:03 +00002069 /* The plan:
2070 * 1. Allocate result space (asize + bsize digits: that's always
2071 * enough).
2072 * 2. Compute ah*bh, and copy into result at 2*shift.
2073 * 3. Compute al*bl, and copy into result at 0. Note that this
2074 * can't overlap with #2.
2075 * 4. Subtract al*bl from the result, starting at shift. This may
2076 * underflow (borrow out of the high digit), but we don't care:
2077 * we're effectively doing unsigned arithmetic mod
2078 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2079 * borrows and carries out of the high digit can be ignored.
2080 * 5. Subtract ah*bh from the result, starting at shift.
2081 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2082 * at shift.
2083 */
2084
2085 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002086 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002087 if (ret == NULL) goto fail;
2088#ifdef Py_DEBUG
2089 /* Fill with trash, to catch reference to uninitialized digits. */
2090 memset(ret->ob_digit, 0xDF, ret->ob_size * sizeof(digit));
2091#endif
Tim Peters44121a62002-08-12 06:17:58 +00002092
Tim Petersd64c1de2002-08-12 17:36:03 +00002093 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002094 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
2095 assert(t1->ob_size >= 0);
2096 assert(2*shift + t1->ob_size <= ret->ob_size);
2097 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
2098 t1->ob_size * sizeof(digit));
2099
2100 /* Zero-out the digits higher than the ah*bh copy. */
2101 i = ret->ob_size - 2*shift - t1->ob_size;
Tim Peters44121a62002-08-12 06:17:58 +00002102 if (i)
Tim Peters738eda72002-08-12 15:08:20 +00002103 memset(ret->ob_digit + 2*shift + t1->ob_size, 0,
Tim Peters44121a62002-08-12 06:17:58 +00002104 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002105
Tim Petersd64c1de2002-08-12 17:36:03 +00002106 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002107 if ((t2 = k_mul(al, bl)) == NULL) {
2108 Py_DECREF(t1);
2109 goto fail;
2110 }
2111 assert(t2->ob_size >= 0);
2112 assert(t2->ob_size <= 2*shift); /* no overlap with high digits */
2113 memcpy(ret->ob_digit, t2->ob_digit, t2->ob_size * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002114
2115 /* Zero out remaining digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002116 i = 2*shift - t2->ob_size; /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002117 if (i)
Tim Peters738eda72002-08-12 15:08:20 +00002118 memset(ret->ob_digit + t2->ob_size, 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002119
Tim Petersd64c1de2002-08-12 17:36:03 +00002120 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2121 * because it's fresher in cache.
2122 */
Tim Peters738eda72002-08-12 15:08:20 +00002123 i = ret->ob_size - shift; /* # digits after shift */
Tim Petersd64c1de2002-08-12 17:36:03 +00002124 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, t2->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002125 Py_DECREF(t2);
2126
Tim Petersd64c1de2002-08-12 17:36:03 +00002127 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, t1->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002128 Py_DECREF(t1);
2129
Tim Petersd64c1de2002-08-12 17:36:03 +00002130 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002131 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2132 Py_DECREF(ah);
2133 Py_DECREF(al);
2134 ah = al = NULL;
2135
Tim Peters0973b992004-08-29 22:16:50 +00002136 if (a == b) {
2137 t2 = t1;
2138 Py_INCREF(t2);
2139 }
2140 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002141 Py_DECREF(t1);
2142 goto fail;
2143 }
2144 Py_DECREF(bh);
2145 Py_DECREF(bl);
2146 bh = bl = NULL;
2147
Tim Peters738eda72002-08-12 15:08:20 +00002148 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002149 Py_DECREF(t1);
2150 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002151 if (t3 == NULL) goto fail;
Tim Peters547607c2002-08-12 19:43:49 +00002152 assert(t3->ob_size >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002153
Tim Petersd6974a52002-08-13 20:37:51 +00002154 /* Add t3. It's not obvious why we can't run out of room here.
2155 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002156 */
Tim Petersd64c1de2002-08-12 17:36:03 +00002157 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, t3->ob_size);
Tim Peters738eda72002-08-12 15:08:20 +00002158 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002159
Tim Peters5af4e6c2002-08-12 02:31:19 +00002160 return long_normalize(ret);
2161
2162 fail:
2163 Py_XDECREF(ret);
2164 Py_XDECREF(ah);
2165 Py_XDECREF(al);
2166 Py_XDECREF(bh);
2167 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002168 return NULL;
2169}
2170
Tim Petersd6974a52002-08-13 20:37:51 +00002171/* (*) Why adding t3 can't "run out of room" above.
2172
Tim Petersab86c2b2002-08-15 20:06:00 +00002173Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2174to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002175
Tim Petersab86c2b2002-08-15 20:06:00 +000021761. For any integer i, i = c(i/2) + f(i/2). In particular,
2177 bsize = c(bsize/2) + f(bsize/2).
21782. shift = f(bsize/2)
21793. asize <= bsize
21804. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2181 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002182
Tim Petersab86c2b2002-08-15 20:06:00 +00002183We allocated asize + bsize result digits, and add t3 into them at an offset
2184of shift. This leaves asize+bsize-shift allocated digit positions for t3
2185to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2186asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002187
Tim Petersab86c2b2002-08-15 20:06:00 +00002188bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2189at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002190
Tim Petersab86c2b2002-08-15 20:06:00 +00002191If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2192digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2193most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002194
Tim Petersab86c2b2002-08-15 20:06:00 +00002195The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002196
Tim Petersab86c2b2002-08-15 20:06:00 +00002197 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002198
Tim Petersab86c2b2002-08-15 20:06:00 +00002199and we have asize + c(bsize/2) available digit positions. We need to show
2200this is always enough. An instance of c(bsize/2) cancels out in both, so
2201the question reduces to whether asize digits is enough to hold
2202(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2203then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2204asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
2205digit is enough to hold 2 bits. This is so since SHIFT=15 >= 2. If
2206asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002207c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2208is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2209bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002210
Tim Peters48d52c02002-08-14 17:07:32 +00002211Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2212clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2213ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002214*/
2215
Tim Peters60004642002-08-12 22:01:34 +00002216/* b has at least twice the digits of a, and a is big enough that Karatsuba
2217 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2218 * of slices, each with a->ob_size digits, and multiply the slices by a,
2219 * one at a time. This gives k_mul balanced inputs to work with, and is
2220 * also cache-friendly (we compute one double-width slice of the result
2221 * at a time, then move on, never bactracking except for the helpful
2222 * single-width slice overlap between successive partial sums).
2223 */
2224static PyLongObject *
2225k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2226{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002227 const Py_ssize_t asize = ABS(a->ob_size);
2228 Py_ssize_t bsize = ABS(b->ob_size);
2229 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002230 PyLongObject *ret;
2231 PyLongObject *bslice = NULL;
2232
2233 assert(asize > KARATSUBA_CUTOFF);
2234 assert(2 * asize <= bsize);
2235
2236 /* Allocate result space, and zero it out. */
2237 ret = _PyLong_New(asize + bsize);
2238 if (ret == NULL)
2239 return NULL;
2240 memset(ret->ob_digit, 0, ret->ob_size * sizeof(digit));
2241
2242 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002243 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002244 if (bslice == NULL)
2245 goto fail;
2246
2247 nbdone = 0;
2248 while (bsize > 0) {
2249 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002250 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002251
2252 /* Multiply the next slice of b by a. */
2253 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2254 nbtouse * sizeof(digit));
2255 bslice->ob_size = nbtouse;
2256 product = k_mul(a, bslice);
2257 if (product == NULL)
2258 goto fail;
2259
2260 /* Add into result. */
2261 (void)v_iadd(ret->ob_digit + nbdone, ret->ob_size - nbdone,
2262 product->ob_digit, product->ob_size);
2263 Py_DECREF(product);
2264
2265 bsize -= nbtouse;
2266 nbdone += nbtouse;
2267 }
2268
2269 Py_DECREF(bslice);
2270 return long_normalize(ret);
2271
2272 fail:
2273 Py_DECREF(ret);
2274 Py_XDECREF(bslice);
2275 return NULL;
2276}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002277
2278static PyObject *
2279long_mul(PyLongObject *v, PyLongObject *w)
2280{
2281 PyLongObject *a, *b, *z;
2282
2283 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002284 Py_INCREF(Py_NotImplemented);
2285 return Py_NotImplemented;
2286 }
2287
Tim Petersd64c1de2002-08-12 17:36:03 +00002288 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002289 /* Negate if exactly one of the inputs is negative. */
2290 if (((a->ob_size ^ b->ob_size) < 0) && z)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002291 z->ob_size = -(z->ob_size);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002292 Py_DECREF(a);
2293 Py_DECREF(b);
Tim Peters9973d742002-08-15 19:41:06 +00002294 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002295}
2296
Guido van Rossume32e0141992-01-19 16:31:05 +00002297/* The / and % operators are now defined in terms of divmod().
2298 The expression a mod b has the value a - b*floor(a/b).
2299 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002300 |a| by |b|, with the sign of a. This is also expressed
2301 as a - b*trunc(a/b), if trunc truncates towards zero.
2302 Some examples:
2303 a b a rem b a mod b
2304 13 10 3 3
2305 -13 10 -3 7
2306 13 -10 3 -7
2307 -13 -10 -3 -3
2308 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002309 have different signs. We then subtract one from the 'div'
2310 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002311
Tim Peters47e52ee2004-08-30 02:44:38 +00002312/* Compute
2313 * *pdiv, *pmod = divmod(v, w)
2314 * NULL can be passed for pdiv or pmod, in which case that part of
2315 * the result is simply thrown away. The caller owns a reference to
2316 * each of these it requests (does not pass NULL for).
2317 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002318static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002319l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002320 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002321{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002322 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002323
Guido van Rossume32e0141992-01-19 16:31:05 +00002324 if (long_divrem(v, w, &div, &mod) < 0)
2325 return -1;
Guido van Rossum472c04f1996-12-05 21:57:21 +00002326 if ((mod->ob_size < 0 && w->ob_size > 0) ||
2327 (mod->ob_size > 0 && w->ob_size < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002328 PyLongObject *temp;
2329 PyLongObject *one;
2330 temp = (PyLongObject *) long_add(mod, w);
2331 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002332 mod = temp;
2333 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002334 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002335 return -1;
2336 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002337 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002338 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002339 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2340 Py_DECREF(mod);
2341 Py_DECREF(div);
2342 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002343 return -1;
2344 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002345 Py_DECREF(one);
2346 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002347 div = temp;
2348 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002349 if (pdiv != NULL)
2350 *pdiv = div;
2351 else
2352 Py_DECREF(div);
2353
2354 if (pmod != NULL)
2355 *pmod = mod;
2356 else
2357 Py_DECREF(mod);
2358
Guido van Rossume32e0141992-01-19 16:31:05 +00002359 return 0;
2360}
2361
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002362static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002363long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002364{
Tim Peters47e52ee2004-08-30 02:44:38 +00002365 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002366
2367 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002368 if (l_divmod(a, b, &div, NULL) < 0)
2369 div = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002370 Py_DECREF(a);
2371 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002372 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002373}
2374
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002375static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00002376long_true_divide(PyObject *v, PyObject *w)
2377{
Tim Peterse2a60002001-09-04 06:17:36 +00002378 PyLongObject *a, *b;
2379 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002380 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002381
2382 CONVERT_BINOP(v, w, &a, &b);
2383 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2384 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002385 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
2386 Py_DECREF(a);
2387 Py_DECREF(b);
2388 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002389 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002390 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2391 but should really be set correctly after sucessful calls to
2392 _PyLong_AsScaledDouble() */
2393 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002394
2395 if (bd == 0.0) {
2396 PyErr_SetString(PyExc_ZeroDivisionError,
2397 "long division or modulo by zero");
2398 return NULL;
2399 }
2400
2401 /* True value is very close to ad/bd * 2**(SHIFT*(aexp-bexp)) */
2402 ad /= bd; /* overflow/underflow impossible here */
2403 aexp -= bexp;
2404 if (aexp > INT_MAX / SHIFT)
2405 goto overflow;
Tim Peterse56ed9b2001-09-06 21:59:14 +00002406 else if (aexp < -(INT_MAX / SHIFT))
2407 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002408 errno = 0;
2409 ad = ldexp(ad, aexp * SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002410 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002411 goto overflow;
2412 return PyFloat_FromDouble(ad);
2413
2414overflow:
2415 PyErr_SetString(PyExc_OverflowError,
2416 "long/long too large for a float");
2417 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002418
Tim Peters20dab9f2001-09-04 05:31:47 +00002419}
2420
2421static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002422long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002423{
Tim Peters47e52ee2004-08-30 02:44:38 +00002424 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002425
2426 CONVERT_BINOP(v, w, &a, &b);
2427
Tim Peters47e52ee2004-08-30 02:44:38 +00002428 if (l_divmod(a, b, NULL, &mod) < 0)
2429 mod = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002430 Py_DECREF(a);
2431 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002432 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002433}
2434
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002435static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002436long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002437{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002438 PyLongObject *a, *b, *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002439 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002440
2441 CONVERT_BINOP(v, w, &a, &b);
2442
2443 if (l_divmod(a, b, &div, &mod) < 0) {
2444 Py_DECREF(a);
2445 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002446 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002447 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002448 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002449 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002450 PyTuple_SetItem(z, 0, (PyObject *) div);
2451 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002452 }
2453 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002454 Py_DECREF(div);
2455 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002456 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002457 Py_DECREF(a);
2458 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002459 return z;
2460}
2461
Tim Peters47e52ee2004-08-30 02:44:38 +00002462/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002463static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002464long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002465{
Tim Peters47e52ee2004-08-30 02:44:38 +00002466 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
2467 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002468
Tim Peters47e52ee2004-08-30 02:44:38 +00002469 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002470 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00002471 PyLongObject *temp = NULL;
2472
2473 /* 5-ary values. If the exponent is large enough, table is
2474 * precomputed so that table[i] == a**i % c for i in range(32).
2475 */
2476 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2477 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2478
2479 /* a, b, c = v, w, x */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002480 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002481 if (PyLong_Check(x)) {
2482 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002483 Py_INCREF(x);
2484 }
Tim Petersde7990b2005-07-17 23:45:23 +00002485 else if (PyInt_Check(x)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002486 c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x));
Tim Petersde7990b2005-07-17 23:45:23 +00002487 if (c == NULL)
2488 goto Error;
2489 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002490 else if (x == Py_None)
2491 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002492 else {
2493 Py_DECREF(a);
2494 Py_DECREF(b);
2495 Py_INCREF(Py_NotImplemented);
2496 return Py_NotImplemented;
2497 }
Tim Peters4c483c42001-09-05 06:24:58 +00002498
Tim Peters47e52ee2004-08-30 02:44:38 +00002499 if (b->ob_size < 0) { /* if exponent is negative */
2500 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00002501 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00002502 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00002503 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00002504 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002505 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00002506 /* else return a float. This works because we know
2507 that this calls float_pow() which converts its
2508 arguments to double. */
2509 Py_DECREF(a);
2510 Py_DECREF(b);
2511 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002512 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002513 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002514
2515 if (c) {
2516 /* if modulus == 0:
2517 raise ValueError() */
2518 if (c->ob_size == 0) {
2519 PyErr_SetString(PyExc_ValueError,
2520 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00002521 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002522 }
2523
2524 /* if modulus < 0:
2525 negativeOutput = True
2526 modulus = -modulus */
2527 if (c->ob_size < 0) {
2528 negativeOutput = 1;
2529 temp = (PyLongObject *)_PyLong_Copy(c);
2530 if (temp == NULL)
2531 goto Error;
2532 Py_DECREF(c);
2533 c = temp;
2534 temp = NULL;
2535 c->ob_size = - c->ob_size;
2536 }
2537
2538 /* if modulus == 1:
2539 return 0 */
2540 if ((c->ob_size == 1) && (c->ob_digit[0] == 1)) {
2541 z = (PyLongObject *)PyLong_FromLong(0L);
2542 goto Done;
2543 }
2544
2545 /* if base < 0:
2546 base = base % modulus
2547 Having the base positive just makes things easier. */
2548 if (a->ob_size < 0) {
2549 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00002550 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002551 Py_DECREF(a);
2552 a = temp;
2553 temp = NULL;
2554 }
2555 }
2556
2557 /* At this point a, b, and c are guaranteed non-negative UNLESS
2558 c is NULL, in which case a may be negative. */
2559
2560 z = (PyLongObject *)PyLong_FromLong(1L);
2561 if (z == NULL)
2562 goto Error;
2563
2564 /* Perform a modular reduction, X = X % c, but leave X alone if c
2565 * is NULL.
2566 */
2567#define REDUCE(X) \
2568 if (c != NULL) { \
2569 if (l_divmod(X, c, NULL, &temp) < 0) \
2570 goto Error; \
2571 Py_XDECREF(X); \
2572 X = temp; \
2573 temp = NULL; \
2574 }
2575
2576 /* Multiply two values, then reduce the result:
2577 result = X*Y % c. If c is NULL, skip the mod. */
2578#define MULT(X, Y, result) \
2579{ \
2580 temp = (PyLongObject *)long_mul(X, Y); \
2581 if (temp == NULL) \
2582 goto Error; \
2583 Py_XDECREF(result); \
2584 result = temp; \
2585 temp = NULL; \
2586 REDUCE(result) \
2587}
2588
2589 if (b->ob_size <= FIVEARY_CUTOFF) {
2590 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
2591 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
2592 for (i = b->ob_size - 1; i >= 0; --i) {
2593 digit bi = b->ob_digit[i];
2594
2595 for (j = 1 << (SHIFT-1); j != 0; j >>= 1) {
2596 MULT(z, z, z)
2597 if (bi & j)
2598 MULT(z, a, z)
2599 }
2600 }
2601 }
2602 else {
2603 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
2604 Py_INCREF(z); /* still holds 1L */
2605 table[0] = z;
2606 for (i = 1; i < 32; ++i)
2607 MULT(table[i-1], a, table[i])
2608
2609 for (i = b->ob_size - 1; i >= 0; --i) {
2610 const digit bi = b->ob_digit[i];
2611
2612 for (j = SHIFT - 5; j >= 0; j -= 5) {
2613 const int index = (bi >> j) & 0x1f;
2614 for (k = 0; k < 5; ++k)
2615 MULT(z, z, z)
2616 if (index)
2617 MULT(z, table[index], z)
2618 }
2619 }
2620 }
2621
2622 if (negativeOutput && (z->ob_size != 0)) {
2623 temp = (PyLongObject *)long_sub(z, c);
2624 if (temp == NULL)
2625 goto Error;
2626 Py_DECREF(z);
2627 z = temp;
2628 temp = NULL;
2629 }
2630 goto Done;
2631
2632 Error:
2633 if (z != NULL) {
2634 Py_DECREF(z);
2635 z = NULL;
2636 }
2637 /* fall through */
2638 Done:
Tim Peters47e52ee2004-08-30 02:44:38 +00002639 if (b->ob_size > FIVEARY_CUTOFF) {
2640 for (i = 0; i < 32; ++i)
2641 Py_XDECREF(table[i]);
2642 }
Tim Petersde7990b2005-07-17 23:45:23 +00002643 Py_DECREF(a);
2644 Py_DECREF(b);
2645 Py_XDECREF(c);
2646 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002647 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002648}
2649
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002650static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002651long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002652{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002653 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002654 PyLongObject *x;
2655 PyLongObject *w;
2656 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002657 if (w == NULL)
2658 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002659 x = (PyLongObject *) long_add(v, w);
2660 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002661 if (x == NULL)
2662 return NULL;
Tim Peters40c397d2001-09-11 23:24:22 +00002663 x->ob_size = -(x->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002664 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002665}
2666
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002667static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002668long_pos(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002669{
Tim Peters69c2de32001-09-11 22:31:33 +00002670 if (PyLong_CheckExact(v)) {
2671 Py_INCREF(v);
2672 return (PyObject *)v;
2673 }
2674 else
2675 return _PyLong_Copy(v);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002676}
2677
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002678static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002679long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002680{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002681 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002682 if (v->ob_size == 0 && PyLong_CheckExact(v)) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002683 /* -0 == 0 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002684 Py_INCREF(v);
2685 return (PyObject *) v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002686 }
Tim Peters69c2de32001-09-11 22:31:33 +00002687 z = (PyLongObject *)_PyLong_Copy(v);
2688 if (z != NULL)
2689 z->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002690 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002691}
2692
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002693static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002694long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002695{
2696 if (v->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002697 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00002698 else
2699 return long_pos(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002700}
2701
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002702static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002703long_nonzero(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002704{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002705 return ABS(v->ob_size) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002706}
2707
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002708static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002709long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002710{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002711 PyLongObject *a, *b;
2712 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002713 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002714 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002715 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002716
Neil Schemenauerba872e22001-01-04 01:46:03 +00002717 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2718
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002719 if (a->ob_size < 0) {
2720 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002721 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002722 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002723 if (a1 == NULL)
2724 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002725 a2 = (PyLongObject *) long_rshift(a1, b);
2726 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002727 if (a2 == NULL)
2728 goto rshift_error;
2729 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002730 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002731 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002732 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002733
Neil Schemenauerba872e22001-01-04 01:46:03 +00002734 shiftby = PyLong_AsLong((PyObject *)b);
2735 if (shiftby == -1L && PyErr_Occurred())
2736 goto rshift_error;
2737 if (shiftby < 0) {
2738 PyErr_SetString(PyExc_ValueError,
2739 "negative shift count");
2740 goto rshift_error;
2741 }
2742 wordshift = shiftby / SHIFT;
2743 newsize = ABS(a->ob_size) - wordshift;
2744 if (newsize <= 0) {
2745 z = _PyLong_New(0);
2746 Py_DECREF(a);
2747 Py_DECREF(b);
2748 return (PyObject *)z;
2749 }
2750 loshift = shiftby % SHIFT;
2751 hishift = SHIFT - loshift;
2752 lomask = ((digit)1 << hishift) - 1;
2753 himask = MASK ^ lomask;
2754 z = _PyLong_New(newsize);
2755 if (z == NULL)
2756 goto rshift_error;
2757 if (a->ob_size < 0)
2758 z->ob_size = -(z->ob_size);
2759 for (i = 0, j = wordshift; i < newsize; i++, j++) {
2760 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
2761 if (i+1 < newsize)
2762 z->ob_digit[i] |=
2763 (a->ob_digit[j+1] << hishift) & himask;
2764 }
2765 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002766 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002767rshift_error:
2768 Py_DECREF(a);
2769 Py_DECREF(b);
2770 return (PyObject *) z;
2771
Guido van Rossumc6913e71991-11-19 20:26:46 +00002772}
2773
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002774static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002775long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002776{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002777 /* This version due to Tim Peters */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002778 PyLongObject *a, *b;
2779 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002780 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002781 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002782 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002783
Neil Schemenauerba872e22001-01-04 01:46:03 +00002784 CONVERT_BINOP(v, w, &a, &b);
2785
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002786 shiftby = PyLong_AsLong((PyObject *)b);
2787 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00002788 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002789 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002790 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00002791 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002792 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002793 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002794 PyErr_SetString(PyExc_ValueError,
2795 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00002796 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002797 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002798 /* wordshift, remshift = divmod(shiftby, SHIFT) */
2799 wordshift = (int)shiftby / SHIFT;
2800 remshift = (int)shiftby - wordshift * SHIFT;
2801
2802 oldsize = ABS(a->ob_size);
2803 newsize = oldsize + wordshift;
2804 if (remshift)
2805 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002806 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002807 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002808 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002809 if (a->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002810 z->ob_size = -(z->ob_size);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002811 for (i = 0; i < wordshift; i++)
2812 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002813 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002814 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00002815 accum |= (twodigits)a->ob_digit[j] << remshift;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002816 z->ob_digit[i] = (digit)(accum & MASK);
2817 accum >>= SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002818 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002819 if (remshift)
2820 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002821 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00002822 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002823 z = long_normalize(z);
2824lshift_error:
2825 Py_DECREF(a);
2826 Py_DECREF(b);
2827 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002828}
2829
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002830
2831/* Bitwise and/xor/or operations */
2832
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002833static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002834long_bitwise(PyLongObject *a,
2835 int op, /* '&', '|', '^' */
2836 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002837{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002838 digit maska, maskb; /* 0 or MASK */
2839 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002840 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002841 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002842 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00002843 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002844 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002845
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002846 if (a->ob_size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002847 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00002848 if (a == NULL)
2849 return NULL;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002850 maska = MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002851 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002852 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002853 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002854 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00002855 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002856 if (b->ob_size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002857 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00002858 if (b == NULL) {
2859 Py_DECREF(a);
2860 return NULL;
2861 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002862 maskb = MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002863 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002864 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002865 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002866 maskb = 0;
2867 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002868
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002869 negz = 0;
2870 switch (op) {
2871 case '^':
2872 if (maska != maskb) {
2873 maska ^= MASK;
2874 negz = -1;
2875 }
2876 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002877 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002878 if (maska && maskb) {
2879 op = '|';
2880 maska ^= MASK;
2881 maskb ^= MASK;
2882 negz = -1;
2883 }
2884 break;
2885 case '|':
2886 if (maska || maskb) {
2887 op = '&';
2888 maska ^= MASK;
2889 maskb ^= MASK;
2890 negz = -1;
2891 }
2892 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002893 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002894
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002895 /* JRH: The original logic here was to allocate the result value (z)
2896 as the longer of the two operands. However, there are some cases
2897 where the result is guaranteed to be shorter than that: AND of two
2898 positives, OR of two negatives: use the shorter number. AND with
2899 mixed signs: use the positive number. OR with mixed signs: use the
2900 negative number. After the transformations above, op will be '&'
2901 iff one of these cases applies, and mask will be non-0 for operands
2902 whose length should be ignored.
2903 */
2904
2905 size_a = a->ob_size;
2906 size_b = b->ob_size;
2907 size_z = op == '&'
2908 ? (maska
2909 ? size_b
2910 : (maskb ? size_a : MIN(size_a, size_b)))
2911 : MAX(size_a, size_b);
2912 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00002913 if (z == NULL) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002914 Py_XDECREF(a);
2915 Py_XDECREF(b);
2916 Py_XDECREF(z);
2917 return NULL;
2918 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002919
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002920 for (i = 0; i < size_z; ++i) {
2921 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
2922 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
2923 switch (op) {
2924 case '&': z->ob_digit[i] = diga & digb; break;
2925 case '|': z->ob_digit[i] = diga | digb; break;
2926 case '^': z->ob_digit[i] = diga ^ digb; break;
2927 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00002928 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002929
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002930 Py_DECREF(a);
2931 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002932 z = long_normalize(z);
2933 if (negz == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002934 return (PyObject *) z;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002935 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002936 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002937 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002938}
2939
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002940static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002941long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002942{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002943 PyLongObject *a, *b;
2944 PyObject *c;
2945 CONVERT_BINOP(v, w, &a, &b);
2946 c = long_bitwise(a, '&', b);
2947 Py_DECREF(a);
2948 Py_DECREF(b);
2949 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002950}
2951
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002952static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002953long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002954{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002955 PyLongObject *a, *b;
2956 PyObject *c;
2957 CONVERT_BINOP(v, w, &a, &b);
2958 c = long_bitwise(a, '^', b);
2959 Py_DECREF(a);
2960 Py_DECREF(b);
2961 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002962}
2963
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002964static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002965long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002966{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002967 PyLongObject *a, *b;
2968 PyObject *c;
2969 CONVERT_BINOP(v, w, &a, &b);
2970 c = long_bitwise(a, '|', b);
2971 Py_DECREF(a);
2972 Py_DECREF(b);
2973 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002974}
2975
Guido van Rossum234f9421993-06-17 12:35:49 +00002976static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002977long_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00002978{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002979 if (PyInt_Check(*pw)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00002980 *pw = PyLong_FromLong(PyInt_AS_LONG(*pw));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002981 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00002982 return 0;
2983 }
Guido van Rossum1952e382001-09-19 01:25:16 +00002984 else if (PyLong_Check(*pw)) {
2985 Py_INCREF(*pv);
2986 Py_INCREF(*pw);
2987 return 0;
2988 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00002989 return 1; /* Can't do it */
2990}
2991
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002992static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002993long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00002994{
Brett Cannonc3647ac2005-04-26 03:45:26 +00002995 if (PyLong_CheckExact(v))
2996 Py_INCREF(v);
2997 else
2998 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00002999 return v;
3000}
3001
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003002static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00003003long_int(PyObject *v)
3004{
3005 long x;
3006 x = PyLong_AsLong(v);
3007 if (PyErr_Occurred()) {
3008 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
3009 PyErr_Clear();
3010 if (PyLong_CheckExact(v)) {
3011 Py_INCREF(v);
3012 return v;
3013 }
3014 else
3015 return _PyLong_Copy((PyLongObject *)v);
3016 }
3017 else
3018 return NULL;
3019 }
3020 return PyInt_FromLong(x);
3021}
3022
3023static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003024long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003025{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003026 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003027 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003028 if (result == -1.0 && PyErr_Occurred())
3029 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003030 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003031}
3032
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003033static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003034long_oct(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003035{
Fred Drake121ee271999-12-23 15:41:28 +00003036 return long_format(v, 8, 1);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003037}
3038
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003039static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003040long_hex(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003041{
Fred Drake121ee271999-12-23 15:41:28 +00003042 return long_format(v, 16, 1);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003043}
Jeremy Hylton938ace62002-07-17 16:30:39 +00003044
3045static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003046long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003047
Tim Peters6d6c1a32001-08-02 04:15:00 +00003048static PyObject *
3049long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3050{
3051 PyObject *x = NULL;
3052 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003053 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003054
Guido van Rossumbef14172001-08-29 15:47:46 +00003055 if (type != &PyLong_Type)
3056 return long_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003057 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist,
3058 &x, &base))
3059 return NULL;
3060 if (x == NULL)
3061 return PyLong_FromLong(0L);
3062 if (base == -909)
3063 return PyNumber_Long(x);
3064 else if (PyString_Check(x))
3065 return PyLong_FromString(PyString_AS_STRING(x), NULL, base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003066#ifdef Py_USING_UNICODE
Tim Peters6d6c1a32001-08-02 04:15:00 +00003067 else if (PyUnicode_Check(x))
3068 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3069 PyUnicode_GET_SIZE(x),
3070 base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003071#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +00003072 else {
3073 PyErr_SetString(PyExc_TypeError,
3074 "long() can't convert non-string with explicit base");
3075 return NULL;
3076 }
3077}
3078
Guido van Rossumbef14172001-08-29 15:47:46 +00003079/* Wimpy, slow approach to tp_new calls for subtypes of long:
3080 first create a regular long from whatever arguments we got,
3081 then allocate a subtype instance and initialize it from
3082 the regular long. The regular long is then thrown away.
3083*/
3084static PyObject *
3085long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3086{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003087 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003088 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003089
3090 assert(PyType_IsSubtype(type, &PyLong_Type));
3091 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3092 if (tmp == NULL)
3093 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003094 assert(PyLong_CheckExact(tmp));
Guido van Rossumbef14172001-08-29 15:47:46 +00003095 n = tmp->ob_size;
3096 if (n < 0)
3097 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003098 newobj = (PyLongObject *)type->tp_alloc(type, n);
3099 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003100 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003101 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003102 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003103 assert(PyLong_Check(newobj));
3104 newobj->ob_size = tmp->ob_size;
Guido van Rossumbef14172001-08-29 15:47:46 +00003105 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003106 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003107 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003108 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003109}
3110
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003111static PyObject *
3112long_getnewargs(PyLongObject *v)
3113{
3114 return Py_BuildValue("(N)", _PyLong_Copy(v));
3115}
3116
3117static PyMethodDef long_methods[] = {
3118 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
3119 {NULL, NULL} /* sentinel */
3120};
3121
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003122PyDoc_STRVAR(long_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003123"long(x[, base]) -> integer\n\
3124\n\
3125Convert a string or number to a long integer, if possible. A floating\n\
3126point argument will be truncated towards zero (this does not include a\n\
3127string representation of a floating point number!) When converting a\n\
3128string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003129converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003130
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003131static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003132 (binaryfunc) long_add, /*nb_add*/
3133 (binaryfunc) long_sub, /*nb_subtract*/
3134 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003135 long_mod, /*nb_remainder*/
3136 long_divmod, /*nb_divmod*/
3137 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003138 (unaryfunc) long_neg, /*nb_negative*/
3139 (unaryfunc) long_pos, /*tp_positive*/
3140 (unaryfunc) long_abs, /*tp_absolute*/
3141 (inquiry) long_nonzero, /*tp_nonzero*/
3142 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003143 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003144 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003145 long_and, /*nb_and*/
3146 long_xor, /*nb_xor*/
3147 long_or, /*nb_or*/
3148 long_coerce, /*nb_coerce*/
3149 long_int, /*nb_int*/
3150 long_long, /*nb_long*/
3151 long_float, /*nb_float*/
3152 long_oct, /*nb_oct*/
3153 long_hex, /*nb_hex*/
Guido van Rossum4668b002001-08-08 05:00:18 +00003154 0, /* nb_inplace_add */
3155 0, /* nb_inplace_subtract */
3156 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00003157 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 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003164 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003165 long_true_divide, /* nb_true_divide */
3166 0, /* nb_inplace_floor_divide */
3167 0, /* nb_inplace_true_divide */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003168 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 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003177 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003178 0, /* tp_print */
3179 0, /* tp_getattr */
3180 0, /* tp_setattr */
3181 (cmpfunc)long_compare, /* tp_compare */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003182 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003183 &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 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003188 long_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003189 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};