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